@effect-agent/platform-cloudflare 0.1.0-beta.51 → 0.1.0-beta.53

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/dist/Alarm.d.mts CHANGED
@@ -3,15 +3,15 @@ import { o as CloudflareDurableRuntimeConfig } from "./CloudflareConfig-f3CqTel1
3
3
  import { DurableBindingFailure } from "@effect-agent/thread/AgentRegistration";
4
4
  import { DurableAgentRuntime, DurableWorkerFailure } from "@effect-agent/thread/DurableAgentRuntime";
5
5
  import { SubmissionLedger } from "@effect-agent/thread/SubmissionLedger";
6
- import { Context, Effect, Layer, Option, Schema } from "effect";
6
+ import { Cause, Context, Effect, Layer, Option, Schema } from "effect";
7
7
  declare namespace Alarm_d_exports {
8
- export { DurableAlarmError, DurableAlarmService, MaintenancePassFailure, MaintenancePassReport, ThreadMaintenance, ThreadMaintenanceFailpoint, ThreadMaintenanceFailpointHandler, ThreadMaintenanceFailpointLocation };
8
+ export { DurableAlarmError, DurableAlarmService, MaintenancePassFailure, MaintenancePassReport, ThreadMaintenance, ThreadMaintenanceFailpoint, ThreadMaintenanceFailpointHandler, ThreadMaintenanceFailpointLocation, ThreadMutationGate, ThreadPublication, ThreadPublicationService, publishCommitted };
9
9
  }
10
10
  declare const DurableAlarmError_base: Schema.Class<DurableAlarmError, Schema.TaggedStruct<"DurableAlarmError", {
11
11
  readonly operation: Schema.String;
12
12
  readonly message: Schema.String;
13
13
  readonly cause: Schema.optionalKey<Schema.Defect>;
14
- }>, import("effect/Cause").YieldableError>;
14
+ }>, Cause.YieldableError>;
15
15
  /**
16
16
  * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
17
17
  * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
@@ -59,7 +59,7 @@ declare class DurableAlarmService extends DurableAlarmService_base {
59
59
  static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext>;
60
60
  }
61
61
  declare const MaintenancePassReport_base: Schema.Class<MaintenancePassReport, Schema.Struct<{
62
- /** `caught-up` is generation-only; `actionable` ran recovery and at most one head Attempt. */
62
+ /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
63
63
  readonly phase: Schema.Literals<readonly ["caught-up", "actionable"]>;
64
64
  /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
65
65
  readonly recovered: Schema.Int;
@@ -82,6 +82,45 @@ declare const ThreadMaintenanceFailpoint_base: Context.ServiceClass<ThreadMainte
82
82
  declare class ThreadMaintenanceFailpoint extends ThreadMaintenanceFailpoint_base {
83
83
  static readonly layer: Layer.Layer<ThreadMaintenanceFailpoint, never, never>;
84
84
  }
85
+ /**
86
+ * Durable host publication of canonical records and ledger approval/abort/resolution intents.
87
+ * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery
88
+ * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.
89
+ *
90
+ * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.
91
+ * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated
92
+ * calls must preserve partial scan progress. It runs with no source mutation in flight.
93
+ * `drain` performs bounded delivery and persists retries before returning. A pending deadline
94
+ * defers runtime recovery/Attempts, allowing committed host publications to drain first.
95
+ * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call
96
+ * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need
97
+ * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.
98
+ */
99
+ interface ThreadPublicationService {
100
+ readonly invalidate: Effect.Effect<void, DurableAlarmError>;
101
+ readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;
102
+ readonly drain: Effect.Effect<void, DurableAlarmError>;
103
+ readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
104
+ }
105
+ declare const ThreadPublication_base: Context.ServiceClass<ThreadPublication, "@effect-agent/platform-cloudflare/ThreadPublication", ThreadPublicationService>;
106
+ /** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
107
+ declare class ThreadPublication extends ThreadPublication_base {
108
+ static readonly layer: Layer.Layer<ThreadPublication, never, never>;
109
+ }
110
+ /** @internal A committed source operation must not become a failed operation because delivery failed. */
111
+ declare const publishCommitted: Effect.Effect<void, never, ThreadPublication>;
112
+ declare const ThreadMutationGate_base: Context.ServiceClass<ThreadMutationGate, "@effect-agent/platform-cloudflare/internal/ThreadMutationGate", {
113
+ readonly withMutation: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | DurableAlarmError, R>;
114
+ readonly withSnapshot: <A, E, R>(body: (active: number) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
115
+ }>;
116
+ /**
117
+ * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
118
+ * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
119
+ * Layers must reuse that instance; a second gate cannot observe the native producers' activity.
120
+ */
121
+ declare class ThreadMutationGate extends ThreadMutationGate_base {
122
+ static readonly layer: Layer.Layer<ThreadMutationGate, never, CloudflareDurableRuntimeConfig | DurableObjectContext | ThreadMaintenanceFailpoint>;
123
+ }
85
124
  type MaintenancePassFailure = DurableWorkerFailure | DurableBindingFailure | DurableAlarmError;
86
125
  declare const ThreadMaintenance_base: Context.ServiceClass<ThreadMaintenance, "@effect-agent/platform-cloudflare/ThreadMaintenance", {
87
126
  /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */
@@ -113,8 +152,8 @@ declare const ThreadMaintenance_base: Context.ServiceClass<ThreadMaintenance, "@
113
152
  * recovery states leave their generation dirty and retain bounded backoff rearming.
114
153
  */
115
154
  declare class ThreadMaintenance extends ThreadMaintenance_base {
116
- static readonly layer: Layer.Layer<ThreadMaintenance, never, DurableAgentRuntime | SubmissionLedger | DurableAlarmService | ThreadMaintenanceFailpoint | CloudflareDurableRuntimeConfig | ThreadObjectIdentity | DurableObjectContext>;
155
+ static readonly layer: Layer.Layer<ThreadMaintenance, never, ThreadMutationGate | ThreadPublication | DurableAgentRuntime | SubmissionLedger | DurableAlarmService | ThreadMaintenanceFailpoint | CloudflareDurableRuntimeConfig | ThreadObjectIdentity | DurableObjectContext>;
117
156
  }
118
157
  //#endregion
119
- export { DurableAlarmError, DurableAlarmService, MaintenancePassFailure, MaintenancePassReport, ThreadMaintenance, ThreadMaintenanceFailpoint, ThreadMaintenanceFailpointHandler, ThreadMaintenanceFailpointLocation, Alarm_d_exports as t };
158
+ export { DurableAlarmError, DurableAlarmService, MaintenancePassFailure, MaintenancePassReport, ThreadMaintenance, ThreadMaintenanceFailpoint, ThreadMaintenanceFailpointHandler, ThreadMaintenanceFailpointLocation, ThreadMutationGate, ThreadPublication, ThreadPublicationService, publishCommitted, Alarm_d_exports as t };
120
159
  //# sourceMappingURL=Alarm.d.mts.map
package/dist/Alarm.mjs CHANGED
@@ -5,14 +5,17 @@ import { r as safeCauseMessage } from "./boundary-BguazVkh.mjs";
5
5
  import "@effect-agent/thread/AgentRegistration";
6
6
  import { DurableAgentRuntime } from "@effect-agent/thread/DurableAgentRuntime";
7
7
  import { SubmissionLedger } from "@effect-agent/thread/SubmissionLedger";
8
- import { Clock, Context, DateTime, Effect, Layer, Option, Random, Ref, Schema, Semaphore, Stream } from "effect";
8
+ import { Cause, Clock, Context, DateTime, Effect, Layer, Option, Random, Ref, Schema, Semaphore, Stream } from "effect";
9
9
  //#region src/Alarm.ts
10
10
  var Alarm_exports = /* @__PURE__ */ __exportAll({
11
11
  DurableAlarmError: () => DurableAlarmError,
12
12
  DurableAlarmService: () => DurableAlarmService,
13
13
  MaintenancePassReport: () => MaintenancePassReport,
14
14
  ThreadMaintenance: () => ThreadMaintenance,
15
- ThreadMaintenanceFailpoint: () => ThreadMaintenanceFailpoint
15
+ ThreadMaintenanceFailpoint: () => ThreadMaintenanceFailpoint,
16
+ ThreadMutationGate: () => ThreadMutationGate,
17
+ ThreadPublication: () => ThreadPublication,
18
+ publishCommitted: () => publishCommitted
16
19
  });
17
20
  /**
18
21
  * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
@@ -74,7 +77,7 @@ var DurableAlarmService = class DurableAlarmService extends Context.Service()("@
74
77
  };
75
78
  /** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
76
79
  var MaintenancePassReport = class extends Schema.Class("@effect-agent/platform-cloudflare/MaintenancePassReport")({
77
- /** `caught-up` is generation-only; `actionable` ran recovery and at most one head Attempt. */
80
+ /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
78
81
  phase: Schema.Literals(["caught-up", "actionable"]),
79
82
  /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
80
83
  recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
@@ -89,6 +92,20 @@ var MaintenancePassReport = class extends Schema.Class("@effect-agent/platform-c
89
92
  var ThreadMaintenanceFailpoint = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint") {
90
93
  static layer = Layer.succeed(this)({ hit: () => Effect.void });
91
94
  };
95
+ /** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
96
+ var ThreadPublication = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadPublication") {
97
+ static layer = Layer.succeed(this)({
98
+ invalidate: Effect.void,
99
+ prepareGeneration: () => Effect.void,
100
+ drain: Effect.void,
101
+ pendingDeadline: Effect.succeed(Option.none())
102
+ });
103
+ };
104
+ /** @internal A committed source operation must not become a failed operation because delivery failed. */
105
+ const publishCommitted = Effect.gen(function* () {
106
+ const publication = yield* ThreadPublication;
107
+ yield* publication.invalidate.pipe(Effect.andThen(publication.drain));
108
+ }).pipe(Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.logError("Thread publication deferred after source commit", cause)));
92
109
  const MaintenanceGeneration = Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(0n));
