@swirls/looms 0.13.0 → 0.13.2

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # @swirls/looms
2
2
 
3
+ ## 0.13.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 06942de: An in-process effect whose attempts keep being lost now fails instead of being re-attempted without limit. When a wake finds an attempt that an earlier wake started and never finished, because its process was lost or the wake failed, it still starts the next attempt, but only while attempts remain: up to the effect's `maxAttempts`, or three attempts when the effect has no retry policy. After that the effect fails with `attempt N was lost before it finished, and no attempts remain`. Attempts ended by a signal in the same wake, such as steering an agent, are not treated as lost.
8
+
9
+ ## 0.13.1
10
+
11
+ ### Patch Changes
12
+
13
+ - ab05943: A run on a Durable Object now recovers by itself when its isolate is lost while an in-process effect is running. Until now such a run had no alarm, so after an eviction, deploy, or crash mid-effect it stayed `running` until something signalled it. While a wake waits on in-process effects it now keeps the object's alarm about 30 seconds ahead and renews it; if the isolate goes away the alarm fires in a new one, the run wakes, and the effect is re-attempted as it already is on any later wake. `WakeScheduler` gains an optional `keepAlive` for hosts whose wakes outlive the process, and `livenessLeaseMs` sets the interval. Schedulers without `keepAlive`, including the default in-process one, behave as before.
14
+
3
15
  ## 0.13.0
4
16
 
5
17
  ### Minor Changes
@@ -9,6 +9,8 @@ export interface ActorCellOptions<TModules extends readonly AnyRuntimeModule[] =
9
9
  readonly definitionResolver?: DefinitionResolver;
10
10
  readonly snapshotEvery?: number;
11
11
  readonly maxWakeIterations?: number;
12
+ /** See `CreateRuntimeOptions.livenessLeaseMs`. */
13
+ readonly livenessLeaseMs?: number;
12
14
  readonly maxPendingRunOperations?: number;
13
15
  readonly snapshotStore?: SnapshotStore;
