@effect-agent/platform-cloudflare 0.0.1-beta.6 → 0.1.0-beta.100

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.
Files changed (102) hide show
  1. package/dist/Alarm.d.mts +207 -0
  2. package/dist/Alarm.mjs +578 -0
  3. package/dist/Alarm.mjs.map +1 -0
  4. package/dist/BrowserRestCapture.d.mts +34 -0
  5. package/dist/BrowserRestCapture.mjs +238 -0
  6. package/dist/BrowserRestCapture.mjs.map +1 -0
  7. package/dist/BrowserRestCrawl.d.mts +16 -0
  8. package/dist/BrowserRestCrawl.mjs +244 -0
  9. package/dist/BrowserRestCrawl.mjs.map +1 -0
  10. package/dist/CloudflareAiGateway.d.mts +64 -0
  11. package/dist/CloudflareAiGateway.mjs +70 -0
  12. package/dist/CloudflareAiGateway.mjs.map +1 -0
  13. package/dist/CloudflareBindings.d.mts +115 -0
  14. package/dist/CloudflareBindings.mjs +113 -0
  15. package/dist/CloudflareBindings.mjs.map +1 -0
  16. package/dist/CloudflareBrowser-DV6kya1H.mjs +495 -0
  17. package/dist/CloudflareBrowser-DV6kya1H.mjs.map +1 -0
  18. package/dist/CloudflareBrowser-Doe1M7R5.d.mts +80 -0
  19. package/dist/CloudflareBrowser.d.mts +2 -0
  20. package/dist/CloudflareBrowser.mjs +2 -0
  21. package/dist/CloudflareCodeMode.d.mts +44 -0
  22. package/dist/CloudflareCodeMode.mjs +616 -0
  23. package/dist/CloudflareCodeMode.mjs.map +1 -0
  24. package/dist/CloudflareConfig-DKXGo8L3.d.mts +106 -0
  25. package/dist/CloudflareConfig.d.mts +2 -0
  26. package/dist/CloudflareConfig.mjs +128 -0
  27. package/dist/CloudflareConfig.mjs.map +1 -0
  28. package/dist/CloudflareMemory.d.mts +142 -0
  29. package/dist/CloudflareMemory.mjs +202 -0
  30. package/dist/CloudflareMemory.mjs.map +1 -0
  31. package/dist/CloudflareScheduling.d.mts +52 -0
  32. package/dist/CloudflareScheduling.mjs +396 -0
  33. package/dist/CloudflareScheduling.mjs.map +1 -0
  34. package/dist/CloudflareSubscriptions.d.mts +87 -0
  35. package/dist/CloudflareSubscriptions.mjs +530 -0
  36. package/dist/CloudflareSubscriptions.mjs.map +1 -0
  37. package/dist/CloudflareThreadClient.d.mts +1600 -0
  38. package/dist/CloudflareThreadClient.mjs +382 -0
  39. package/dist/CloudflareThreadClient.mjs.map +1 -0
  40. package/dist/InteractiveBrowser-BCS9g0tn.mjs +1180 -0
  41. package/dist/InteractiveBrowser-BCS9g0tn.mjs.map +1 -0
  42. package/dist/InteractiveBrowser-BR16UPbF.d.mts +169 -0
  43. package/dist/InteractiveBrowser.d.mts +2 -0
  44. package/dist/InteractiveBrowser.mjs +2 -0
  45. package/dist/ProtectedBrowser.d.mts +123 -0
  46. package/dist/ProtectedBrowser.mjs +1135 -0
  47. package/dist/ProtectedBrowser.mjs.map +1 -0
  48. package/dist/ThreadObject-CMQiW2uX.d.mts +827 -0
  49. package/dist/ThreadObject-DXavwaU-.mjs +853 -0
  50. package/dist/ThreadObject-DXavwaU-.mjs.map +1 -0
  51. package/dist/ThreadObject.d.mts +2 -0
  52. package/dist/ThreadObject.mjs +3 -0
  53. package/dist/WakeScheduler.d.mts +23 -0
  54. package/dist/WakeScheduler.mjs +57 -0
  55. package/dist/WakeScheduler.mjs.map +1 -0
  56. package/dist/boundary-BguazVkh.mjs +42 -0
  57. package/dist/boundary-BguazVkh.mjs.map +1 -0
  58. package/dist/index.d.mts +13 -1580
  59. package/dist/index.mjs +13 -1941
  60. package/dist/prepared-admission-DU0_T-ev.mjs +73 -0
  61. package/dist/prepared-admission-DU0_T-ev.mjs.map +1 -0
  62. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  63. package/package.json +1 -52
  64. package/src/Alarm.ts +1270 -0
  65. package/src/BrowserRestCapture.ts +477 -0
  66. package/src/BrowserRestCrawl.ts +540 -0
  67. package/src/CloudflareAiGateway.ts +170 -0
  68. package/src/CloudflareBindings.ts +199 -0
  69. package/src/CloudflareBrowser.ts +15 -0
  70. package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +372 -204
  71. package/src/{config.ts → CloudflareConfig.ts} +19 -15
  72. package/src/CloudflareMemory.ts +420 -0
  73. package/src/CloudflareScheduling.ts +747 -0
  74. package/src/CloudflareSubscriptions.ts +1041 -0
  75. package/src/CloudflareThreadClient.ts +809 -0
  76. package/src/InteractiveBrowser.ts +2418 -0
  77. package/src/ProtectedBrowser.ts +9 -0
  78. package/src/ThreadObject.ts +1179 -0
  79. package/src/{wake-scheduler.ts → WakeScheduler.ts} +32 -26
  80. package/src/index.ts +12 -24
  81. package/src/internal/boundary.ts +55 -0
  82. package/src/internal/browser-quick-action.ts +857 -0
  83. package/src/internal/browser-session-lifecycle.ts +160 -0
  84. package/src/internal/layers.ts +756 -0
  85. package/src/internal/message-delivery.ts +181 -0
  86. package/src/internal/prepared-admission.ts +116 -0
  87. package/src/internal/progress-wait.ts +121 -0
  88. package/src/internal/transport.ts +44 -0
  89. package/src/protected-browser/binding.ts +313 -0
  90. package/src/protected-browser/host.ts +344 -0
  91. package/src/protected-browser/inspect-frame.ts +125 -0
  92. package/src/protected-browser/native.ts +445 -0
  93. package/src/protected-browser/policy.ts +821 -0
  94. package/dist/index.mjs.map +0 -1
  95. package/src/alarm.ts +0 -334
  96. package/src/bindings.ts +0 -145
  97. package/src/client.ts +0 -646
  98. package/src/conversation-object.ts +0 -847
  99. package/src/layers.ts +0 -385
  100. package/src/telemetry-internal.ts +0 -432
  101. package/src/telemetry.ts +0 -37
  102. package/src/transport.ts +0 -38