93
110
  /** Versioned, platform-private maintenance state stored through Durable Object KV. */
94
111
  var ThreadMaintenanceState = class extends Schema.Class("@effect-agent/platform-cloudflare/ThreadMaintenanceState")({
@@ -137,6 +154,46 @@ const stableExternalWait = (snapshot, reports) => {
137
154
  }
138
155
  };
139
156
  /**
157
+ * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
158
+ * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
159
+ * Layers must reuse that instance; a second gate cannot observe the native producers' activity.
160
+ */
161
+ var ThreadMutationGate = class ThreadMutationGate extends Context.Service()("@effect-agent/platform-cloudflare/internal/ThreadMutationGate") {
162
+ static layer = Layer.effect(this)(Effect.gen(function* () {
163
+ const { ctx } = yield* DurableObjectContext;
164
+ const config = yield* CloudflareDurableRuntimeConfig;
165
+ const failpoint = yield* ThreadMaintenanceFailpoint;
166
+ const activeMutations = yield* Ref.make(0);
167
+ const generationGate = yield* Semaphore.make(1);
168
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
169
+ const runTransaction = (operation, transaction) => Effect.tryPromise({
170
+ try: transaction,
171
+ catch: alarmFailure(operation)
172
+ });
173
+ const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* () {
174
+ yield* failpoint.hit("maintenance:dirty:before");
175
+ const now = yield* Clock.currentTimeMillis;
176
+ yield* runTransaction("advance maintenance generation", () => ctx.storage.transaction(async (transaction) => {
177
+ const { state } = await readMaintenanceState(transaction);
178
+ const next = ThreadMaintenanceState.make({
179
+ ...state,
180
+ dirty: state.dirty + 1n
181
+ });
182
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
183
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
184
+ }));
185
+ yield* failpoint.hit("maintenance:dirty:after");
186
+ yield* Ref.update(activeMutations, (active) => active + 1);
187
+ });
188
+ const endMutation = generationGate.withPermit(Ref.update(activeMutations, (active) => Math.max(0, active - 1)));
189
+ const withMutation = (body) => Effect.acquireUseRelease(generationGate.withPermit(beginMutation()), () => failpoint.hit("maintenance:mutation:armed").pipe(Effect.andThen(body), Effect.tap(() => failpoint.hit("maintenance:mutation:finished"))), () => endMutation);
190
+ return ThreadMutationGate.of({
191
+ withMutation,
192
+ withSnapshot: (body) => generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body))
193
+ });
194
+ }));
195
+ };
196
+ /**
140
197
  * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
141
198
  *
142
199
  * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:
@@ -164,37 +221,14 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
164
221
  * restarts at zero and merely re-arms sooner than a long-lived one would have.
165
222
  */
166
223
  const stalls = yield* Ref.make(0);
167
- /**
168
- * Incarnation-local mutation count guarded with the generation transactions below. It is
169
- * deliberately not durable: after eviction every begun mutation has stopped, while its
170
- * pre-armed dirty generation remains durable for recovery. The short gate never spans the
171
- * caller's mutation or cross-Object I/O.
172
- */
173
- const activeMutations = yield* Ref.make(0);
174
- const generationGate = yield* Semaphore.make(1);
224
+ const mutations = yield* ThreadMutationGate;
225
+ const publication = yield* ThreadPublication;
175
226
  const maintenancePassGate = yield* Semaphore.make(1);
176
227
  const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
177
228
  const runTransaction = (operation, transaction) => Effect.tryPromise({
178
229
  try: transaction,
179
230
  catch: alarmFailure(operation)
180
231
  });