14
16
  readonly trimAfterSnapshot?: {
@@ -17,6 +17,7 @@ export function createActorCell(options) {
17
17
  worker: options.worker,
18
18
  snapshotEvery: options.snapshotEvery,
19
19
  maxWakeIterations: options.maxWakeIterations,
20
+ livenessLeaseMs: options.livenessLeaseMs,
20
21
  maxPendingRunOperations: options.maxPendingRunOperations,
21
22
  snapshotStore: options.snapshotStore,
22
23
  trimAfterSnapshot: options.trimAfterSnapshot,
@@ -10,10 +10,19 @@ export interface DurableObjectAlarms {
10
10
  readonly scheduler: WakeScheduler;
11
11
  /** Ensures the alarm fires no later than `at` without forgetting the runtime deadline. */
12
12
  readonly scheduleAtEarliest: (at: number) => Effect.Effect<void>;
13
+ /**
14
+ * Run when the alarm fires, before waking. A runtime deadline that is already due is being
15
+ * delivered by this alarm, so it is forgotten instead of being set again by a later rearm.
16
+ */
17
+ readonly fired: Effect.Effect<void>;
13
18
  }
14
19
  /**
15
20
  * The single owner of a Durable Object's one alarm. Every write is serialized and sets the alarm to
16
- * the earliest of the runtime deadline, `additionalDeadline` (such as projector retries), and the
17
- * requested time, so concurrent writers cannot overwrite each other's deadlines.
21
+ * the earliest of the runtime deadline, the liveness deadline of a wake with in-process effects in
22
+ * flight, `additionalDeadline` (such as projector retries), and the requested time, so concurrent
23
+ * writers cannot overwrite each other's deadlines.
24
+ *
25
+ * The liveness deadline is what recovers a run whose isolate is lost mid-effect: the live wake
26
+ * keeps pushing it forward, and once nothing does it fires in a fresh isolate, which wakes the run.
18
27
  */
19
28
  export declare function durableObjectAlarms(storage: AlarmStorage, additionalDeadline?: () => Effect.Effect<number | null>): DurableObjectAlarms;
@@ -1,16 +1,21 @@
1
- import { Effect, Semaphore } from 'effect';
1
+ import { Clock, Effect, Semaphore } from 'effect';
2
2
  function earliest(...deadlines) {
3
3
  const known = deadlines.filter((deadline) => deadline !== null && deadline !== undefined);
4
4
  return known.length === 0 ? null : Math.min(...known);
5
5
  }
6
6
  /**
7
7
  * The single owner of a Durable Object's one alarm. Every write is serialized and sets the alarm to
8
- * the earliest of the runtime deadline, `additionalDeadline` (such as projector retries), and the
9
- * requested time, so concurrent writers cannot overwrite each other's deadlines.
8
+ * the earliest of the runtime deadline, the liveness deadline of a wake with in-process effects in
9
+ * flight, `additionalDeadline` (such as projector retries), and the requested time, so concurrent
10
+ * writers cannot overwrite each other's deadlines.
11
+ *
12
+ * The liveness deadline is what recovers a run whose isolate is lost mid-effect: the live wake
13
+ * keeps pushing it forward, and once nothing does it fires in a fresh isolate, which wakes the run.
10
14
  */
11
15
  export function durableObjectAlarms(storage, additionalDeadline) {
12
16
  // `undefined` until the runtime reports a deadline; until then an existing alarm is preserved.
13
17
  let runtimeDeadline;
18
+ let livenessDeadline = null;
14
19
  const writes = Semaphore.makeUnsafe(1);
15
20
  const rearm = (requested) => Semaphore.withPermits(writes, 1, Effect.gen(function* () {
16
21
  const [additional, current] = yield* Effect.all([
@@ -18,7 +23,7 @@ export function durableObjectAlarms(storage, additionalDeadline) {
18
23
  Effect.promise(() => storage.getAlarm?.() ?? Promise.resolve(null)),
19
24
  ], { concurrency: 'unbounded' });
20
25
  const preserved = runtimeDeadline === undefined ? current : null;
21
- const desired = earliest(runtimeDeadline, additional, requested, preserved);
26
+ const desired = earliest(runtimeDeadline, livenessDeadline, additional, requested, preserved);
22
27
  if (desired === current) {
23
28
  return;
24
29
  }
@@ -34,7 +39,16 @@ export function durableObjectAlarms(storage, additionalDeadline) {
34
39
  runtimeDeadline = null;
35
40
  return rearm(null);
36
41
  }),
42
+ keepAlive: (_runId, until) => Effect.suspend(() => {
43
+ livenessDeadline = until;
44
+ return rearm(null);
45
+ }),
37
46
  },
38
47
  scheduleAtEarliest: rearm,
48
+ fired: Clock.currentTimeMillis.pipe(Effect.map((now) => {
49
+ if (runtimeDeadline !== undefined && runtimeDeadline !== null && runtimeDeadline <= now) {
50
+ runtimeDeadline = null;
51
+ }
52
+ })),
39
53
  };
40
54
  }
@@ -14,6 +14,11 @@ export interface LoomsDurableObjectConfig {
14
14
  readonly blobs?: BlobStore;
15
15
  readonly snapshotEvery?: number;
16
16
  readonly maxWakeIterations?: number;
17
+ /**
18
+ * How far ahead the alarm is kept while in-process effects run, in milliseconds. If the isolate
19
+ * is lost mid-effect the run wakes and re-attempts within about this long. Default 30000.
20
+ */
21
+ readonly livenessLeaseMs?: number;
17
22
  readonly maxPendingRunOperations?: number;
18
23
  readonly trimAfterSnapshot?: {
19
24
  readonly keepSnapshots: number;
@@ -41,6 +46,7 @@ export interface LoomsDurableObjectConfig {
41
46
  export declare abstract class LoomsDurableObject<Env = unknown> extends DurableObject<Env> {
42
47
  private cellPromise?;
43
48
  private store?;
49
+ private alarms?;
44
50
  private authorize;
45
51
  abstract configure(env: Env): LoomsDurableObjectConfig | Promise<LoomsDurableObjectConfig>;
46
52
  private getCell;
@@ -15,6 +15,7 @@ import { attachSocketFanout, isRunSocketUpgrade, openRunSocket } from './websock
15
15
  export class LoomsDurableObject extends DurableObject {
16
16
  cellPromise;
17
17
  store;
18
+ alarms;
18
19
  authorize = defaultAuthorize;
19
20
  getCell() {
20
21
  if (this.cellPromise) {
@@ -44,6 +45,7 @@ export class LoomsDurableObject extends DurableObject {
44
45
  blobs: config.blobs,
45
46
  });
46
47
  this.store = store;
48
+ this.alarms = alarms;
47
49
  this.authorize = config.authorize ?? defaultAuthorize;
48
50
  const cell = createActorCell({
49
51
  runId,
@@ -54,6 +56,7 @@ export class LoomsDurableObject extends DurableObject {
54
56
  attributes: config.attributes,
55
57
  snapshotEvery: config.snapshotEvery,
56
58
  maxWakeIterations: config.maxWakeIterations,
59
+ livenessLeaseMs: config.livenessLeaseMs,
57
60
  maxPendingRunOperations: config.maxPendingRunOperations,
58
61
  trimAfterSnapshot: config.trimAfterSnapshot,
59
62
  authorize: config.authorize,
@@ -142,6 +145,7 @@ export class LoomsDurableObject extends DurableObject {
142
145
  return cell.getRun().then((state) => deleteTerminalRunStorage(this.ctx.storage, store, runId, state, options).then(() => {
143
146
  this.cellPromise = undefined;
144
147
  this.store = undefined;
148
+ this.alarms = undefined;
145
149
  }));
146
150
  });
147
151
  }
@@ -157,7 +161,9 @@ export class LoomsDurableObject extends DurableObject {
157
161
  if (delivery) {
158
162
  this.ctx.waitUntil(Effect.runPromise(delivery.deliver(runId)));
159
163
  }
160
- return cell.wake();
164
+ // Otherwise a wake still running here would keep rearming for the deadline that just
165
+ // fired, alongside its liveness deadline, and the alarm would fire again at once.
166
+ return Effect.runPromise(this.alarms?.fired ?? Effect.void).then(() => cell.wake());
161
167
  })
162
168
  .then(() => undefined);
163
169
  }
@@ -21,6 +21,8 @@ export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttri
21
21
  hostname?: string;
22
22
  };
23
23
  readonly maxWakeIterations?: number;
24
+ /** See `CreateRuntimeOptions.livenessLeaseMs`. Only used when `scheduler` implements `keepAlive`. */
25
+ readonly livenessLeaseMs?: number;
24
26
  /** Maximum active and queued mutation operations per run. Default 256. */
25
27
  readonly maxPendingRunOperations?: number;
26
28
  /** Durable events between mid-wake snapshots. Default 200; `0` disables. Parking always snapshots. */
@@ -41,6 +41,7 @@ export function createLooms(options = {}) {
41
41
  modules,
42
42
  store,
43
43
  maxWakeIterations: options.maxWakeIterations,
44
+ livenessLeaseMs: options.livenessLeaseMs,
44
45
  maxPendingRunOperations: options.maxPendingRunOperations,
45
46
  snapshotEvery: options.snapshotEvery,
46
47
  snapshotStore: options.blobStore
@@ -253,6 +253,7 @@ export function createRuntime(options) {
253
253
  repository,
254
254
  snapshotEvery,
255
255
  maxWakeIterations,
256
+ livenessLeaseMs: options.livenessLeaseMs,
256
257
  maxInFlightWorkerEffects: options.maxInFlightWorkerEffects,
257
258
  worker: options.worker,
258
259
  observer: options.observer,
@@ -21,6 +21,12 @@ export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule
21
21
  */
22
22
  readonly snapshotEvery?: number;
23
23
  readonly maxWakeIterations?: number;
24
+ /**
25
+ * How far ahead a wake with in-process effects in flight keeps its `WakeScheduler.keepAlive`
26
+ * deadline, in milliseconds. Renewed every third of it. Default 30000. Only used when the
27
+ * scheduler implements `keepAlive`.
28
+ */
29
+ readonly livenessLeaseMs?: number;
24
30
  /** Maximum concurrent in-flight worker effects dispatched per run (fairness guard). */
25
31
  readonly maxInFlightWorkerEffects?: number;
26
32
  /** Maximum active and queued mutation operations per run. Default 256. */
@@ -13,6 +13,7 @@ export interface WakeEngineOptions {
13
13
  readonly repository: RuntimeRepository;
14
14
  readonly snapshotEvery: number;
15
15
  readonly maxWakeIterations: number;
16
+ readonly livenessLeaseMs?: number;
16
17
  readonly maxInFlightWorkerEffects?: number;
17
18
  readonly worker?: EffectWorker;
18
19
  readonly observer?: RuntimeObserver;
@@ -1,14 +1,17 @@
1
1
  import { Clock, Deferred, Effect, Exit, Fiber, Option, Queue, } from 'effect';
2
- import { createEvent, deferredUntil, EventStoreTag, foldRun, isRunTerminal, } from '@swirls/looms/core';
2
+ import { createEvent, deferredUntil, EventStoreTag, foldRun, isPrimitiveEffect, isRunTerminal, } from '@swirls/looms/core';
3
3
  import { childCloseCancellations, notifyLaunchingParent } from './child-run.js';
4
4
  import { nextRuntimeDeadline, planDeadlineTransitions, planTerminalCancellationTransitions, } from './deadline-transition-planner.js';
5
5
  import { admitOrFailAttempt } from './effect-admission.js';
6
6
  import { DuplicateEffectDispatchError, MaxWakeIterationsError, RuntimeExecutionError, } from './errors.js';
7
- import { cascadedCancellations, groupOutstanding, stripSeq, synthesizedThreadFailed, waitSatisfiedEvents, } from './helpers.js';
7
+ import { cascadedCancellations, createEffectFailedEvent, groupOutstanding, stripSeq, synthesizedThreadFailed, waitSatisfiedEvents, } from './helpers.js';
8
8
  import { executeLocalEffects } from './local-effect-executor.js';
9
9
  import { notifyObserver } from './observer.js';
10
10
  import { requestWakeAgain, } from './run-execution-context.js';
11
11
  import { dispatchWorkerEffect, isWorkerEffect, planWorkerEffects } from './worker-effect-dispatch.js';
12
+ const DEFAULT_LIVENESS_LEASE_MS = 30_000;
13
+ /** Attempts allowed for an effect with no retry policy when its attempts keep being lost. */
14
+ const DEFAULT_LOST_ATTEMPT_LIMIT = 3;
12
15
  function currentTimeMillis() {
13
16
  return Math.floor(performance.timeOrigin + performance.now());
14
17
  }
@@ -20,6 +23,8 @@ export function createWakeEngine(options) {
20
23
  set: repository.setCachedCursor,
21
24
  };
22
25
  const observe = (event) => notifyObserver(options.observer, event);
26
+ const livenessLeaseMs = Math.max(1, options.livenessLeaseMs ?? DEFAULT_LIVENESS_LEASE_MS);
27
+ const livenessRenewMs = Math.max(1, Math.floor(livenessLeaseMs / 3));
23
28
  const closeLaunchedRuns = (store, runId, cursor) => Effect.gen(function* () {
24
29
  let next = cursor;
25
30
  const state = next.state;
@@ -74,6 +79,37 @@ export function createWakeEngine(options) {
74
79
  executionContext.resolveWakeCompletion = resolveCompletion;
75
80
  executionContext.waking = true;
76
81
  let released = false;
82
+ // `effectId:attempt` of every attempt this wake started, across its passes. An attempt
83
+ // found running that is not here was started by a wake that never finished it.
84
+ const startedByThisWake = new Set();
85
+ // When the liveness deadline is next due for renewal; `null` while this wake holds none.
86
+ let livenessRenewAt = null;
87
+ // In-process effects have no deadline of their own, so nothing would wake the run if this
88
+ // process were lost while they run. Where the scheduler supports it, keep a wake pending a
89
+ // short time ahead for as long as the wake waits on them. Never returns.
90
+ const holdLiveness = Effect.gen(function* () {
91
+ const scheduler = options.scheduler();
92
+ if (!scheduler.keepAlive) {
93
+ return yield* Effect.never;
94
+ }
95
+ while (true) {
96
+ const now = yield* Clock.currentTimeMillis;
97
+ if (livenessRenewAt !== null && now < livenessRenewAt) {
98
+ yield* Effect.sleep(livenessRenewAt - now);
99
+ continue;
100
+ }
101
+ // Claimed before the write so a failed or interrupted write is still cleared on exit.
102
+ livenessRenewAt = now + livenessRenewMs;
103
+ yield* scheduler.keepAlive(runId, now + livenessLeaseMs);
104
+ }
105
+ });
106
+ const releaseLiveness = Effect.suspend(() => {
107
+ if (livenessRenewAt === null) {
108
+ return Effect.void;
109
+ }
110
+ livenessRenewAt = null;
111
+ return options.scheduler().keepAlive?.(runId, null) ?? Effect.void;
112
+ });
77
113
  const releaseWake = () => {
78
114
  released = true;
79
115
  executionContext.waking = false;
@@ -288,11 +324,35 @@ export function createWakeEngine(options) {
288
324
  }
289
325
  return yield* new DuplicateEffectDispatchError(runId, item.effectId, item.threadId);
290
326
  }
327
+ // An attempt left running by a wake that is gone (its process was lost, or the wake
328
+ // failed) is re-attempted below. That counts against the effect's attempts, so an
329
+ // effect that takes its process down every time fails instead of repeating forever.
330
+ const exhausted = outstanding.flatMap((item) => {
331
+ const execution = state.effectExecutions[item.effectId];
332
+ if (execution?.status !== 'running' ||
333
+ isPrimitiveEffect(item.effect) ||
334
+ startedByThisWake.has(`${item.effectId}:${execution.attempt}`)) {
335
+ return [];
336
+ }
337
+ const limit = registry.effects.get(item.effect.type)?.retry?.maxAttempts ??
338
+ DEFAULT_LOST_ATTEMPT_LIMIT;
339
+ return execution.attempt >= limit
340
+ ? [
341
+ createEffectFailedEvent(runId, item, `attempt ${execution.attempt} was lost before it finished, and no attempts remain`),
342
+ ]
343
+ : [];
344
+ });
345
+ if (exhausted.length > 0) {
346
+ yield* foldProduced(exhausted);
347
+ continue;
348
+ }
291
349
  const due = outstanding.filter((item) => !dispatchedEffectIds.has(dispatchKeyFor(item)));
292
350
  if (due.length > 0) {
293
351
  const attempts = new Map(due.map((item) => [item.effectId, attemptFor(item)]));
294
352
  for (const item of due) {
295
- dispatchedEffectIds.add(`${item.effectId}:${attempts.get(item.effectId) ?? 1}`);
353
+ const key = `${item.effectId}:${attempts.get(item.effectId) ?? 1}`;
354
+ dispatchedEffectIds.add(key);
355
+ startedByThisWake.add(key);
296
356
  }
297
357
  const attemptEvents = due.map((item) => createEvent(runId, {
298
358
  type: 'runtime.effect.attempt.started',
@@ -361,11 +421,16 @@ export function createWakeEngine(options) {
361
421
  if (executionContext.wakeAgain) {
362
422
  Deferred.doneUnsafe(wakeGate, Effect.void);
363
423
  }
364
- const progress = yield* Effect.raceFirst(Queue.take(settled).pipe(Effect.map((item) => ({ _tag: 'settled', ...item }))), Deferred.await(wakeGate).pipe(Effect.as({ _tag: 'wake' })));
424
+ const progress = yield* Effect.raceFirst(Effect.raceFirst(Queue.take(settled).pipe(Effect.map((item) => ({ _tag: 'settled', ...item }))), Deferred.await(wakeGate).pipe(Effect.as({ _tag: 'wake' }))), holdLiveness);
365
425
  if (executionContext.wakeSignal === wakeGate) {
366
426
  executionContext.wakeSignal = null;
367
427
  }
368
428
  if (progress._tag === 'wake') {
429
+ // A joined wake may be the host's pending wake firing, which uses it up. Ask again
430
+ // on the next wait instead of at the next renewal.
431
+ if (livenessRenewAt !== null) {
432
+ livenessRenewAt = Number.NEGATIVE_INFINITY;
433
+ }
369
434
  continue;
370
435
  }
371
436
  inFlight.delete(progress.groupKey);
@@ -453,7 +518,10 @@ export function createWakeEngine(options) {
453
518
  return yield* new RuntimeExecutionError(`Wake for run "${runId}" completed without state`);
454
519
  }
455
520
  return finalState;
456
- }).pipe(Effect.onExit((exit) => Effect.sync(() => {
521
+ }).pipe(
522
+ // Before the claim is released, so a wake that starts next takes a fresh deadline after
523
+ // this one is cleared rather than having its own cleared.
524
+ Effect.onExit(() => releaseLiveness), Effect.onExit((exit) => Effect.sync(() => {
457
525
  if (!released) {
458
526
  releaseWake();
459
527
  }
@@ -2,6 +2,14 @@ import { Effect } from 'effect';
2
2
  export interface WakeScheduler {
3
3
  schedule(runId: string, at: number): Effect.Effect<void>;
4
4
  cancel(runId: string): Effect.Effect<void>;
5
+ /**
6
+ * Optional. While a wake has in-process effects in flight it asks to be woken at `until`, renews
7
+ * that before it passes, and clears it with `null` when the wake ends. Implement it only where
8
+ * the wake outlives the process (a Durable Object alarm): if the process is lost mid-effect the
9
+ * deadline fires elsewhere and the run re-attempts the effect. It must not replace the deadline
10
+ * set through `schedule`; the host wakes at the earlier of the two.
11
+ */
12
+ keepAlive?(runId: string, until: number | null): Effect.Effect<void>;
5
13
  dispose?(): void;
6
14
  }
7
15
  export declare function createTimeoutScheduler(wake: (runId: string) => Effect.Effect<void>): WakeScheduler;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirls/looms",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "description": "Pluggable event-sourced runtime for durable agents and workflows",
5
5
  "homepage": "https://github.com/ByteSliceHQ/looms#readme",
6
6
  "bugs": {