package/src/Alarm.ts ADDED
@@ -0,0 +1,1270 @@
1
+ import {
2
+ Cause,
3
+ Clock,
4
+ Context,
5
+ DateTime,
6
+ Deferred,
7
+ Effect,
8
+ Exit,
9
+ Fiber,
10
+ Layer,
11
+ Option,
12
+ Random,
13
+ Ref,
14
+ Schema,
15
+ Scope,
16
+ Semaphore,
17
+ Stream,
18
+ Struct,
19
+ } from "effect";
20
+ import { type DurableBindingFailure } from "effect-agent/agent-registration";
21
+ import {
22
+ DurableAgentRuntime,
23
+ type DurableWorkerFailure,
24
+ type RecoveryReport,
25
+ } from "effect-agent/durable-agent-runtime";
26
+ import { ThreadId, SubmissionId } from "effect-agent/identifiers";
27
+ import { SubmissionLedger, type SubmissionSnapshot } from "effect-agent/submission-ledger";
28
+ import {
29
+ ThreadProjectionMaintenance,
30
+ drainDue,
31
+ type ThreadProjectionError,
32
+ } from "effect-agent/thread-projection-maintenance";
33
+ import { SqlClient } from "effect/unstable/sql/SqlClient";
34
+
35
+ import { DurableObjectContext } from "./CloudflareBindings.ts";
36
+ import { AuxiliaryDispatchMillis, CloudflareDurableRuntimeConfig } from "./CloudflareConfig.ts";
37
+ import { safeCauseMessage } from "./internal/boundary.ts";
38
+
39
+ /**
40
+ * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
41
+ * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
42
+ * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and
43
+ * the slot always holds the EARLIEST deadline any caller asked for.
44
+ *
45
+ * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable
46
+ * maintenance generation and a committed alarm. Stable externally-driven waits may be
47
+ * nonterminal without retaining an alarm; their resolving mutation advances the generation and
48
+ * restores the alarm atomically.
49
+ */
50
+
51
+ /** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */
52
+ export class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(
53
+ "DurableAlarmError",
54
+ {
55
+ operation: Schema.String,
56
+ message: Schema.String,
57
+ cause: Schema.optionalKey(Schema.Defect()),
58
+ },
59
+ ) {}
60
+
61
+ const alarmFailure =
62
+ (operation: string) =>
63
+ (cause: unknown): DurableAlarmError =>
64
+ DurableAlarmError.make({
65
+ operation,
66
+ message: safeCauseMessage(cause, "The Cloudflare alarm API failed without a diagnostic"),
67
+ cause,
68
+ });
69
+
70
+ // SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its
71
+ // connection for each short storage operation, never around a mutation or snapshot body.
72
+ const makeStorageOperation = Effect.map(
73
+ SqlClient,
74
+ (sql) =>
75
+ <A>(operation: string, execute: () => Promise<A>) =>
76
+ Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {
77
+ const body = Effect.uninterruptible(
78
+ Effect.tryPromise({ try: execute, catch: alarmFailure(operation) }),
79
+ );
80
+
81
+ return current._tag === "Some"
82
+ ? body
83
+ : Effect.scoped(
84
+ Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body),
85
+ );
86
+ }),
87
+ );
88
+
89
+ /** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */
90
+ export class DurableAlarmService extends Context.Service<
91
+ DurableAlarmService,
92
+ {
93
+ /** The scheduled deadline in epoch milliseconds, if any. */
94
+ readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;
95
+ /** Replace the slot with this deadline. */
96
+ readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;
97
+ /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */
98
+ readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;
99
+ /**
100
+ * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a
101
+ * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new
102
+ * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the
103
+ * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass
104
+ * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)
105
+ * would kill the running Attempt — manufacturing an ownership loss no real eviction
106
+ * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.
107
+ * Deferral is contract-safe: wakes are droppable hints, every mutating entry point
108
+ * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this
109
+ * call). The pass's durable generation check observes any racing mutation, so the
110
+ * in-memory hint does not need to be flushed after a stable wait is acknowledged.
111
+ */
112
+ readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;
113
+ /**
114
+ * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`
115
+ * executes are droppable promptness hints; correctness rests on the durable generation.
116
+ */
117
+ readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
118
+ /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */
119
+ readonly cancel: Effect.Effect<void, DurableAlarmError>;
120
+ }
121
+ >()("@effect-agent/platform-cloudflare/DurableAlarmService") {
122
+ static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext | SqlClient> =
123
+ Layer.effect(DurableAlarmService)(
124
+ Effect.gen(function* () {
125
+ const { ctx } = yield* DurableObjectContext;
126
+ /**
127
+ * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no
128
+ * running pass, and a deferred wake lost to eviction was only ever a promptness hint
129
+ * on top of the already-committed pre-armed alarm.
130
+ */
131
+ const runningPasses = yield* Ref.make(0);
132
+
133
+ const storageOperation = yield* makeStorageOperation;
134
+
135
+ const scheduled = storageOperation("get alarm", () => ctx.storage.getAlarm()).pipe(
136
+ Effect.map((deadline) =>
137
+ deadline === null ? Option.none<number>() : Option.some(deadline),
138
+ ),
139
+ );
140
+
141
+ const scheduleAt = (epochMillis: number) =>
142
+ storageOperation("set alarm", () => ctx.storage.setAlarm(epochMillis));
143
+
144
+ const ensureScheduledBy = (epochMillis: number) =>
145
+ storageOperation("ensure alarm", () =>
146
+ ctx.storage.transaction(async (transaction) => {
147
+ const existing = await transaction.getAlarm();
148
+
149
+ if (existing === null || existing > epochMillis) {
150
+ await transaction.setAlarm(epochMillis);
151
+ }
152
+ }),
153
+ );
154
+
155
+ const armNow = Clock.currentTimeMillis.pipe(
156
+ Effect.flatMap((now) => ensureScheduledBy(now)),
157
+ );
158
+
159
+ const scheduleNow = Ref.get(runningPasses).pipe(
160
+ Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),
161
+ );
162
+
163
+ const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
164
+ Ref.update(runningPasses, (passes) => passes + 1).pipe(
165
+ Effect.andThen(body),
166
+ Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),
167
+ );
168
+
169
+ const cancel = storageOperation("delete alarm", () => ctx.storage.deleteAlarm());
170
+
171
+ return DurableAlarmService.of({
172
+ scheduled,
173
+ scheduleAt,
174
+ ensureScheduledBy,
175
+ scheduleNow,
176
+ withWakesDeferred,
177
+ cancel,
178
+ });
179
+ }),
180
+ );
181
+ }
182
+
183
+ /** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
184
+ export class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(
185
+ "@effect-agent/platform-cloudflare/MaintenancePassReport",
186
+ )({
187
+ /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
188
+ phase: Schema.Literals(["caught-up", "actionable"]),
189
+ /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
190
+ recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
191
+ /** Whether the head Attempt settled. Joined input may settle with that head. */
192
+ settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
193
+ /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
194
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
195
+ /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */
196
+ alarm: Schema.Literals(["rearmed", "cleared"]),
197
+ }) {}
198
+
199
+ /** Fault boundaries around every maintenance-owned durable mutation. */
200
+ export type ThreadMaintenanceFailpointLocation =
201
+ | "maintenance:dirty:before"
202
+ | "maintenance:dirty:after"
203
+ | "maintenance:mutation:armed"
204
+ | "maintenance:mutation:finished"
205
+ | "maintenance:ensure:before"
206
+ | "maintenance:ensure:after"
207
+ | "maintenance:begin:before"
208
+ | "maintenance:begin:after"
209
+ | "maintenance:select:before"
210
+ | "maintenance:select:after"
211
+ | "maintenance:binding-retry:before"
212
+ | "maintenance:binding-retry:after"
213
+ | "maintenance:retry:before"
214
+ | "maintenance:retry:after"
215
+ | "maintenance:finish:before"
216
+ | "maintenance:finish:after";
217
+
218
+ export type ThreadMaintenanceFailpointHandler = (
219
+ location: ThreadMaintenanceFailpointLocation,
220
+ ) => Effect.Effect<void>;
221
+
222
+ /** Test-only fault authority; production uses the inert layer. */
223
+ export class ThreadMaintenanceFailpoint extends Context.Service<
224
+ ThreadMaintenanceFailpoint,
225
+ {
226
+ readonly hit: ThreadMaintenanceFailpointHandler;
227
+ }
228
+ >()("@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint") {
229
+ static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });
230
+ }
231
+
232
+ /**
233
+ * Durable host publication of canonical records and ledger approval/abort/resolution intents.
234
+ * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery
235
+ * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.
236
+ *
237
+ * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.
238
+ * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated
239
+ * calls must preserve partial scan progress. It runs with no source mutation in flight.
240
+ * Use this gate only for publication required before dependent native execution. Independent
241
+ * UI relays and outboxes belong to ThreadHostMaintenance.
242
+ * `drain` performs bounded delivery and persists retries before returning. A pending deadline
243
+ * defers runtime recovery/Attempts, allowing committed host publications to drain first.
244
+ * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call
245
+ * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need
246
+ * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.
247
+ */
248
+ export interface ThreadPublicationService {
249
+ readonly invalidate: Effect.Effect<void, DurableAlarmError>;
250
+ readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;
251
+ readonly drain: Effect.Effect<void, DurableAlarmError>;
252
+ readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
253
+ }
254
+
255
+ /** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
256
+ export class ThreadPublication extends Context.Service<
257
+ ThreadPublication,
258
+ ThreadPublicationService
259
+ >()("@effect-agent/platform-cloudflare/ThreadPublication") {
260
+ static readonly layer = Layer.succeed(this)({
261
+ invalidate: Effect.void,
262
+ prepareGeneration: () => Effect.void,
263
+ drain: Effect.void,
264
+ pendingDeadline: Effect.succeed(Option.none()),
265
+ });
266
+ }
267
+
268
+ /**
269
+ * Host-assembled native message recovery. The driver bounds each actual Claim and persists its
270
+ * timeout/retry before this pump returns. Do not add a second timer starting at batch selection:
271
+ * local Claim setup may take time, and expiration still owes the driver's local retry commit.
272
+ */
273
+ export const ThreadMessageDelivery = Context.Reference<{
274
+ readonly drainUntil: (
275
+ sourceFinished: Effect.Effect<void>,
276
+ dispatchUntil: DateTime.Utc,
277
+ ) => Effect.Effect<void, DurableAlarmError, Scope.Scope>;
278
+ readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
279
+ }>("@effect-agent/platform-cloudflare/ThreadMessageDelivery", {
280
+ defaultValue: () => ({
281
+ drainUntil: () => Effect.void,
282
+ pendingDeadline: Effect.succeed(Option.none()),
283
+ }),
284
+ });
285
+
286
+ /**
287
+ * Application obligations sharing this Object's alarm. Admit one initial external wave even on
288
+ * a caught-up pass, then respond to wakes while native work runs. sourceFinished closes only
289
+ * admission of NEW external waves. Keep local admission/hub subscriptions in the supplied event
290
+ * Scope until maintenance tears it down; do not scope them to sourceFinished or to this Effect.
291
+ * No deadline sleeps or automatic retry loops. Return after already-admitted waves finish.
292
+ *
293
+ * Declare a finite whole-wave allowance (1..300000ms): maximum for parallel lanes, sum for
294
+ * sequential operations. Admit a wave only if its allowance fits before dispatchUntil. Later
295
+ * arrivals cannot renew the retirement window. Maintenance bounds the join after sourceFinished,
296
+ * interrupts and joins event Scope, then reads local deadlines under the mutation gate.
297
+ *
298
+ * Setup and pendingDeadline are bounded local operations. Persist claims/envelopes before
299
+ * dispatch; interrupted waits leave exact retries/receipts recoverable. Cancellation is local,
300
+ * not remote rollback. Retry accounting is unchanged. Network waits/finalizers must be
301
+ * interruptible; short local atomic commits may be uninterruptible. Hooks never write the raw
302
+ * alarm slot. Required native publication gates belong to ThreadPublication.
303
+ */
304
+ export const ThreadHostMaintenance = Context.Reference<{
305
+ readonly dispatchTimeoutMillis: number;
306
+ readonly drainUntil: (
307
+ sourceFinished: Effect.Effect<void>,
308
+ dispatchUntil: DateTime.Utc,
309
+ ) => Effect.Effect<void, DurableAlarmError, Scope.Scope>;
310
+ readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
311
+ }>("@effect-agent/platform-cloudflare/ThreadHostMaintenance", {
312
+ defaultValue: () => ({
313
+ dispatchTimeoutMillis: 1,
314
+ drainUntil: () => Effect.void,
315
+ pendingDeadline: Effect.succeed(Option.none()),
316
+ }),
317
+ });
318
+
319
+ const earliestDeadline = (
320
+ left: Option.Option<number>,
321
+ right: Option.Option<number>,
322
+ ): Option.Option<number> =>
323
+ Option.isSome(left)
324
+ ? Option.isSome(right)
325
+ ? Option.some(Math.min(left.value, right.value))
326
+ : left
327
+ : right;
328
+
329
+ /** @internal A committed source operation must not become a failed operation because delivery failed. */
330
+ export const publishCommitted = Effect.gen(function* () {
331
+ const publication = yield* ThreadPublication;
332
+
333
+ yield* publication.invalidate.pipe(Effect.andThen(publication.drain));
334
+ }).pipe(
335
+ Effect.catchCause((cause) =>
336
+ Cause.hasInterrupts(cause)
337
+ ? Effect.interrupt
338
+ : Effect.logError("Thread publication deferred after source commit", cause),
339
+ ),
340
+ );
341
+
342
+ const MaintenanceGeneration = Schema.BigIntFromString.check(
343
+ Schema.isGreaterThanOrEqualToBigInt(0n),
344
+ );
345
+
346
+ class BindingRetry extends Schema.Class<BindingRetry>("BindingRetry")({
347
+ threadId: ThreadId,
348
+ submissionId: SubmissionId,
349
+ attempts: Schema.Natural,
350
+ notBefore: Schema.Finite,
351
+ reportedAt: Schema.Finite,
352
+ }) {}
353
+
354
+ interface MaintenanceObservation {
355
+ generation?: bigint;
356
+ nativeOnly: boolean;
357
+ }
358
+
359
+ class MaintenanceRetry extends Schema.Class<MaintenanceRetry>("MaintenanceRetry")({
360
+ generation: MaintenanceGeneration,
361
+ notBefore: Schema.Finite,
362
+ nativeOnly: Schema.Boolean,
363
+ stalls: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(30)),
364
+ }) {}
365
+
366
+ /** Versioned, platform-private maintenance state stored through Durable Object KV. */
367
+ class ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(
368
+ "@effect-agent/platform-cloudflare/ThreadMaintenanceState",
369
+ )({
370
+ schemaVersion: Schema.Literal(1),
371
+ dirty: MaintenanceGeneration,
372
+ processed: MaintenanceGeneration,
373
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
374
+ /** One physical-owner cursor; old single-lane records need no conversion. */
375
+ lastServedThreadId: Schema.optionalKey(ThreadId),
376
+ bindingRetries: Schema.optionalKey(Schema.Array(BindingRetry)),
377
+ /** Absent on older records. A newer mutation makes this retry obsolete. */
378
+ retry: Schema.optionalKey(MaintenanceRetry),
379
+ }) {}
380
+
381
+ const MAINTENANCE_STATE_KEY = "effect-agent:thread-maintenance:v1";
382
+ const decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);
383
+ const encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);
384
+
385
+ const initialMaintenanceState = (): ThreadMaintenanceState =>
386
+ ThreadMaintenanceState.make({
387
+ schemaVersion: 1,
388
+ // Bootstrap Objects created by the pre-generation release without scanning the ledger in
389
+ // the constructor. One useful pass classifies and acknowledges any existing obligation.
390
+ dirty: 1n,
391
+ processed: 0n,
392
+ nonterminal: 0,
393
+ });
394
+
395
+ const readMaintenanceState = async (
396
+ transaction: DurableObjectTransaction,
397
+ ): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {
398
+ const encoded = await transaction.get(MAINTENANCE_STATE_KEY);
399
+
400
+ return encoded === undefined
401
+ ? { state: initialMaintenanceState(), initialized: false }
402
+ : { state: decodeMaintenanceState(encoded), initialized: true };
403
+ };
404
+
405
+ const ensureTransactionAlarmBy = async (
406
+ transaction: DurableObjectTransaction,
407
+ deadline: number,
408
+ ): Promise<void> => {
409
+ const scheduled = await transaction.getAlarm();
410
+
411
+ if (scheduled === null || scheduled > deadline) {
412
+ await transaction.setAlarm(deadline);
413
+ }
414
+ };
415
+
416
+ const stableExternalWait = (
417
+ snapshot: SubmissionSnapshot,
418
+ reports: ReadonlyMap<string, RecoveryReport>,
419
+ ): boolean => {
420
+ const report = reports.get(snapshot.submissionId);
421
+ const decision = report?.decision._tag;
422
+
423
+ // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.
424
+ if (decision === "SettleAborted") return false;
425
+ switch (snapshot.state) {
426
+ case "suspended":
427
+ case "joined":
428
+ return true;
429
+ case "unknown":
430
+ return report?.disposition === "unknown";
431
+ case "admitted":
432
+ return reports.get(snapshot.submissionId)?.decision._tag === "AwaitParentEstablishment";
433
+ case "input-applied":
434
+ case "joining":
435
+ case "ready":
436
+ case "running":
437
+ case "settled":
438
+ case "terminalizing":
439
+ return false;
440
+ }
441
+ };
442
+
443
+ /**
444
+ * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
445
+ * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
446
+ * Layers must reuse that instance; a second gate cannot observe the native producers' activity.
447
+ */
448
+ export class ThreadMutationGate extends Context.Service<
449
+ ThreadMutationGate,
450
+ {
451
+ readonly withMutation: <A, E, R>(
452
+ body: Effect.Effect<A, E, R>,
453
+ /**
454
+ * Native admission, approval, abort and unknown resolution keep the default true.
455
+ * Projection/relay/reply receipt-only bookkeeping must use false: its local durable
456
+ * pendingDeadline owns scheduling without creating native recovery debt.
457
+ */
458
+ options?: { readonly invalidatesRecovery: boolean },
459
+ ) => Effect.Effect<A, E | DurableAlarmError, R>;
460
+ readonly withSnapshot: <A, E, R>(
461
+ body: (active: number) => Effect.Effect<A, E, R>,
462
+ ) => Effect.Effect<A, E, R>;
463
+ }
464
+ >()("@effect-agent/platform-cloudflare/internal/ThreadMutationGate") {
465
+ static readonly layer = Layer.effect(this)(
466
+ Effect.gen(function* () {
467
+ const { ctx } = yield* DurableObjectContext;
468
+ const config = yield* CloudflareDurableRuntimeConfig;
469
+ const failpoint = yield* ThreadMaintenanceFailpoint;
470
+ // A fresh incarnation has no live mutations; durable generations survive eviction.
471
+ const activeMutations = yield* Ref.make(0);
472
+ const generationGate = yield* Semaphore.make(1);
473
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
474
+
475
+ const runTransaction = yield* makeStorageOperation;
476
+
477
+ const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* (
478
+ invalidatesRecovery: boolean,
479
+ ) {
480
+ yield* failpoint.hit("maintenance:dirty:before");
481
+ const now = yield* Clock.currentTimeMillis;
482
+
483
+ yield* runTransaction("advance maintenance generation", () =>
484
+ ctx.storage.transaction(async (transaction) => {
485
+ const { state, initialized } = await readMaintenanceState(transaction);
486
+
487
+ const next = ThreadMaintenanceState.make({
488
+ ...state,
489
+ dirty: state.dirty + (invalidatesRecovery ? 1n : 0n),
490
+ });
491
+
492
+ if (invalidatesRecovery || !initialized)
493
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
494
+ // The earliest configured retry bounds a newly actionable mutation without relying
495
+ // on its best-effort immediate wake hint.
496
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
497
+ }),
498
+ );
499
+ yield* failpoint.hit("maintenance:dirty:after");
500
+ yield* Ref.update(activeMutations, (active) => active + 1);
501
+ });
502
+
503
+ const endMutation = generationGate.withPermit(
504
+ Ref.update(activeMutations, (active) => Math.max(0, active - 1)),
505
+ );
506
+
507
+ const withMutation = <A, E, R>(
508
+ body: Effect.Effect<A, E, R>,
509
+ options?: { readonly invalidatesRecovery: boolean },
510
+ ): Effect.Effect<A, E | DurableAlarmError, R> =>
511
+ Effect.acquireUseRelease(
512
+ generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true)),
513
+ () =>
514
+ failpoint.hit("maintenance:mutation:armed").pipe(
515
+ Effect.andThen(body),
516
+ Effect.tap(() => failpoint.hit("maintenance:mutation:finished")),
517
+ ),
518
+ () => endMutation,
519
+ );
520
+
521
+ return ThreadMutationGate.of({
522
+ withMutation,
523
+ withSnapshot: (body) =>
524
+ generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),
525
+ });
526
+ }),
527
+ );
528
+ }
529
+
530
+ export type MaintenancePassFailure =
531
+ | DurableWorkerFailure
532
+ | DurableBindingFailure
533
+ | DurableAlarmError
534
+ | ThreadProjectionError;
535
+
536
+ /**
537
+ * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
538
+ *
539
+ * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:
540
+ *
541
+ * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced
542
+ * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.
543
+ * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests
544
+ * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.
545
+ * 3. Auxiliary dispatch and listeners belong to the event Scope. After native completion,
546
+ * stop new external waves, join native delivery through its driver-owned Claim deadline,
547
+ * and bound host/backfill work by explicit allowances before closing and joining Scope.
548
+ * Ordinary auxiliary setup failures are reported after the one native opportunity.
549
+ * 4. The final transaction acknowledges only the generation observed at pass start. A racing
550
+ * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.
551
+ * 5. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease
552
+ * recovery states leave their generation dirty and retain bounded backoff rearming.
553
+ */
554
+ export class ThreadMaintenance extends Context.Service<
555
+ ThreadMaintenance,
556
+ {
557
+ /** One idempotent pass; failures propagate after durably scheduling bounded recovery. */
558
+ readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;
559
+ /**
560
+ * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty
561
+ * generation has an alarm. It never scans the ledger or canonical history.
562
+ */
563
+ readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;
564
+ /**
565
+ * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty
566
+ * generation and arm the alarm in one transaction BEFORE running the caller's mutation.
567
+ * A pass cannot acknowledge while that mutation remains in flight.
568
+ */
569
+ readonly withMutation: <A, E, R>(
570
+ body: Effect.Effect<A, E, R>,
571
+ ) => Effect.Effect<A, E | DurableAlarmError, R>;
572
+ }
573
+ >()("@effect-agent/platform-cloudflare/ThreadMaintenance") {
574
+ static readonly layer: Layer.Layer<
575
+ ThreadMaintenance,
576
+ never,
577
+ | ThreadMutationGate
578
+ | ThreadPublication
579
+ | ThreadProjectionMaintenance
580
+ | DurableAgentRuntime
581
+ | SubmissionLedger
582
+ | DurableAlarmService
583
+ | ThreadMaintenanceFailpoint
584
+ | CloudflareDurableRuntimeConfig
585
+ | DurableObjectContext
586
+ | SqlClient
587
+ > = Layer.effect(ThreadMaintenance)(
588
+ Effect.gen(function* () {
589
+ const runtime = yield* DurableAgentRuntime;
590
+ const ledger = yield* SubmissionLedger;
591
+ const alarm = yield* DurableAlarmService;
592
+ const config = yield* CloudflareDurableRuntimeConfig;
593
+ const { ctx } = yield* DurableObjectContext;
594
+ const failpoint = yield* ThreadMaintenanceFailpoint;
595
+
596
+ const mutations = yield* ThreadMutationGate;
597
+ const publication = yield* ThreadPublication;
598
+ const projection = yield* ThreadProjectionMaintenance;
599
+ const messages = yield* ThreadMessageDelivery;
600
+ const host = yield* ThreadHostMaintenance;
601
+
602
+ // A broken disposable index still needs a retry alarm and must not prevent startup.
603
+ const projectionDeadline = projection.pendingDeadline.pipe(
604
+ Effect.catchCauseIf(
605
+ (cause) => !Cause.hasInterrupts(cause),
606
+ (cause) =>
607
+ Effect.logError("Thread projection deadline unavailable", cause).pipe(
608
+ Effect.as(Option.some(0)),
609
+ ),
610
+ ),
611
+ );
612
+
613
+ const pendingDeadline = Effect.gen(function* () {
614
+ return earliestDeadline(
615
+ earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),
616
+ earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline),
617
+ );
618
+ });
619
+
620
+ const maintenancePassGate = yield* Semaphore.make(1);
621
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
622
+
623
+ const runTransaction = yield* makeStorageOperation;
624
+
625
+ const ensureAlarm = Effect.fn("ThreadMaintenance.ensureAlarm")(function* () {
626
+ yield* failpoint.hit("maintenance:ensure:before");
627
+ const now = yield* Clock.currentTimeMillis;
628
+
629
+ const retry = yield* runTransaction("ensure maintenance alarm", () =>
630
+ ctx.storage.transaction(async (transaction) => {
631
+ const { state, initialized } = await readMaintenanceState(transaction);
632
+
633
+ if (!initialized) {
634
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
635
+ }
636
+ if (state.dirty > state.processed) {
637
+ await ensureTransactionAlarmBy(
638
+ transaction,
639
+ state.retry?.generation === state.dirty
640
+ ? Math.max(now + minimumAlarmDelay, state.retry.notBefore)
641
+ : now + config.wakeScanInterval,
642
+ );
643
+ }
644
+
645
+ return state.retry?.generation === state.dirty ? state.retry : undefined;
646
+ }),
647
+ );
648
+
649
+ const deadline = yield* pendingDeadline;
650
+
651
+ if (Option.isSome(deadline)) {
652
+ yield* runTransaction("ensure publication alarm", () =>
653
+ ctx.storage.transaction((transaction) =>
654
+ ensureTransactionAlarmBy(
655
+ transaction,
656
+ Math.max(
657
+ now + minimumAlarmDelay,
658
+ deadline.value <= now && retry !== undefined && !retry.nativeOnly
659
+ ? Math.max(deadline.value, retry.notBefore)
660
+ : deadline.value,
661
+ ),
662
+ ),
663
+ ),
664
+ );
665
+ }
666
+ yield* failpoint.hit("maintenance:ensure:after");
667
+ });
668
+
669
+ const beginPass = Effect.fn("ThreadMaintenance.beginPass")(function* (observed: {
670
+ generation?: bigint;
671
+ }) {
672
+ yield* failpoint.hit("maintenance:begin:before");
673
+ const now = yield* Clock.currentTimeMillis;
674
+
675
+ const result = yield* runTransaction("begin maintenance pass", () =>
676
+ ctx.storage.transaction(async (transaction) => {
677
+ const { state, initialized } = await readMaintenanceState(transaction);
678
+
679
+ observed.generation = state.dirty;
680
+ if (!initialized) {
681
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
682
+ }
683
+ const retryAt = state.retry?.generation === state.dirty ? state.retry.notBefore : 0;
684
+
685
+ // Prearm before recovery or any host hook, including publication-only passes.
686
+ // A completed pass may move this crash fallback later to its bounded retry.
687
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
688
+ if (state.processed >= state.dirty || retryAt > now) {
689
+ return {
690
+ _tag: "CaughtUp" as const,
691
+ nonterminal: state.nonterminal,
692
+ };
693
+ }
694
+
695
+ return {
696
+ _tag: "Actionable" as const,
697
+ generation: state.dirty,
698
+ nonterminal: state.nonterminal,
699
+ stalls: state.retry?.generation === state.dirty ? state.retry.stalls : 0,
700
+ };
701
+ }),
702
+ );
703
+
704
+ yield* failpoint.hit("maintenance:begin:after");
705
+
706
+ return result;
707
+ });
708
+
709
+ const backoffDelay = (priorStalls: number, jitter: number) => {
710
+ const backoff = Math.min(
711
+ config.alarmBackoffCap,
712
+ config.alarmBackoffBase * 2 ** Math.min(priorStalls, 30),
713
+ );
714
+
715
+ // Jitter over [backoff/2, backoff] spreads retries without exceeding the cap.
716
+ return Math.ceil(backoff / 2 + (backoff / 2) * jitter);
717
+ };
718
+
719
+ const rearmDelay = Effect.fn("ThreadMaintenance.rearmDelay")(function* (
720
+ progressed: boolean,
721
+ priorStalls: number,
722
+ ) {
723
+ return progressed ? config.alarmBackoffBase : backoffDelay(priorStalls, yield* Random.next);
724
+ });
725
+
726
+ const rearmFailure = Effect.fn("ThreadMaintenance.rearmFailure")(function* (
727
+ observed: MaintenanceObservation,
728
+ ) {
729
+ const { generation, nativeOnly } = observed;
730
+
731
+ if (generation === undefined) return;
732
+ yield* failpoint.hit("maintenance:retry:before");
733
+ yield* mutations.withSnapshot((active) =>
734
+ Effect.gen(function* () {
735
+ // A failed deadline read must not prevent committing the native retry.
736
+ const deadline = yield* pendingDeadline.pipe(
737
+ Effect.catchCause(() => Effect.succeed(Option.none<number>())),
738
+ );
739
+
740
+ const now = yield* Clock.currentTimeMillis;
741
+
742
+ const jitter = yield* Random.next;
743
+
744
+ yield* runTransaction("back off failed maintenance", () =>
745
+ ctx.storage.transaction(async (transaction) => {
746
+ const { state } = await readMaintenanceState(transaction);
747
+
748
+ const previous = state.retry?.generation === generation ? state.retry : undefined;
749
+
750
+ const retry = MaintenanceRetry.make({
751
+ generation,
752
+ notBefore: Math.max(
753
+ previous?.notBefore ?? 0,
754
+ now + backoffDelay(previous?.stalls ?? 0, jitter),
755
+ ),
756
+ nativeOnly,
757
+ stalls: Math.min(30, (previous?.stalls ?? 0) + 1),
758
+ });
759
+
760
+ await transaction.put(
761
+ MAINTENANCE_STATE_KEY,
762
+ encodeMaintenanceState(ThreadMaintenanceState.make({ ...state, retry })),
763
+ );
764
+
765
+ // Never postpone a producer that raced the failed observation. Host work
766
+ // retains its own deadline; an early delivery skips native recovery below.
767
+ const nativeDeadline =
768
+ active > 0 || state.dirty !== generation
769
+ ? now + minimumAlarmDelay
770
+ : retry.notBefore;
771
+
772
+ await transaction.setAlarm(
773
+ Math.max(
774
+ now + minimumAlarmDelay,
775
+ Option.isSome(deadline) && (nativeOnly || deadline.value > now)
776
+ ? Math.min(nativeDeadline, deadline.value)
777
+ : nativeDeadline,
778
+ ),
779
+ );
780
+ }),
781
+ );
782
+ }),
783
+ );
784
+ yield* failpoint.hit("maintenance:retry:after");
785
+ });
786
+
787
+ const pass = Effect.fn("ThreadMaintenance.pass")(function* (
788
+ yieldAfter: DateTime.Utc,
789
+ dispatchUntil: DateTime.Utc,
790
+ observed: MaintenanceObservation,
791
+ ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure, Scope.Scope> {
792
+ const annotate = (report: MaintenancePassReport) =>
793
+ Effect.annotateCurrentSpan({
794
+ phase: report.phase,
795
+ recovered: report.recovered,
796
+ settled: report.settled,
797
+ nonterminal: report.nonterminal,
798
+ alarm: report.alarm,
799
+ }).pipe(Effect.as(report));
800
+
801
+ const started = yield* mutations.withSnapshot((activeAtStart) =>
802
+ Effect.gen(function* () {
803
+ const generation = yield* beginPass(observed);
804
+
805
+ if (generation._tag === "Actionable" && activeAtStart === 0) {
806
+ // The gate excludes a producer starting between the snapshot and certification.
807
+ yield* publication.prepareGeneration(generation.generation);
808
+ }
809
+
810
+ return { ...generation, activeAtStart };
811
+ }),
812
+ );
813
+
814
+ // This scope owns auxiliary dispatch and listeners, independently of source completion.
815
+ // Close it before acknowledgement, including on failure or event interruption.
816
+ const auxiliaryScope = yield* Effect.acquireRelease(Scope.make("parallel"), (scope, exit) =>
817
+ Scope.close(scope, exit),
818
+ );
819
+
820
+ const sourceFinished = yield* Deferred.make<void>();
821
+ const finished = Deferred.await(sourceFinished);
822
+
823
+ // Fork setup too: an ordinary auxiliary setup failure is reported after native work,
824
+ // rather than gating its opportunity. Event interruption still closes every fiber.
825
+ const deliveryFiber = yield* Effect.forkIn(
826
+ Scope.provide(auxiliaryScope)(messages.drainUntil(finished, dispatchUntil)),
827
+ auxiliaryScope,
828
+ );
829
+
830
+ const hostFiber = yield* Effect.forkIn(
831
+ Scope.provide(auxiliaryScope)(
832
+ Effect.gen(function* () {
833
+ yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(host.dispatchTimeoutMillis).pipe(
834
+ Effect.mapError((cause) =>
835
+ DurableAlarmError.make({
836
+ operation: "host dispatch allowance",
837
+ message:
838
+ "Declare an integer whole-wave allowance between 1 and 300000 milliseconds",
839
+ cause,
840
+ }),
841
+ ),
842
+ );
843
+ yield* host.drainUntil(finished, dispatchUntil);
844
+ }),
845
+ ),
846
+ auxiliaryScope,
847
+ );
848
+
849
+ // Backfill is one disposable wave; its timer starts beside native execution.
850
+ const backfill = yield* Effect.forkIn(
851
+ drainDue.pipe(
852
+ Effect.provideService(ThreadProjectionMaintenance, projection),
853
+ Effect.timeoutOption(config.projectionDispatchTimeoutMillis),
854
+ ),
855
+ auxiliaryScope,
856
+ );
857
+
858
+ const finishAuxiliary = Effect.gen(function* () {
859
+ yield* Deferred.succeed(sourceFinished, undefined);
860
+
861
+ const remaining = Math.max(
862
+ 1,
863
+ DateTime.toEpochMillis(dispatchUntil) - (yield* Clock.currentTimeMillis),
864
+ );
865
+
866
+ const hostJoin = yield* Effect.forkIn(
867
+ Fiber.join(hostFiber).pipe(
868
+ Effect.timeoutOption(Math.min(host.dispatchTimeoutMillis, remaining)),
869
+ Effect.tap((result) =>
870
+ Effect.annotateCurrentSpan({ "host.timedOut": Option.isNone(result) }),
871
+ ),
872
+ ),
873
+ auxiliaryScope,
874
+ );
875
+
876
+ // Native transport uses the driver's actual Claim deadline, through Retry persistence.
877
+ // Only our host/backfill timers suppress their own interruption. Earlier failed exits,
878
+ // including pure self-interruption, remain failures while siblings are still blocked.
879
+ yield* Fiber.joinAll([deliveryFiber, hostJoin, backfill]);
880
+ yield* Scope.close(auxiliaryScope, Exit.void);
881
+ });
882
+
883
+ const deadline = yield* publication.pendingDeadline;
884
+
885
+ if (
886
+ started._tag === "Actionable" ||
887
+ (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))
888
+ ) {
889
+ yield* publication.drain;
890
+ }
891
+ const pending = yield* publication.pendingDeadline;
892
+
893
+ if (started._tag === "CaughtUp" || Option.isSome(pending)) {
894
+ yield* finishAuxiliary;
895
+ yield* failpoint.hit("maintenance:finish:before");
896
+
897
+ const disposition = yield* mutations.withSnapshot((active) =>
898
+ Effect.gen(function* () {
899
+ // Re-read under the producer gate: a concurrent append/host mutation cannot be
900
+ // cleared using a stale empty deadline. Dirty generations bound all producer races.
901
+ const latest = yield* pendingDeadline;
902
+ const now = yield* Clock.currentTimeMillis;
903
+
904
+ return yield* runTransaction("finish publication pass", () =>
905
+ ctx.storage.transaction(async (transaction) => {
906
+ const { state } = await readMaintenanceState(transaction);
907
+
908
+ const nativeDeadline =
909
+ active > 0 || state.dirty > state.processed
910
+ ? state.retry?.generation === state.dirty && active === 0
911
+ ? Math.max(now + minimumAlarmDelay, state.retry.notBefore)
912
+ : now + config.wakeScanInterval
913
+ : Infinity;
914
+
915
+ const next = Option.isSome(latest)
916
+ ? Math.min(nativeDeadline, latest.value)
917
+ : nativeDeadline;
918
+
919
+ if (Number.isFinite(next)) {
920
+ await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));
921
+
922
+ return "rearmed" as const;
923
+ }
924
+ await transaction.deleteAlarm();
925
+
926
+ return "cleared" as const;
927
+ }),
928
+ );
929
+ }),
930
+ );
931
+
932
+ yield* failpoint.hit("maintenance:finish:after");
933
+
934
+ return yield* annotate(
935
+ MaintenancePassReport.make({
936
+ phase: "caught-up",
937
+ recovered: 0,
938
+ settled: 0,
939
+ nonterminal: started.nonterminal,
940
+ alarm: disposition,
941
+ }),
942
+ );
943
+ }
944
+ // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).
945
+ observed.nativeOnly = true;
946
+ const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;
947
+ const reports = new Map(recovered.map((report) => [report.submissionId, report]));
948
+ const current = yield* Stream.runCollect(ledger.scanNonterminal);
949
+ const heads = new Map<ThreadId, SubmissionSnapshot>();
950
+
951
+ for (const row of current) {
952
+ // Parked uncertainty keeps its settlement obligation, but later input can run.
953
+ // Accepted aborts and every other wait remain subject to the lane's FIFO barrier.
954
+ if (row.state === "unknown" && stableExternalWait(row, reports)) continue;
955
+ if (!heads.has(row.threadId)) heads.set(row.threadId, row);
956
+ }
957
+
958
+ const eligible = [...heads.values()]
959
+ .filter((head) => !stableExternalWait(head, reports))
960
+ .map((head) => head.threadId)
961
+ .sort();
962
+
963
+ const selectionTime = yield* Clock.currentTimeMillis;
964
+
965
+ yield* failpoint.hit("maintenance:select:before");
966
+
967
+ const selection = yield* runTransaction("select maintenance lane", () =>
968
+ ctx.storage.transaction(async (transaction) => {
969
+ const { state } = await readMaintenanceState(transaction);
970
+
971
+ const retries = (state.bindingRetries ?? []).filter(
972
+ (retry) => heads.get(retry.threadId)?.submissionId === retry.submissionId,
973
+ );
974
+
975
+ const runnable = eligible.filter(
976
+ (threadId) =>
977
+ !retries.some(
978
+ (retry) => retry.threadId === threadId && retry.notBefore > selectionTime,
979
+ ),
980
+ );
981
+
982
+ const next =
983
+ runnable.find(
984
+ (threadId) =>
985
+ state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,
986
+ ) ?? runnable[0];
987
+
988
+ if (next !== undefined) {
989
+ await transaction.put(
990
+ MAINTENANCE_STATE_KEY,
991
+ encodeMaintenanceState(
992
+ ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),
993
+ ),
994
+ );
995
+ }
996
+
997
+ return { selected: next, retries };
998
+ }),
999
+ );
1000
+
1001
+ yield* failpoint.hit("maintenance:select:after");
1002
+
1003
+ const selected =
1004
+ selection.selected === undefined ? undefined : heads.get(selection.selected);
1005
+
1006
+ let retries = selection.retries;
1007
+ let bindingFailure: DurableBindingFailure | undefined;
1008
+
1009
+ // One runnable FIFO head per event. An absent agent is a durable wait for a deployment,
1010
+ // including for children; other local lanes and host deliveries remain independently due.
1011
+ const settlement =
1012
+ selected === undefined
1013
+ ? Option.none()
1014
+ : yield* runtime.processThreadHead(selected.threadId, { yieldAfter }).pipe(
1015
+ Effect.catchTag("BindingUnavailable", (failure) => {
1016
+ bindingFailure = failure;
1017
+
1018
+ return Effect.succeed(Option.none());
1019
+ }),
1020
+ );
1021
+
1022
+ if (selected !== undefined) {
1023
+ const previous = retries.find((retry) => retry.submissionId === selected.submissionId);
1024
+ let retry: BindingRetry | undefined;
1025
+ let reportBindingFailure = false;
1026
+
1027
+ if (bindingFailure !== undefined) {
1028
+ const now = yield* Clock.currentTimeMillis;
1029
+ const attempts = Math.min(30, (previous?.attempts ?? 0) + 1);
1030
+
1031
+ reportBindingFailure =
1032
+ previous === undefined || now - previous.reportedAt >= 15 * 60_000;
1033
+ retry = BindingRetry.make({
1034
+ threadId: selected.threadId,
1035
+ submissionId: selected.submissionId,
1036
+ attempts,
1037
+ notBefore: now + Math.min(60_000, 5_000 * 2 ** (attempts - 1)),
1038
+ reportedAt: reportBindingFailure ? now : (previous?.reportedAt ?? now),
1039
+ });
1040
+ }
1041
+ if (retry !== undefined || previous !== undefined) {
1042
+ // The Attempt released its Claim. Commit its binding wait (or clear) once,
1043
+ // before joining fallible auxiliary work. This local fact neither acknowledges
1044
+ // a generation nor changes the shared alarm; those require event retirement.
1045
+ yield* failpoint.hit("maintenance:binding-retry:before");
1046
+ retries = yield* runTransaction("record submission binding retry", () =>
1047
+ ctx.storage.transaction(async (transaction) => {
1048
+ const { state } = await readMaintenanceState(transaction);
1049
+
1050
+ const bindingRetries = [
1051
+ ...(state.bindingRetries ?? []).filter(
1052
+ (entry) => entry.submissionId !== selected.submissionId,
1053
+ ),
1054
+ ...(retry === undefined ? [] : [retry]),
1055
+ ];
1056
+
1057
+ await transaction.put(
1058
+ MAINTENANCE_STATE_KEY,
1059
+ encodeMaintenanceState(ThreadMaintenanceState.make({ ...state, bindingRetries })),
1060
+ );
1061
+
1062
+ return bindingRetries;
1063
+ }),
1064
+ );
1065
+ yield* failpoint.hit("maintenance:binding-retry:after");
1066
+ }
1067
+ if (bindingFailure !== undefined) {
1068
+ yield* reportBindingFailure
1069
+ ? Effect.logError(
1070
+ "Thread awaits a current agent binding; original work remains pending",
1071
+ Cause.fail(bindingFailure),
1072
+ )
1073
+ : Effect.logDebug("Thread binding retry remains pending", Cause.fail(bindingFailure));
1074
+ }
1075
+ }
1076
+
1077
+ observed.nativeOnly = false;
1078
+ yield* finishAuxiliary;
1079
+ const remaining = yield* Stream.runCollect(ledger.scanNonterminal);
1080
+ const waitingHeads = new Map<ThreadId, boolean>();
1081
+
1082
+ const autonomous = remaining.some((snapshot) => {
1083
+ if (snapshot.state === "unknown" && stableExternalWait(snapshot, reports)) return false;
1084
+ const headWaiting = waitingHeads.get(snapshot.threadId);
1085
+
1086
+ if (headWaiting === undefined)
1087
+ waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));
1088
+ // FIFO followers cannot execute through a stable external wait. Only plain queued
1089
+ // input is dormant here; admission repairs and accepted aborts still need a pass.
1090
+ if (
1091
+ headWaiting === true &&
1092
+ snapshot.state === "ready" &&
1093
+ reports.get(snapshot.submissionId)?.decision._tag === "ApplyInput"
1094
+ )
1095
+ return false;
1096
+
1097
+ return !stableExternalWait(snapshot, reports);
1098
+ });
1099
+
1100
+ const progressed =
1101
+ Option.isSome(settlement) ||
1102
+ recovered.some((report) => report.disposition === "repaired");
1103
+
1104
+ const now = yield* Clock.currentTimeMillis;
1105
+ const ordinaryDelay = autonomous ? yield* rearmDelay(progressed, started.stalls) : 0;
1106
+
1107
+ const nextEligible = eligible.map(
1108
+ (threadId) =>
1109
+ retries.find((retry) => retry.submissionId === heads.get(threadId)?.submissionId)
1110
+ ?.notBefore ?? now,
1111
+ );
1112
+
1113
+ const bindingDelay =
1114
+ nextEligible.length === 0 ? 0 : Math.max(0, Math.min(...nextEligible) - now);
1115
+
1116
+ const delay = Math.max(ordinaryDelay, bindingDelay);
1117
+
1118
+ yield* failpoint.hit("maintenance:finish:before");
1119
+
1120
+ const alarmDisposition = yield* mutations.withSnapshot((active) =>
1121
+ Effect.gen(function* () {
1122
+ const publicationDeadline = yield* pendingDeadline;
1123
+
1124
+ return yield* runTransaction("finish maintenance pass", () =>
1125
+ ctx.storage.transaction(async (transaction) => {
1126
+ const { state } = await readMaintenanceState(transaction);
1127
+
1128
+ // Autonomous work and in-flight mutations intentionally leave the observed
1129
+ // generation dirty. Otherwise acknowledge only the pass-start generation.
1130
+ const processed =
1131
+ autonomous || started.activeAtStart > 0 || active > 0
1132
+ ? state.processed
1133
+ : state.processed > started.generation
1134
+ ? state.processed
1135
+ : started.generation;
1136
+
1137
+ const next = ThreadMaintenanceState.make({
1138
+ ...Struct.omit(state, ["retry"]),
1139
+ processed,
1140
+ nonterminal: remaining.length,
1141
+ bindingRetries: (state.bindingRetries ?? []).filter((retry) =>
1142
+ remaining.some((row) => row.submissionId === retry.submissionId),
1143
+ ),
1144
+ ...(autonomous && !progressed
1145
+ ? {
1146
+ retry: MaintenanceRetry.make({
1147
+ generation: started.generation,
1148
+ notBefore: now + delay,
1149
+ nativeOnly: true,
1150
+ stalls: Math.min(30, started.stalls + 1),
1151
+ }),
1152
+ }
1153
+ : {}),
1154
+ });
1155
+
1156
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
1157
+ if (autonomous) {
1158
+ // Replace the crash-fallback slot with this pass's bounded backoff. The target
1159
+ // is never earlier than the begin-pass fallback, so workerd does not cancel
1160
+ // this running alarm handler before its report/span can complete.
1161
+ const nativeDeadline =
1162
+ started.activeAtStart > 0 || active > 0 || state.dirty !== started.generation
1163
+ ? now + minimumAlarmDelay
1164
+ : now + delay;
1165
+
1166
+ await transaction.setAlarm(
1167
+ Option.isSome(publicationDeadline)
1168
+ ? Math.max(
1169
+ now + minimumAlarmDelay,
1170
+ Math.min(nativeDeadline, publicationDeadline.value),
1171
+ )
1172
+ : nativeDeadline,
1173
+ );
1174
+
1175
+ return "rearmed" as const;
1176
+ }
1177
+ if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {
1178
+ // A mutation overlapped this pass's observation window or raced
1179
+ // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;
1180
+ // unseen effects are never acknowledged. Do not accelerate that future alarm
1181
+ // from inside the current handler: workerd cancels a running handler when it
1182
+ // writes an earlier slot.
1183
+ await ensureTransactionAlarmBy(
1184
+ transaction,
1185
+ Option.isSome(publicationDeadline)
1186
+ ? Math.max(
1187
+ now + minimumAlarmDelay,
1188
+ Math.min(now + config.wakeScanInterval, publicationDeadline.value),
1189
+ )
1190
+ : now + config.wakeScanInterval,
1191
+ );
1192
+
1193
+ return "rearmed" as const;
1194
+ }
1195
+ if (Option.isSome(publicationDeadline)) {
1196
+ await transaction.setAlarm(
1197
+ Math.max(now + minimumAlarmDelay, publicationDeadline.value),
1198
+ );
1199
+
1200
+ return "rearmed" as const;
1201
+ }
1202
+ await transaction.deleteAlarm();
1203
+
1204
+ return "cleared" as const;
1205
+ }),
1206
+ );
1207
+ }),
1208
+ );
1209
+
1210
+ yield* failpoint.hit("maintenance:finish:after");
1211
+
1212
+ return yield* annotate(
1213
+ MaintenancePassReport.make({
1214
+ phase: "actionable",
1215
+ recovered: recovered.length,
1216
+ settled: Option.isSome(settlement) ? 1 : 0,
1217
+ nonterminal: remaining.length,
1218
+ alarm: alarmDisposition,
1219
+ }),
1220
+ );
1221
+ });
1222
+
1223
+ return ThreadMaintenance.of({
1224
+ // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.
1225
+ pass: Effect.gen(function* () {
1226
+ const now = yield* Clock.currentTimeMillis;
1227
+ const yieldAfter = DateTime.makeUnsafe(now + 10 * 60_000);
1228
+ const dispatchUntil = DateTime.makeUnsafe(now + 14 * 60_000);
1229
+ const observed: MaintenanceObservation = { nativeOnly: false };
1230
+
1231
+ return yield* alarm.withWakesDeferred(
1232
+ maintenancePassGate.withPermit(
1233
+ Effect.scoped(pass(yieldAfter, dispatchUntil, observed)).pipe(
1234
+ // Close event-owned auxiliary work and release Attempt ownership before
1235
+ // failure rearming, while still holding the pass permit.
1236
+ Effect.onErrorIf(
1237
+ () => true,
1238
+ () => rearmFailure(observed),
1239
+ ),
1240
+ ),
1241
+ ),
1242
+ );
1243
+ }).pipe(
1244
+ // Include permit waiting, recovery and acknowledgement in the event deadline.
1245
+ // Interruption releases Attempt ownership, leaving the prearmed dirty generation
1246
+ // for recovery. It never changes the logical Run duration or settles a policy failure.
1247
+ // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.
1248
+ Effect.timeoutOrElse({
1249
+ duration: "14 minutes",
1250
+ orElse: () =>
1251
+ DurableAlarmError.make({
1252
+ operation: "maintenance pass deadline",
1253
+ message:
1254
+ "The maintenance event exceeded its 14 minute deadline; durable recovery remains pending",
1255
+ }),
1256
+ }),
1257
+ ),
1258
+ ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),
1259
+ withMutation: (body) =>
1260
+ mutations.withMutation(
1261
+ body.pipe(
1262
+ Effect.tap(() =>
1263
+ publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),
1264
+ ),
1265
+ ),
1266
+ ),
1267
+ });
1268
+ }),
1269
+ );
1270
+ }