181
- const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* () {
182
- yield* failpoint.hit("maintenance:dirty:before");
183
- const now = yield* Clock.currentTimeMillis;
184
- yield* runTransaction("advance maintenance generation", () => ctx.storage.transaction(async (transaction) => {
185
- const { state } = await readMaintenanceState(transaction);
186
- const next = ThreadMaintenanceState.make({
187
- ...state,
188
- dirty: state.dirty + 1n
189
- });
190
- await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
191
- await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
192
- }));
193
- yield* failpoint.hit("maintenance:dirty:after");
194
- yield* Ref.update(activeMutations, (active) => active + 1);
195
- });
196
- const endMutation = generationGate.withPermit(Ref.update(activeMutations, (active) => Math.max(0, active - 1)));
197
- const withMutation = (body) => Effect.acquireUseRelease(generationGate.withPermit(beginMutation()), () => failpoint.hit("maintenance:mutation:armed").pipe(Effect.andThen(body), Effect.tap(() => failpoint.hit("maintenance:mutation:finished"))), () => endMutation);
198
232
  const ensureAlarm = Effect.fn("ThreadMaintenance.ensureAlarm")(function* () {
199
233
  yield* failpoint.hit("maintenance:ensure:before");
200
234
  const now = yield* Clock.currentTimeMillis;
@@ -203,6 +237,8 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
203
237
  if (!initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
204
238
  if (state.dirty > state.processed) await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);
205
239
  }));
240
+ const deadline = yield* publication.pendingDeadline;
241
+ if (Option.isSome(deadline)) yield* runTransaction("ensure publication alarm", () => ctx.storage.transaction((transaction) => ensureTransactionAlarmBy(transaction, Math.max(now + minimumAlarmDelay, deadline.value))));
206
242
  yield* failpoint.hit("maintenance:ensure:after");
207
243
  });
208
244
  const beginPass = Effect.fn("ThreadMaintenance.beginPass")(function* () {
@@ -212,7 +248,7 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
212
248
  const { state, initialized } = await readMaintenanceState(transaction);
213
249
  if (!initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
214
250
  if (state.processed >= state.dirty) {
215
- await transaction.deleteAlarm();
251
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
216
252
  return {
217
253
  _tag: "CaughtUp",
218
254
  nonterminal: state.nonterminal
@@ -221,7 +257,8 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
221
257
  await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
222
258
  return {
223
259
  _tag: "Actionable",
224
- generation: state.dirty
260
+ generation: state.dirty,
261
+ nonterminal: state.nonterminal
225
262
  };
226
263
  }));
227
264
  yield* failpoint.hit("maintenance:begin:after");
@@ -244,20 +281,43 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
244
281
  nonterminal: report.nonterminal,
245
282
  alarm: report.alarm
246
283
  }).pipe(Effect.as(report));
247
- const started = yield* generationGate.withPermit(Effect.gen(function* () {
248
- const activeAtStart = yield* Ref.get(activeMutations);
284
+ const started = yield* mutations.withSnapshot((activeAtStart) => Effect.gen(function* () {
285
+ const generation = yield* beginPass();
286
+ if (generation._tag === "Actionable" && activeAtStart === 0) yield* publication.prepareGeneration(generation.generation);
249
287
  return {
250
- ...yield* beginPass(),
288
+ ...generation,
251
289
  activeAtStart
252
290
  };
253
291
  }));
254
- if (started._tag === "CaughtUp") return yield* annotate(MaintenancePassReport.make({
255
- phase: "caught-up",
256
- recovered: 0,
257
- settled: 0,
258
- nonterminal: started.nonterminal,
259
- alarm: "cleared"
260
- }));
292
+ const deadline = yield* publication.pendingDeadline;
293
+ if (started._tag === "Actionable" || Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis)) yield* publication.drain;
294
+ const pending = yield* publication.pendingDeadline;
295
+ if (started._tag === "CaughtUp" || Option.isSome(pending)) {
296
+ yield* failpoint.hit("maintenance:finish:before");
297
+ const disposition = yield* mutations.withSnapshot((active) => Effect.gen(function* () {
298
+ const latest = yield* publication.pendingDeadline;
299
+ const now = yield* Clock.currentTimeMillis;
300
+ return yield* runTransaction("finish publication pass", () => ctx.storage.transaction(async (transaction) => {
301
+ const { state } = await readMaintenanceState(transaction);
302
+ const nativeDeadline = active > 0 || state.dirty > state.processed ? now + config.wakeScanInterval : Infinity;
303
+ const next = Option.isSome(latest) ? Math.min(nativeDeadline, latest.value) : nativeDeadline;
304
+ if (Number.isFinite(next)) {
305
+ await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));
306
+ return "rearmed";
307
+ }
308
+ await transaction.deleteAlarm();
309
+ return "cleared";
310
+ }));
311
+ }));
312
+ yield* failpoint.hit("maintenance:finish:after");
313
+ return yield* annotate(MaintenancePassReport.make({
314
+ phase: "caught-up",
315
+ recovered: 0,
316
+ settled: 0,
317
+ nonterminal: started.nonterminal,
318
+ alarm: disposition
319
+ }));
320
+ }
261
321
  const recovered = yield* runtime.runRecovery;
262
322
  const settlement = yield* runtime.processThreadHead(identity.threadId, { yieldAfter });
263
323
  const remaining = yield* Stream.runCollect(ledger.scanNonterminal);
@@ -272,8 +332,8 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
272
332
  const delay = autonomous ? yield* rearmDelay(progressed) : 0;
273
333
  const now = yield* Clock.currentTimeMillis;
274
334
  yield* failpoint.hit("maintenance:finish:before");
275
- const alarmDisposition = yield* generationGate.withPermit(Effect.gen(function* () {
276
- const active = yield* Ref.get(activeMutations);
335
+ const alarmDisposition = yield* mutations.withSnapshot((active) => Effect.gen(function* () {
336
+ const publicationDeadline = yield* publication.pendingDeadline;
277
337
  return yield* runTransaction("finish maintenance pass", () => ctx.storage.transaction(async (transaction) => {
278
338
  const { state } = await readMaintenanceState(transaction);
279
339
  const processed = autonomous || started.activeAtStart > 0 || active > 0 ? state.processed : state.processed > started.generation ? state.processed : started.generation;
@@ -284,11 +344,15 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
284
344
  });
285
345
  await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
286
346
  if (autonomous) {
287
- await transaction.setAlarm(now + delay);
347
+ await transaction.setAlarm(Option.isSome(publicationDeadline) ? Math.max(now + minimumAlarmDelay, Math.min(now + delay, publicationDeadline.value)) : now + delay);
288
348
  return "rearmed";
289
349
  }
290
350
  if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {
291
- await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);
351
+ await ensureTransactionAlarmBy(transaction, Option.isSome(publicationDeadline) ? Math.max(now + minimumAlarmDelay, Math.min(now + config.wakeScanInterval, publicationDeadline.value)) : now + config.wakeScanInterval);
352
+ return "rearmed";
353
+ }
354
+ if (Option.isSome(publicationDeadline)) {
355
+ await transaction.setAlarm(Math.max(now + minimumAlarmDelay, publicationDeadline.value));
292
356
  return "rearmed";
293
357
  }
294
358
  await transaction.deleteAlarm();
@@ -316,12 +380,12 @@ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effe
316
380
  message: "The maintenance event exceeded its 14 minute deadline; durable recovery remains pending"
317
381
  })
318
382
  })),
319
- ensureAlarm: ensureAlarm(),
320
- withMutation
383
+ ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),
384
+ withMutation: (body) => mutations.withMutation(body.pipe(Effect.tap(() => publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)))))
321
385
  });
322
386
  }));
323
387
  };
324
388
  //#endregion
325
- export { DurableAlarmError, DurableAlarmService, MaintenancePassReport, ThreadMaintenance, ThreadMaintenanceFailpoint, Alarm_exports as t };
389
+ export { DurableAlarmError, DurableAlarmService, MaintenancePassReport, ThreadMaintenance, ThreadMaintenanceFailpoint, ThreadMutationGate, ThreadPublication, publishCommitted, Alarm_exports as t };
326
390
 
327
391
  //# sourceMappingURL=Alarm.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Alarm.mjs","names":[],"sources":["../src/Alarm.ts"],"sourcesContent":["import { type DurableBindingFailure } from \"@effect-agent/thread/AgentRegistration\";\nimport {\n DurableAgentRuntime,\n type DurableWorkerFailure,\n type RecoveryReport,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { SubmissionLedger, type SubmissionSnapshot } from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n Clock,\n Context,\n DateTime,\n Effect,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\n\nimport { ThreadObjectIdentity, DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE\n * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement\n * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and\n * the slot always holds the EARLIEST deadline any caller asked for.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n /** The scheduled deadline in epoch milliseconds, if any. */\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n /** Replace the slot with this deadline. */\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /**\n * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a\n * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new\n * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the\n * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass\n * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)\n * would kill the running Attempt — manufacturing an ownership loss no real eviction\n * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.\n * Deferral is contract-safe: wakes are droppable hints, every mutating entry point\n * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this\n * call). The pass's durable generation check observes any racing mutation, so the\n * in-memory hint does not need to be flushed after a stable wait is acknowledged.\n */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /**\n * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`\n * executes are droppable promptness hints; correctness rests on the durable generation.\n */\n readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext> =\n Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n /**\n * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no\n * running pass, and a deferred wake lost to eviction was only ever a promptness hint\n * on top of the already-committed pre-armed alarm.\n */\n const runningPasses = yield* Ref.make(0);\n\n const scheduled = Effect.tryPromise({\n try: () => ctx.storage.getAlarm(),\n catch: alarmFailure(\"get alarm\"),\n }).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n\n const scheduleAt = (epochMillis: number) =>\n Effect.tryPromise({\n try: () => ctx.storage.setAlarm(epochMillis),\n catch: alarmFailure(\"set alarm\"),\n });\n\n const ensureScheduledBy = (epochMillis: number) =>\n scheduled.pipe(\n Effect.flatMap((existing) =>\n Option.isSome(existing) && existing.value <= epochMillis\n ? Effect.void\n : scheduleAt(epochMillis),\n ),\n );\n\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\n );\n\n const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Ref.update(runningPasses, (passes) => passes + 1).pipe(\n Effect.andThen(body),\n Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),\n );\n\n const cancel = Effect.tryPromise({\n try: () => ctx.storage.deleteAlarm(),\n catch: alarmFailure(\"delete alarm\"),\n });\n\n return DurableAlarmService.of({\n scheduled,\n scheduleAt,\n ensureScheduledBy,\n scheduleNow,\n withWakesDeferred,\n cancel,\n });\n }),\n );\n}\n\n/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` is generation-only; `actionable` ran recovery and at most one head Attempt. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Whether the head Attempt settled. Joined input may settle with that head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: DurableObjectTransaction,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst ensureTransactionAlarmBy = async (\n transaction: DurableObjectTransaction,\n deadline: number,\n): Promise<void> => {\n const scheduled = await transaction.getAlarm();\n\n if (scheduled === null || scheduled > deadline) {\n await transaction.setAlarm(deadline);\n }\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionSnapshot,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const decision = reports.get(snapshot.submissionId)?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return decision === \"AwaitUnknownResolution\" || decision === \"MarkUnknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"running\":\n case \"settled\":\n case \"terminalizing\":\n return false;\n }\n};\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:\n *\n * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced\n * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.\n * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests\n * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.\n * 3. The final transaction acknowledges only the generation observed at pass start. A racing\n * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.\n * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease\n * recovery states leave their generation dirty and retain bounded backoff rearming.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n never,\n | DurableAgentRuntime\n | SubmissionLedger\n | DurableAlarmService\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | ThreadObjectIdentity\n | DurableObjectContext\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const identity = yield* ThreadObjectIdentity;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n /**\n * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation\n * restarts at zero and merely re-arms sooner than a long-lived one would have.\n */\n const stalls = yield* Ref.make(0);\n /**\n * Incarnation-local mutation count guarded with the generation transactions below. It is\n * deliberately not durable: after eviction every begun mutation has stopped, while its\n * pre-armed dirty generation remains durable for recovery. The short gate never spans the\n * caller's mutation or cross-Object I/O.\n */\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n // At-least-once deliveries are idempotent, but overlapping pass bodies could otherwise\n // acknowledge state while a sibling pass is still mutating it. Port/RPC mutations do not\n // take this permit, so cross-Object I/O cannot deadlock the maintenance serialization.\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = <A>(\n operation: string,\n transaction: () => Promise<A>,\n ): Effect.Effect<A, DurableAlarmError> =>\n Effect.tryPromise({\n try: transaction,\n catch: alarmFailure(operation),\n });\n\n const beginMutation = Effect.fn(\"ThreadMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n }),\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n });\n\n const endMutation = generationGate.withPermit(\n Ref.update(activeMutations, (active) => Math.max(0, active - 1)),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.acquireUseRelease(\n generationGate.withPermit(beginMutation()),\n () =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(body),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n () => endMutation,\n );\n\n const ensureAlarm = Effect.fn(\"ThreadMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.dirty > state.processed) {\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n }\n }),\n );\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ThreadMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n await transaction.deleteAlarm();\n\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n }\n // Pre-arm the earliest retry before recovery. A successful finish may move this slot\n // LATER to its bounded backoff, which does not cancel the running handler.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return { _tag: \"Actionable\" as const, generation: state.dirty };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ThreadMaintenance.rearmDelay\")(function* (progressed: boolean) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\n );\n\n if (progressed) return config.alarmBackoffBase;\n const exponent = Math.min(priorStalls, 30);\n const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);\n const jitter = yield* Random.next;\n // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever\n // waiting longer than the deterministic bound.\n const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n\n return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ThreadMaintenance.pass\")(function* (\n yieldAfter: DateTime.Utc,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {\n const annotate = (report: MaintenancePassReport) =>\n Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n }).pipe(Effect.as(report));\n\n const started = yield* generationGate.withPermit(\n Effect.gen(function* () {\n const activeAtStart = yield* Ref.get(activeMutations);\n const generation = yield* beginPass();\n\n return { ...generation, activeAtStart };\n }),\n );\n\n if (started._tag === \"CaughtUp\") {\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: \"cleared\",\n }),\n );\n }\n // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).\n const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;\n // One head Attempt per event. The runtime yields after a committed turn when the\n // soft deadline is reached; queued followers belong to a subsequent alarm.\n const settlement = yield* runtime.processThreadHead(identity.threadId, { yieldAfter });\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const head = remaining[0];\n const headWaiting = head !== undefined && stableExternalWait(head, reports);\n\n const autonomous = remaining.some((snapshot, index) => {\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n index > 0 &&\n headWaiting &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !stableExternalWait(snapshot, reports);\n });\n\n const progressed =\n Option.isSome(settlement) ||\n recovered.some((report) => report.disposition === \"repaired\");\n\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const alarmDisposition = yield* generationGate.withPermit(\n Effect.gen(function* () {\n const active = yield* Ref.get(activeMutations);\n\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n // Autonomous work and in-flight mutations intentionally leave the observed\n // generation dirty. Otherwise acknowledge only the pass-start generation.\n const processed =\n autonomous || started.activeAtStart > 0 || active > 0\n ? state.processed\n : state.processed > started.generation\n ? state.processed\n : started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n if (autonomous) {\n // Replace the crash-fallback slot with this pass's bounded backoff. The target\n // is never earlier than the begin-pass fallback, so workerd does not cancel\n // this running alarm handler before its report/span can complete.\n await transaction.setAlarm(now + delay);\n\n return \"rearmed\" as const;\n }\n if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {\n // A mutation overlapped this pass's observation window or raced\n // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;\n // unseen effects are never acknowledged. Do not accelerate that future alarm\n // from inside the current handler: workerd cancels a running handler when it\n // writes an earlier slot.\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: Option.isSome(settlement) ? 1 : 0,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);\n\n return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n ),\n ensureAlarm: ensureAlarm(),\n withMutation,\n });\n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AM,qBAAqB,GAAW;IAErF,OAAO,OAAO,MAAM,kBAAkB,oBAAoB,WAAW,KAAK,UAAU,CAAC,CAAC;GACxF,CAAC,CAAC,CAAC,KAKD,OAAO,cAAc;IACnB,UAAU;IACV,cACE,kBAAkB,KAAK;KACrB,WAAW;KACX,SACE;IACJ,CAAC;GACL,CAAC,CACH;GACA,aAAa,YAAY;GACzB;EACF,CAAC;CACH,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"Alarm.mjs","names":[],"sources":["../src/Alarm.ts"],"sourcesContent":["import { type DurableBindingFailure } from \"@effect-agent/thread/AgentRegistration\";\nimport {\n DurableAgentRuntime,\n type DurableWorkerFailure,\n type RecoveryReport,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { SubmissionLedger, type SubmissionSnapshot } from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n Cause,\n Clock,\n Context,\n DateTime,\n Effect,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\n\nimport { ThreadObjectIdentity, DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE\n * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement\n * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and\n * the slot always holds the EARLIEST deadline any caller asked for.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n /** The scheduled deadline in epoch milliseconds, if any. */\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n /** Replace the slot with this deadline. */\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /**\n * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a\n * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new\n * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the\n * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass\n * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)\n * would kill the running Attempt — manufacturing an ownership loss no real eviction\n * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.\n * Deferral is contract-safe: wakes are droppable hints, every mutating entry point\n * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this\n * call). The pass's durable generation check observes any racing mutation, so the\n * in-memory hint does not need to be flushed after a stable wait is acknowledged.\n */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /**\n * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`\n * executes are droppable promptness hints; correctness rests on the durable generation.\n */\n readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext> =\n Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n /**\n * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no\n * running pass, and a deferred wake lost to eviction was only ever a promptness hint\n * on top of the already-committed pre-armed alarm.\n */\n const runningPasses = yield* Ref.make(0);\n\n const scheduled = Effect.tryPromise({\n try: () => ctx.storage.getAlarm(),\n catch: alarmFailure(\"get alarm\"),\n }).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n\n const scheduleAt = (epochMillis: number) =>\n Effect.tryPromise({\n try: () => ctx.storage.setAlarm(epochMillis),\n catch: alarmFailure(\"set alarm\"),\n });\n\n const ensureScheduledBy = (epochMillis: number) =>\n scheduled.pipe(\n Effect.flatMap((existing) =>\n Option.isSome(existing) && existing.value <= epochMillis\n ? Effect.void\n : scheduleAt(epochMillis),\n ),\n );\n\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\n );\n\n const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Ref.update(runningPasses, (passes) => passes + 1).pipe(\n Effect.andThen(body),\n Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),\n );\n\n const cancel = Effect.tryPromise({\n try: () => ctx.storage.deleteAlarm(),\n catch: alarmFailure(\"delete alarm\"),\n });\n\n return DurableAlarmService.of({\n scheduled,\n scheduleAt,\n ensureScheduledBy,\n scheduleNow,\n withWakesDeferred,\n cancel,\n });\n }),\n );\n}\n\n/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Whether the head Attempt settled. Joined input may settle with that head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\n/**\n * Durable host publication of canonical records and ledger approval/abort/resolution intents.\n * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery\n * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.\n *\n * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.\n * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated\n * calls must preserve partial scan progress. It runs with no source mutation in flight.\n * `drain` performs bounded delivery and persists retries before returning. A pending deadline\n * defers runtime recovery/Attempts, allowing committed host publications to drain first.\n * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call\n * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need\n * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.\n */\nexport interface ThreadPublicationService {\n readonly invalidate: Effect.Effect<void, DurableAlarmError>;\n readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}\n\n/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */\nexport class ThreadPublication extends Context.Service<\n ThreadPublication,\n ThreadPublicationService\n>()(\"@effect-agent/platform-cloudflare/ThreadPublication\") {\n static readonly layer = Layer.succeed(this)({\n invalidate: Effect.void,\n prepareGeneration: () => Effect.void,\n drain: Effect.void,\n pendingDeadline: Effect.succeed(Option.none()),\n });\n}\n\n/** @internal A committed source operation must not become a failed operation because delivery failed. */\nexport const publishCommitted = Effect.gen(function* () {\n const publication = yield* ThreadPublication;\n\n yield* publication.invalidate.pipe(Effect.andThen(publication.drain));\n}).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\"Thread publication deferred after source commit\", cause),\n ),\n);\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: DurableObjectTransaction,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst ensureTransactionAlarmBy = async (\n transaction: DurableObjectTransaction,\n deadline: number,\n): Promise<void> => {\n const scheduled = await transaction.getAlarm();\n\n if (scheduled === null || scheduled > deadline) {\n await transaction.setAlarm(deadline);\n }\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionSnapshot,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const decision = reports.get(snapshot.submissionId)?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return decision === \"AwaitUnknownResolution\" || decision === \"MarkUnknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"running\":\n case \"settled\":\n case \"terminalizing\":\n return false;\n }\n};\n\n/**\n * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.\n * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance\n * Layers must reuse that instance; a second gate cannot observe the native producers' activity.\n */\nexport class ThreadMutationGate extends Context.Service<\n ThreadMutationGate,\n {\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n readonly withSnapshot: <A, E, R>(\n body: (active: number) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/internal/ThreadMutationGate\") {\n static readonly layer = Layer.effect(this)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n // A fresh incarnation has no live mutations; durable generations survive eviction.\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = <A>(operation: string, transaction: () => Promise<A>) =>\n Effect.tryPromise({ try: transaction, catch: alarmFailure(operation) });\n\n const beginMutation = Effect.fn(\"ThreadMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n }),\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n });\n\n const endMutation = generationGate.withPermit(\n Ref.update(activeMutations, (active) => Math.max(0, active - 1)),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.acquireUseRelease(\n generationGate.withPermit(beginMutation()),\n () =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(body),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n () => endMutation,\n );\n\n return ThreadMutationGate.of({\n withMutation,\n withSnapshot: (body) =>\n generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),\n });\n }),\n );\n}\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:\n *\n * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced\n * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.\n * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests\n * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.\n * 3. The final transaction acknowledges only the generation observed at pass start. A racing\n * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.\n * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease\n * recovery states leave their generation dirty and retain bounded backoff rearming.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n never,\n | ThreadMutationGate\n | ThreadPublication\n | DurableAgentRuntime\n | SubmissionLedger\n | DurableAlarmService\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | ThreadObjectIdentity\n | DurableObjectContext\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const identity = yield* ThreadObjectIdentity;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n /**\n * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation\n * restarts at zero and merely re-arms sooner than a long-lived one would have.\n */\n const stalls = yield* Ref.make(0);\n const mutations = yield* ThreadMutationGate;\n const publication = yield* ThreadPublication;\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = <A>(operation: string, transaction: () => Promise<A>) =>\n Effect.tryPromise({ try: transaction, catch: alarmFailure(operation) });\n\n const ensureAlarm = Effect.fn(\"ThreadMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.dirty > state.processed) {\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n }\n }),\n );\n const deadline = yield* publication.pendingDeadline;\n\n if (Option.isSome(deadline)) {\n yield* runTransaction(\"ensure publication alarm\", () =>\n ctx.storage.transaction((transaction) =>\n ensureTransactionAlarmBy(\n transaction,\n Math.max(now + minimumAlarmDelay, deadline.value),\n ),\n ),\n );\n }\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ThreadMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n // Prearm even a publication-only pass before invoking any host hook.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n }\n // Pre-arm the earliest retry before recovery. A successful finish may move this slot\n // LATER to its bounded backoff, which does not cancel the running handler.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return {\n _tag: \"Actionable\" as const,\n generation: state.dirty,\n nonterminal: state.nonterminal,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ThreadMaintenance.rearmDelay\")(function* (progressed: boolean) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\n );\n\n if (progressed) return config.alarmBackoffBase;\n const exponent = Math.min(priorStalls, 30);\n const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);\n const jitter = yield* Random.next;\n // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever\n // waiting longer than the deterministic bound.\n const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n\n return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ThreadMaintenance.pass\")(function* (\n yieldAfter: DateTime.Utc,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {\n const annotate = (report: MaintenancePassReport) =>\n Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n }).pipe(Effect.as(report));\n\n const started = yield* mutations.withSnapshot((activeAtStart) =>\n Effect.gen(function* () {\n const generation = yield* beginPass();\n\n if (generation._tag === \"Actionable\" && activeAtStart === 0) {\n // The gate excludes a producer starting between the snapshot and certification.\n yield* publication.prepareGeneration(generation.generation);\n }\n\n return { ...generation, activeAtStart };\n }),\n );\n\n const deadline = yield* publication.pendingDeadline;\n\n if (\n started._tag === \"Actionable\" ||\n (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))\n ) {\n yield* publication.drain;\n }\n const pending = yield* publication.pendingDeadline;\n\n if (started._tag === \"CaughtUp\" || Option.isSome(pending)) {\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const disposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n // Re-read under the producer gate: a concurrent append/host mutation cannot be\n // cleared using a stale empty deadline. Dirty generations bound all producer races.\n const latest = yield* publication.pendingDeadline;\n const now = yield* Clock.currentTimeMillis;\n\n return yield* runTransaction(\"finish publication pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const nativeDeadline =\n active > 0 || state.dirty > state.processed\n ? now + config.wakeScanInterval\n : Infinity;\n\n const next = Option.isSome(latest)\n ? Math.min(nativeDeadline, latest.value)\n : nativeDeadline;\n\n if (Number.isFinite(next)) {\n await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: disposition,\n }),\n );\n }\n // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).\n const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;\n // One head Attempt per event. The runtime yields after a committed turn when the\n // soft deadline is reached; queued followers belong to a subsequent alarm.\n const settlement = yield* runtime.processThreadHead(identity.threadId, { yieldAfter });\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const head = remaining[0];\n const headWaiting = head !== undefined && stableExternalWait(head, reports);\n\n const autonomous = remaining.some((snapshot, index) => {\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n index > 0 &&\n headWaiting &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !stableExternalWait(snapshot, reports);\n });\n\n const progressed =\n Option.isSome(settlement) ||\n recovered.some((report) => report.disposition === \"repaired\");\n\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const alarmDisposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const publicationDeadline = yield* publication.pendingDeadline;\n\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n // Autonomous work and in-flight mutations intentionally leave the observed\n // generation dirty. Otherwise acknowledge only the pass-start generation.\n const processed =\n autonomous || started.activeAtStart > 0 || active > 0\n ? state.processed\n : state.processed > started.generation\n ? state.processed\n : started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n if (autonomous) {\n // Replace the crash-fallback slot with this pass's bounded backoff. The target\n // is never earlier than the begin-pass fallback, so workerd does not cancel\n // this running alarm handler before its report/span can complete.\n await transaction.setAlarm(\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + delay, publicationDeadline.value),\n )\n : now + delay,\n );\n\n return \"rearmed\" as const;\n }\n if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {\n // A mutation overlapped this pass's observation window or raced\n // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;\n // unseen effects are never acknowledged. Do not accelerate that future alarm\n // from inside the current handler: workerd cancels a running handler when it\n // writes an earlier slot.\n await ensureTransactionAlarmBy(\n transaction,\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + config.wakeScanInterval, publicationDeadline.value),\n )\n : now + config.wakeScanInterval,\n );\n\n return \"rearmed\" as const;\n }\n if (Option.isSome(publicationDeadline)) {\n await transaction.setAlarm(\n Math.max(now + minimumAlarmDelay, publicationDeadline.value),\n );\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: Option.isSome(settlement) ? 1 : 0,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);\n\n return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n ),\n ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),\n withMutation: (body) =>\n mutations.withMutation(\n body.pipe(\n Effect.tap(() =>\n publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),\n ),\n ),\n ),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,gBACH,eACA,UACC,kBAAkB,KAAK;CACrB;CACA,SAAS,iBAAiB,OAAO,sDAAsD;CACvF;AACF,CAAC;;AAGL,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QA+B/C,CAAC,CAAC,uDAAuD,CAAC,CAAC;CAC3D,OAAgB,QACd,MAAM,OAAO,mBAAmB,CAAC,CAC/B,OAAO,IAAI,aAAa;EACtB,MAAM,EAAE,QAAQ,OAAO;;;;;;EAMvB,MAAM,gBAAgB,OAAO,IAAI,KAAK,CAAC;EAEvC,MAAM,YAAY,OAAO,WAAW;GAClC,WAAW,IAAI,QAAQ,SAAS;GAChC,OAAO,aAAa,WAAW;EACjC,CAAC,CAAC,CAAC,KACD,OAAO,KAAK,aACV,aAAa,OAAO,OAAO,KAAa,IAAI,OAAO,KAAK,QAAQ,CAClE,CACF;EAEA,MAAM,cAAc,gBAClB,OAAO,WAAW;GAChB,WAAW,IAAI,QAAQ,SAAS,WAAW;GAC3C,OAAO,aAAa,WAAW;EACjC,CAAC;EAEH,MAAM,qBAAqB,gBACzB,UAAU,KACR,OAAO,SAAS,aACd,OAAO,OAAO,QAAQ,KAAK,SAAS,SAAS,cACzC,OAAO,OACP,WAAW,WAAW,CAC5B,CACF;EAEF,MAAM,SAAS,MAAM,kBAAkB,KACrC,OAAO,SAAS,QAAQ,kBAAkB,GAA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AsB,KAAK;IACzB,OAAO;IACP,WAAW,UAAU;IACrB,SAAS,OAAO,OAAO,UAAU,IAAI,IAAI;IACzC,aAAa,UAAU;IACvB,OAAO;GACT,CAAC,CACH;EACF,CAAC;EAED,OAAO,kBAAkB,GAAG;GAE1B,MAAM,OAAO,IAAI,aAAa;IAC5B,MAAM,aAAa,SAAS,YAAY,OAAO,MAAM,qBAAqB,GAAW;IAErF,OAAO,OAAO,MAAM,kBAAkB,oBAAoB,WAAW,KAAK,UAAU,CAAC,CAAC;GACxF,CAAC,CAAC,CAAC,KAKD,OAAO,cAAc;IACnB,UAAU;IACV,cACE,kBAAkB,KAAK;KACrB,WAAW;KACX,SACE;IACJ,CAAC;GACL,CAAC,CACH;GACA,aAAa,UAAU,mBAAmB,YAAY,CAAC;GACvD,eAAe,SACb,UAAU,aACR,KAAK,KACH,OAAO,UACL,iBAAiB,KAAK,OAAO,eAAe,mBAAmB,WAAW,CAAC,CAC7E,CACF,CACF;EACJ,CAAC;CACH,CAAC,CACH;AACF"}
@@ -7,7 +7,7 @@ import { EventSources } from "@effect-agent/thread/EventSource";
7
7
  import { SubscriptionInputBindings } from "@effect-agent/thread/SubscriptionInput";
8
8
  import { SubscriptionDriver, SubscriptionIntake, Subscriptions } from "@effect-agent/thread/Subscriptions";
9
9
  declare namespace CloudflareSubscriptions_d_exports {
10
- export { CloudflareSubscriptionConfigError, CloudflareSubscriptionsClient, SubscriptionAlarmExtensionError, SubscriptionAlarmProtocolError, SubscriptionPartitionAlarmExtension, SubscriptionPartitionAlarmHandler, SubscriptionPartitionIdentity, SubscriptionPartitionNamespace, SubscriptionPartitionObjectClass, SubscriptionPartitionObjectInstance, SubscriptionPartitionObjectRpc, SubscriptionPartitionProtocolError, makeSubscriptionPartitionAlarmHandler, makeSubscriptionPartitionObjectClass, sourcePartitionName, validateCloudflareSubscriptionLimits };
10
+ export { CloudflareSubscriptionConfigError, CloudflareSubscriptionsClient, SubscriptionAlarmExtensionError, SubscriptionAlarmProtocolError, SubscriptionPartitionAlarmExtension, SubscriptionPartitionAlarmHandler, SubscriptionPartitionAlarmServices, SubscriptionPartitionIdentity, SubscriptionPartitionNamespace, SubscriptionPartitionObjectClass, SubscriptionPartitionObjectInstance, SubscriptionPartitionObjectRpc, SubscriptionPartitionProtocolError, makeSubscriptionPartitionAlarmHandler, makeSubscriptionPartitionObjectClass, sourcePartitionName, validateCloudflareSubscriptionLimits };
11
11
  }
12
12
  declare const SubscriptionAlarmProtocolError_base: Schema.Class<SubscriptionAlarmProtocolError, Schema.TaggedStruct<"SubscriptionAlarmProtocolError", {
13
13
  readonly message: Schema.String;
@@ -18,15 +18,18 @@ declare const SubscriptionAlarmExtensionError_base: Schema.Class<SubscriptionAla
18
18
  }>, Cause.YieldableError>;
19
19
  /** Bounded host diagnostic; credentials and provider responses do not belong in alarm failures. */
20
20
  declare class SubscriptionAlarmExtensionError extends SubscriptionAlarmExtensionError_base {}
21
- interface SubscriptionPartitionAlarmHandler {
21
+ /** Native partition services supplied at alarm invocation, after the host Layer is built. */
22
+ type SubscriptionPartitionAlarmServices = Subscriptions | SubscriptionIntake | SubscriptionDriver;
23
+ interface SubscriptionPartitionAlarmHandler<R = SubscriptionPartitionAlarmServices> {
22
24
  readonly tag: string;
23
- readonly handle: (event: DurableObjectAlarm.DurableObjectAlarmEvent) => Effect.Effect<void, SubscriptionAlarmProtocolError | SubscriptionAlarmExtensionError>;
25
+ readonly handle: (event: DurableObjectAlarm.DurableObjectAlarmEvent) => Effect.Effect<void, SubscriptionAlarmProtocolError | SubscriptionAlarmExtensionError, R>;
24
26
  }
25
27
  /** Host-only handlers; the framework reserves its namespace and rejects every unknown tag. */
26
28
  declare const SubscriptionPartitionAlarmExtension: Context.Reference<{
27
29
  readonly handlers: ReadonlyArray<SubscriptionPartitionAlarmHandler>;
28
30
  }>;
29
- /** Capture host services once; each invocation owns its codec/handler Scope and timeout.
31
+ /** Capture host services once, deferring native partition services to invocation.
32
+ * Each invocation owns its codec/handler Scope and timeout.
30
33
  * Callback failures stay typed. Defects and interruption reach the native alarm multiplexer.
31
34
  * The host owns durable idempotency, prearming and external-effect uncertainty.
32
35
  */
@@ -37,7 +40,7 @@ declare const makeSubscriptionPartitionAlarmHandler: <Payload extends Schema.Top
37
40
  readonly handle: (event: Omit<DurableObjectAlarm.DurableObjectAlarmEvent, "payload"> & {
38
41
  readonly payload: Payload["Type"];
39
42
  }) => Effect.Effect<void, SubscriptionAlarmExtensionError, R>;
40
- }) => Effect.Effect<SubscriptionPartitionAlarmHandler, SubscriptionAlarmProtocolError, Exclude<R, Scope.Scope> | Exclude<Payload["DecodingServices"], Scope.Scope>>;
43
+ }) => Effect.Effect<SubscriptionPartitionAlarmHandler<Exclude<Exclude<R, Scope.Scope>, Exclude<Exclude<R, Scope.Scope | SubscriptionPartitionAlarmServices>, SubscriptionPartitionAlarmServices> | Exclude<Exclude<Payload["DecodingServices"], Scope.Scope | SubscriptionPartitionAlarmServices>, SubscriptionPartitionAlarmServices>> | Exclude<Exclude<Payload["DecodingServices"], Scope.Scope>, Exclude<Exclude<R, Scope.Scope | SubscriptionPartitionAlarmServices>, SubscriptionPartitionAlarmServices> | Exclude<Exclude<Payload["DecodingServices"], Scope.Scope | SubscriptionPartitionAlarmServices>, SubscriptionPartitionAlarmServices>>>, SubscriptionAlarmProtocolError, Exclude<R, Scope.Scope | SubscriptionPartitionAlarmServices> | Exclude<Payload["DecodingServices"], Scope.Scope | SubscriptionPartitionAlarmServices>>;
41
44
  declare const SubscriptionPartitionProtocolError_base: Schema.Class<SubscriptionPartitionProtocolError, Schema.TaggedStruct<"SubscriptionPartitionProtocolError", {
42
45
  readonly message: Schema.String;
43
46
  }>, Cause.YieldableError>;
@@ -80,5 +83,5 @@ interface SubscriptionPartitionObjectClass {
80
83
  */
81
84
  declare const makeSubscriptionPartitionObjectClass: <E>(host: Layer.Layer<SubscriptionAuthorizer | EventSources | SubscriptionInputBindings | ThreadObjectNamespace, E, DurableObjectState$1.DurableObjectState | WorkerEnvironment | SubscriptionPartitionIdentity>, limits?: SubscriptionLimits) => SubscriptionPartitionObjectClass;
82
85
  //#endregion
83
- export { CloudflareSubscriptionConfigError, CloudflareSubscriptionsClient, SubscriptionAlarmExtensionError, SubscriptionAlarmProtocolError, SubscriptionPartitionAlarmExtension, SubscriptionPartitionAlarmHandler, SubscriptionPartitionIdentity, SubscriptionPartitionNamespace, SubscriptionPartitionObjectClass, SubscriptionPartitionObjectInstance, SubscriptionPartitionObjectRpc, SubscriptionPartitionProtocolError, makeSubscriptionPartitionAlarmHandler, makeSubscriptionPartitionObjectClass, sourcePartitionName, CloudflareSubscriptions_d_exports as t, validateCloudflareSubscriptionLimits };
86
+ export { CloudflareSubscriptionConfigError, CloudflareSubscriptionsClient, SubscriptionAlarmExtensionError, SubscriptionAlarmProtocolError, SubscriptionPartitionAlarmExtension, SubscriptionPartitionAlarmHandler, SubscriptionPartitionAlarmServices, SubscriptionPartitionIdentity, SubscriptionPartitionNamespace, SubscriptionPartitionObjectClass, SubscriptionPartitionObjectInstance, SubscriptionPartitionObjectRpc, SubscriptionPartitionProtocolError, makeSubscriptionPartitionAlarmHandler, makeSubscriptionPartitionObjectClass, sourcePartitionName, CloudflareSubscriptions_d_exports as t, validateCloudflareSubscriptionLimits };
84
87
  //# sourceMappingURL=CloudflareSubscriptions.d.mts.map
@@ -41,13 +41,14 @@ var SubscriptionAlarmProtocolError = class extends Schema.TaggedError()("Subscri
41
41
  var SubscriptionAlarmExtensionError = class extends Schema.TaggedError()("SubscriptionAlarmExtensionError", { code: Schema.NonEmptyString.check(Schema.isMaxLength(128)) }) {};
42
42
  /** Host-only handlers; the framework reserves its namespace and rejects every unknown tag. */
43
43
  const SubscriptionPartitionAlarmExtension = Context.Reference("@effect-agent/platform-cloudflare/SubscriptionPartitionAlarmExtension", { defaultValue: () => ({ handlers: [] }) });
44
- /** Capture host services once; each invocation owns its codec/handler Scope and timeout.
44
+ /** Capture host services once, deferring native partition services to invocation.
45
+ * Each invocation owns its codec/handler Scope and timeout.
45
46
  * Callback failures stay typed. Defects and interruption reach the native alarm multiplexer.
46
47
  * The host owns durable idempotency, prearming and external-effect uncertainty.
47
48
  */
48
49
  const makeSubscriptionPartitionAlarmHandler = Effect.fn("makeSubscriptionPartitionAlarmHandler")(function* (options) {
49
50
  if (options.tag.length === 0 || options.tag.length > 128 || options.tag.startsWith("effect-agent/") || !Number.isSafeInteger(options.timeoutMillis) || options.timeoutMillis < 1 || options.timeoutMillis > MAX_ANCILLARY_ALARM_MILLIS) return yield* SubscriptionAlarmProtocolError.make({ message: "Invalid ancillary alarm tag or timeout" });
50
- const services = yield* Effect.context();
51
+ const services = (yield* Effect.context()).pipe(Context.omit(Subscriptions, SubscriptionIntake, SubscriptionDriver));
51
52
  return {
52
53
  tag: options.tag,
53
54
  handle: (event) => Effect.gen(function* () {