@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/Alarm-CbhflIzz.mjs +1931 -0
  3. package/dist/Alarm-CbhflIzz.mjs.map +1 -0
  4. package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
  5. package/dist/Alarm.d.mts +3 -0
  6. package/dist/Alarm.mjs +3 -0
  7. package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
  8. package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
  9. package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
  10. package/dist/BrowserCredentials.d.mts +2 -0
  11. package/dist/BrowserCredentials.mjs +1 -0
  12. package/dist/BrowserRestCapture.d.mts +14 -0
  13. package/dist/BrowserRestCapture.mjs +195 -0
  14. package/dist/BrowserRestCapture.mjs.map +1 -0
  15. package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
  16. package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
  17. package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
  18. package/dist/BrowserSession.d.mts +3 -0
  19. package/dist/BrowserSession.mjs +4 -0
  20. package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
  21. package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
  22. package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
  23. package/dist/BrowserUse.d.mts +2 -0
  24. package/dist/BrowserUse.mjs +1 -0
  25. package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
  26. package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
  27. package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
  28. package/dist/CloudflareAiGateway.d.mts +2 -0
  29. package/dist/CloudflareAiGateway.mjs +1 -0
  30. package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
  31. package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
  32. package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
  33. package/dist/CloudflareBindings.d.mts +2 -0
  34. package/dist/CloudflareBindings.mjs +1 -0
  35. package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
  36. package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
  37. package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
  38. package/dist/CloudflareBrowser.d.mts +3 -0
  39. package/dist/CloudflareBrowser.mjs +1 -0
  40. package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
  41. package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
  42. package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
  43. package/dist/CloudflareCodeMode.d.mts +2 -0
  44. package/dist/CloudflareCodeMode.mjs +1 -0
  45. package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
  46. package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
  47. package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
  48. package/dist/CloudflareConfig.d.mts +2 -0
  49. package/dist/CloudflareConfig.mjs +1 -0
  50. package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
  51. package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
  52. package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
  53. package/dist/CloudflareMemory.d.mts +2 -0
  54. package/dist/CloudflareMemory.mjs +1 -0
  55. package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
  56. package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
  57. package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
  58. package/dist/CloudflareScheduling.d.mts +2 -0
  59. package/dist/CloudflareScheduling.mjs +1 -0
  60. package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
  61. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
  62. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
  63. package/dist/CloudflareSubscriptions.d.mts +2 -0
  64. package/dist/CloudflareSubscriptions.mjs +1 -0
  65. package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
  66. package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
  67. package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
  68. package/dist/CloudflareThreadClient.d.mts +3 -0
  69. package/dist/CloudflareThreadClient.mjs +3 -0
  70. package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
  71. package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
  72. package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
  73. package/dist/InteractiveBrowser.d.mts +2 -0
  74. package/dist/InteractiveBrowser.mjs +1 -0
  75. package/dist/LiveText-CfpcZaGb.d.mts +91 -0
  76. package/dist/LiveText-DaF0tN_p.mjs +148 -0
  77. package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
  78. package/dist/LiveText.d.mts +2 -0
  79. package/dist/LiveText.mjs +1 -0
  80. package/dist/R2ToolResultStorage.d.mts +27 -0
  81. package/dist/R2ToolResultStorage.mjs +84 -0
  82. package/dist/R2ToolResultStorage.mjs.map +1 -0
  83. package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
  84. package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
  85. package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
  86. package/dist/ThreadObject.d.mts +2 -0
  87. package/dist/ThreadObject.mjs +1 -0
  88. package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
  89. package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
  90. package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
  91. package/dist/WakeScheduler.d.mts +2 -0
  92. package/dist/WakeScheduler.mjs +1 -0
  93. package/dist/boundary-YrOnE2zO.mjs +41 -0
  94. package/dist/boundary-YrOnE2zO.mjs.map +1 -0
  95. package/dist/browser-failure-CWBBnf1j.mjs +70 -0
  96. package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
  97. package/dist/index.d.mts +17 -0
  98. package/dist/index.mjs +17 -0
  99. package/dist/prepared-admission-DngoYN74.mjs +57 -0
  100. package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
  101. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  102. package/package.json +134 -3
  103. package/src/Alarm.ts +3402 -0
  104. package/src/BrowserCredentials.ts +181 -0
  105. package/src/BrowserRestCapture.ts +383 -0
  106. package/src/BrowserSession.ts +993 -0
  107. package/src/BrowserUse.ts +438 -0
  108. package/src/CloudflareAiGateway.ts +176 -0
  109. package/src/CloudflareBindings.ts +225 -0
  110. package/src/CloudflareBrowser.ts +9 -0
  111. package/src/CloudflareCodeMode.ts +896 -0
  112. package/src/CloudflareConfig.ts +142 -0
  113. package/src/CloudflareMemory.ts +418 -0
  114. package/src/CloudflareScheduling.ts +736 -0
  115. package/src/CloudflareSubscriptions.ts +1032 -0
  116. package/src/CloudflareThreadClient.ts +980 -0
  117. package/src/InteractiveBrowser.ts +3300 -0
  118. package/src/LiveText.ts +145 -0
  119. package/src/R2ToolResultStorage.ts +131 -0
  120. package/src/ThreadObject.ts +1348 -0
  121. package/src/WakeScheduler.ts +102 -0
  122. package/src/index.ts +16 -0
  123. package/src/internal/boundary.ts +53 -0
  124. package/src/internal/browser-binding.ts +483 -0
  125. package/src/internal/browser-credentials.ts +481 -0
  126. package/src/internal/browser-failure.ts +145 -0
  127. package/src/internal/browser-file-selection.ts +146 -0
  128. package/src/internal/browser-quick-action.ts +666 -0
  129. package/src/internal/browser-readonly-live-view.ts +121 -0
  130. package/src/internal/browser-session-lifecycle.ts +200 -0
  131. package/src/internal/crypto.ts +44 -0
  132. package/src/internal/due-queue.ts +452 -0
  133. package/src/internal/host-protocol-error.ts +23 -0
  134. package/src/internal/layers.ts +1181 -0
  135. package/src/internal/live-text-observation.ts +8 -0
  136. package/src/internal/live-text-protocol.ts +59 -0
  137. package/src/internal/live-text.ts +339 -0
  138. package/src/internal/message-delivery.ts +149 -0
  139. package/src/internal/page-function.ts +12 -0
  140. package/src/internal/prepared-admission.ts +83 -0
  141. package/src/internal/progress-wait.ts +121 -0
  142. package/src/internal/transport.ts +53 -0
  143. package/README.md +0 -3
package/src/Alarm.ts ADDED
@@ -0,0 +1,3402 @@
1
+ import { CurrentNativeSource } from '@systemfsoftware/agent-storage-cloudflare/port-routing'
2
+ import { type DurableBindingFailure } from '@systemfsoftware/agent/agent-registration'
3
+ import {
4
+ DurableAgentRuntime,
5
+ DurableRuntimeConfig,
6
+ type DurableWorkerFailure,
7
+ isolateRecovery,
8
+ RecoveryBlocked,
9
+ RecoveryFailure,
10
+ type RecoveryReport,
11
+ RecoverySweepResult,
12
+ } from '@systemfsoftware/agent/durable-agent-runtime'
13
+ import { SubmissionId, ThreadId } from '@systemfsoftware/agent/identifiers'
14
+ import { AbortIntentRequest, SubmissionLedger, type SubmissionWorkItem } from '@systemfsoftware/agent/submission-ledger'
15
+ import {
16
+ type ThreadProjectionError,
17
+ ThreadProjectionMaintenance,
18
+ } from '@systemfsoftware/agent/thread-projection-maintenance'
19
+ import { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'
20
+ import { DurableObjectAlarm, DurableObjectState, DurableObjectStorage } from 'effect-cf'
21
+ import * as Cause from 'effect/Cause'
22
+ import * as Clock from 'effect/Clock'
23
+ import * as Context from 'effect/Context'
24
+ import * as SecureRandom from 'effect/crypto/SecureRandom'
25
+ import * as DateTime from 'effect/DateTime'
26
+ import * as Deferred from 'effect/Deferred'
27
+ import * as Effect from 'effect/Effect'
28
+ import * as ErrorReporter from 'effect/ErrorReporter'
29
+ import * as Exit from 'effect/Exit'
30
+ import * as Fiber from 'effect/Fiber'
31
+ import * as Layer from 'effect/Layer'
32
+ import * as Option from 'effect/Option'
33
+ import * as Random from 'effect/Random'
34
+ import * as Ref from 'effect/Ref'
35
+ import * as Result from 'effect/Result'
36
+ import * as Scheduler from 'effect/Scheduler'
37
+ import * as Schema from 'effect/Schema'
38
+ import * as Scope from 'effect/Scope'
39
+ import * as Semaphore from 'effect/Semaphore'
40
+ import * as SqlClient from 'effect/sql/SqlClient'
41
+ import * as SqlError from 'effect/sql/SqlError'
42
+ import * as Stream from 'effect/Stream'
43
+ import * as Struct from 'effect/Struct'
44
+
45
+ import { DurableAlarmError, DurableObjectContext, ThreadObjectPlacement } from './CloudflareBindings'
46
+ import { AuxiliaryDispatchMillis, CloudflareDurableRuntimeConfig } from './CloudflareConfig'
47
+ import { safeCauseMessage } from './internal/boundary'
48
+ import * as DueQueue from './internal/due-queue'
49
+
50
+ /**
51
+ * The maintenance queue owns lease expiry, settlement, retries and dirty generations.
52
+ * Its manual effect-cf alarm shares the native slot with other registered alarms.
53
+ *
54
+ * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable
55
+ * maintenance generation and a committed alarm. Stable externally-driven waits may be
56
+ * nonterminal without retaining an alarm; their resolving mutation advances the generation and
57
+ * restores the alarm atomically.
58
+ */
59
+
60
+ export { DurableAlarmError } from './CloudflareBindings'
61
+
62
+ /** Content-free operational notice: pending work now retries at the hourly ceiling. */
63
+ class MaintenanceRetryParked extends Schema.TaggedError<MaintenanceRetryParked>()(
64
+ 'MaintenanceRetryParked',
65
+ { lane: Schema.String, retryAfterMillis: Schema.Finite },
66
+ ) {}
67
+
68
+ const alarmFailure = (operation: string) => (cause: unknown): DurableAlarmError =>
69
+ DurableAlarmError.make({
70
+ operation,
71
+ message: safeCauseMessage(cause, 'The Cloudflare alarm API failed without a diagnostic'),
72
+ cause,
73
+ })
74
+
75
+ // SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its
76
+ // connection for each short storage operation, never around a mutation or snapshot body.
77
+ const makeStorageEffect = Effect.gen(function*() {
78
+ const sql = yield* SqlClient.SqlClient
79
+ const { ctx } = yield* DurableObjectContext
80
+ const invalidate = Effect.sync(() => DueQueue.invalidate(ctx.storage))
81
+
82
+ return <A, R>(operation: string, execute: Effect.Effect<A, DurableAlarmError, R>) =>
83
+ Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {
84
+ const body = Effect.uninterruptible(execute)
85
+
86
+ // Explicit source transactions own the view through flush and rollback.
87
+ // Unwrapped host SQL keeps eager writes and discards speculative cache rows.
88
+ if (current._tag === 'Some') {
89
+ if (DueQueue.buffering(ctx.storage)) return body
90
+
91
+ return body.pipe(Effect.ensuring(invalidate))
92
+ }
93
+
94
+ return Effect.scoped(
95
+ Effect.andThen(
96
+ sql.reserve.pipe(Effect.mapError(alarmFailure(operation))),
97
+ body.pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? invalidate : Effect.void))),
98
+ ),
99
+ )
100
+ })
101
+ })
102
+
103
+ const makeStorageOperation = Effect.map(
104
+ makeStorageEffect,
105
+ (run) => <A>(operation: string, execute: () => Promise<A>) =>
106
+ run(operation, Effect.tryPromise({ try: execute, catch: alarmFailure(operation) })),
107
+ )
108
+
109
+ /** One manual alarm for the entire consumer-owned maintenance queue. */
110
+ export class ThreadMaintenanceAlarm extends DurableObjectAlarm.Tag<ThreadMaintenanceAlarm>()(
111
+ '@systemfsoftware/agent/thread-maintenance',
112
+ { '@systemfsoftware/agent/thread-maintenance': { payload: Schema.Null, lifecycle: 'manual' } },
113
+ ) {}
114
+
115
+ const maintenanceAlarmRef = { tag: '@systemfsoftware/agent/thread-maintenance', id: 'queue' } as const
116
+
117
+ const maintenanceAlarmInput = (deadline: number) => ({
118
+ ...maintenanceAlarmRef,
119
+ payload: null,
120
+ runAt: DateTime.makeUnsafe(deadline),
121
+ })
122
+
123
+ /** Named maintenance checkpoint; the library owns the shared native alarm slot. */
124
+ export class DurableAlarmService extends Context.Service<
125
+ DurableAlarmService,
126
+ {
127
+ readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>
128
+ readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>
129
+ readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>
130
+ /** Queue-aware promptness hint; idle queues stay idle and retry floors survive. */
131
+ readonly scheduleNow: Effect.Effect<void, DurableAlarmError>
132
+ /** Coalesce droppable inline hints without delaying committed deadlines or their delivery. */
133
+ readonly withHintsDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
134
+ readonly cancel: Effect.Effect<void, DurableAlarmError>
135
+ }
136
+ >()('@effect-agent/platform-cloudflare/DurableAlarmService') {
137
+ static readonly layer = Layer.effect(DurableAlarmService)(
138
+ Effect.gen(function*() {
139
+ const alarms = yield* ThreadMaintenanceAlarm
140
+ const random = yield* SecureRandom.SecureRandom
141
+ const { ctx } = yield* DurableObjectContext
142
+ const run = yield* makeStorageEffect
143
+ const inlineWork = yield* Ref.make(0)
144
+
145
+ const wrap = <A, E, R>(operation: string, effect: Effect.Effect<A, E, R>) =>
146
+ run(
147
+ operation,
148
+ effect.pipe(
149
+ Effect.provideService(SecureRandom.SecureRandom, random),
150
+ Effect.mapError(alarmFailure(operation)),
151
+ ),
152
+ )
153
+
154
+ return DurableAlarmService.of({
155
+ scheduled: wrap(
156
+ 'read maintenance checkpoint',
157
+ alarms.getAlarmStatus(maintenanceAlarmRef),
158
+ ).pipe(
159
+ Effect.map((at) => at === undefined ? Option.none() : Option.some(DateTime.toEpochMillis(at.runAt))),
160
+ ),
161
+ scheduleAt: (at) => wrap('replace maintenance checkpoint', alarms.scheduleAlarm(maintenanceAlarmInput(at))),
162
+ ensureScheduledBy: (at) =>
163
+ wrap(
164
+ 'advance maintenance checkpoint',
165
+ alarms.scheduleAlarmEarlier(maintenanceAlarmInput(at)),
166
+ ),
167
+ scheduleNow: Ref.get(inlineWork).pipe(
168
+ Effect.flatMap((active) =>
169
+ active > 0
170
+ ? Effect.void
171
+ : wrap(
172
+ 'hint maintenance checkpoint',
173
+ Effect.gen(function*() {
174
+ const now = yield* Clock.currentTimeMillis
175
+ const next = DueQueue.next(DueQueue.make(ctx.storage).read())
176
+
177
+ if (!Number.isFinite(next)) return
178
+ const at = Math.max(now, next)
179
+ const scheduled = yield* alarms.getAlarmStatus(maintenanceAlarmRef)
180
+
181
+ // Fresh progress already carries its prompt checkpoint. Replays still
182
+ // advance the pre-arm when no source transaction recorded new progress.
183
+ if (scheduled !== undefined && DateTime.toEpochMillis(scheduled.runAt) <= at) {
184
+ return
185
+ }
186
+ yield* alarms.scheduleAlarmEarlier(maintenanceAlarmInput(at))
187
+ }),
188
+ )
189
+ ),
190
+ ),
191
+ withHintsDeferred: (body) =>
192
+ Effect.acquireUseRelease(
193
+ Ref.update(inlineWork, (active) => active + 1),
194
+ () => body,
195
+ () => Ref.update(inlineWork, (active) => active - 1),
196
+ ),
197
+ cancel: wrap('cancel maintenance checkpoint', alarms.cancelAlarm(maintenanceAlarmRef)),
198
+ })
199
+ }),
200
+ )
201
+ }
202
+
203
+ type CheckpointIntent = {
204
+ readonly at: (deadline: number) => void
205
+ readonly earlier: (deadline: number) => void
206
+ readonly cancel: () => void
207
+ }
208
+
209
+ type MaintenanceStorage = Pick<DurableObjectTransaction, 'get' | 'put' | 'delete'>
210
+ type MaintenanceCheckpoint = {
211
+ readonly mutations: Parameters<
212
+ Parameters<ThreadMaintenanceAlarm['Service']['transaction']>[0]
213
+ >[0]
214
+ readonly isActive: (fiber: Fiber.Fiber<unknown, unknown>) => boolean
215
+ }
216
+
217
+ const CurrentCheckpoint = Context.Reference<MaintenanceCheckpoint | undefined>(
218
+ '@systemfsoftware/agent/cloudflare/CurrentCheckpoint',
219
+ { defaultValue: () => undefined },
220
+ )
221
+
222
+ /** One source transaction owns queue intent and the library checkpoint through commit. */
223
+ const makeAlarmOperation = Effect.gen(function*() {
224
+ const alarms = yield* ThreadMaintenanceAlarm
225
+ const random = yield* SecureRandom.SecureRandom
226
+ const sql = yield* SqlClient.SqlClient
227
+ const { ctx } = yield* DurableObjectContext
228
+ const queue = DueQueue.make(ctx.storage)
229
+
230
+ const transaction = <A, E, R>(
231
+ body: (owner: Fiber.Fiber<unknown, unknown>) => Effect.Effect<A, E, R>,
232
+ ): Effect.Effect<A, E | SqlError.SqlError, R> =>
233
+ alarms
234
+ .transaction(
235
+ (mutations) =>
236
+ Effect.withFiber((owner) => {
237
+ let active = true
238
+
239
+ return Effect.onExitPrimitive(
240
+ body(owner).pipe(
241
+ Effect.provideService(CurrentCheckpoint, {
242
+ mutations,
243
+ isActive: (fiber) => active && fiber === owner,
244
+ }),
245
+ ),
246
+ () => {
247
+ active = false
248
+
249
+ return undefined
250
+ },
251
+ )
252
+ }),
253
+ { sqlClient: sql },
254
+ )
255
+ .pipe(
256
+ Effect.mapError((cause) =>
257
+ cause instanceof DurableObjectStorage.StorageOperationError
258
+ ? SqlError.SqlError.make({
259
+ reason: SqlError.UnknownError.make({
260
+ operation: 'commit maintenance checkpoint',
261
+ message: 'Source facts and maintenance checkpoint could not commit',
262
+ cause,
263
+ }),
264
+ })
265
+ : cause
266
+ ),
267
+ )
268
+
269
+ const withTransaction = <A, E, R>(body: Effect.Effect<A, E, R>) =>
270
+ Effect.withFiber((fiber) => {
271
+ const ambient = Context.getOption(fiber.context, sql.transactionService)
272
+
273
+ if (ambient._tag === 'Some' && !DueQueue.ownsTransaction(ctx.storage, ambient.value[1])) {
274
+ return Effect.fail(
275
+ SqlError.SqlError.make({
276
+ reason: SqlError.UnknownError.make({
277
+ operation: 'begin maintenance source transaction',
278
+ message: 'Use ThreadMutationGate.withTransaction at the outermost source transaction',
279
+ cause: 'Unwrapped SQL transaction cannot own buffered maintenance intent',
280
+ }),
281
+ }),
282
+ )
283
+ }
284
+ let frame: ReturnType<typeof queue.begin> | undefined
285
+
286
+ return Effect.uninterruptibleMask((restore) =>
287
+ Effect.onExitPrimitive(
288
+ transaction((owner) => {
289
+ const current = Context.getOption(owner.context, sql.transactionService)
290
+
291
+ if (current._tag === 'None') {
292
+ return SqlError.SqlError.make({
293
+ reason: SqlError.UnknownError.make({
294
+ operation: 'begin maintenance source transaction',
295
+ message: 'SQL transaction unavailable',
296
+ cause: 'SQL transaction unavailable',
297
+ }),
298
+ })
299
+ }
300
+ const started = queue.begin(current.value[1])
301
+
302
+ frame = started
303
+
304
+ return Effect.flatMap(restore(body), (value) =>
305
+ Effect.try({
306
+ try: () => {
307
+ queue.flush(started)
308
+
309
+ return value
310
+ },
311
+ catch: (cause) =>
312
+ SqlError.SqlError.make({
313
+ reason: SqlError.UnknownError.make({
314
+ cause,
315
+ operation: 'flush maintenance due queue',
316
+ message: 'Maintenance intent could not commit',
317
+ }),
318
+ }),
319
+ }))
320
+ }),
321
+ (exit) => {
322
+ if (frame !== undefined) queue.finish(frame, Exit.isSuccess(exit))
323
+
324
+ return undefined
325
+ },
326
+ ).pipe(
327
+ // A released permit can resume another transaction. Do not auto-yield
328
+ // between the driver's settlement and removing this transaction's frame.
329
+ Effect.provideService(Scheduler.PreventSchedulerYield, true),
330
+ )
331
+ )
332
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql))
333
+
334
+ const run = <A>(
335
+ operation: string,
336
+ execute: (transaction: MaintenanceStorage, checkpoint: CheckpointIntent) => Promise<A>,
337
+ ) => {
338
+ const commit = Effect.withFiber((fiber) => {
339
+ const tx = fiber.getRef(CurrentCheckpoint)
340
+
341
+ if (tx === undefined) {
342
+ return Effect.die(
343
+ DurableAlarmError.make({
344
+ operation: 'checkpoint',
345
+ message: 'Maintenance checkpoint transaction unavailable',
346
+ }),
347
+ )
348
+ }
349
+
350
+ if (!tx.isActive(fiber)) {
351
+ return Effect.fail(
352
+ DurableAlarmError.make({
353
+ operation: 'enroll maintenance source',
354
+ message: "Source intent requires its active transaction callback's fiber",
355
+ }),
356
+ )
357
+ }
358
+
359
+ let checkpoint: ReturnType<DurableObjectAlarm.AlarmScheduler['scheduleAlarm']> = Effect.void
360
+
361
+ const intent: CheckpointIntent = {
362
+ at: (at) => {
363
+ checkpoint = tx.mutations.scheduleAlarm(maintenanceAlarmInput(at))
364
+ },
365
+ earlier: (at) => {
366
+ checkpoint = tx.mutations.scheduleAlarmEarlier(maintenanceAlarmInput(at))
367
+ },
368
+ cancel: () => {
369
+ checkpoint = tx.mutations.cancelAlarm(maintenanceAlarmRef)
370
+ },
371
+ }
372
+
373
+ // The SQL/alarm callback already owns the native transaction; KV uses the same storage.
374
+ return Effect.tryPromise({
375
+ try: () => execute(ctx.storage, intent),
376
+ catch: alarmFailure(operation),
377
+ }).pipe(
378
+ Effect.tap(() => checkpoint.pipe(Effect.provideService(SecureRandom.SecureRandom, random))),
379
+ )
380
+ })
381
+
382
+ return Effect.withFiber((fiber) => {
383
+ const current = fiber.getRef(CurrentCheckpoint)
384
+
385
+ if (current !== undefined) return commit
386
+ const ambient = Context.getOption(fiber.context, sql.transactionService)
387
+
388
+ // Preserve eager writes and invalidation for an unwrapped host SQL transaction.
389
+ return ambient._tag === 'Some' && !DueQueue.buffering(ctx.storage)
390
+ ? transaction(() => commit).pipe(
391
+ Effect.ensuring(Effect.sync(() => DueQueue.invalidate(ctx.storage))),
392
+ )
393
+ : withTransaction(commit)
394
+ }).pipe(Effect.uninterruptible, Effect.mapError(alarmFailure(operation)))
395
+ }
396
+
397
+ return { run, withTransaction }
398
+ })
399
+
400
+ export class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(
401
+ '@effect-agent/platform-cloudflare/MaintenancePassReport',
402
+ )({
403
+ /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
404
+ phase: Schema.Literals(['caught-up', 'actionable']),
405
+ /** Recovery decisions and Thread faults observed during this event. */
406
+ recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
407
+ /** Head Attempts settled during the event. Joined input may settle with each head. */
408
+ settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
409
+ /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
410
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
411
+ /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */
412
+ alarm: Schema.Literals(['rearmed', 'cleared']),
413
+ }) {}
414
+
415
+ /** Fault boundaries around every maintenance-owned durable mutation. */
416
+ export type ThreadMaintenanceFailpointLocation =
417
+ | 'maintenance:dirty:before'
418
+ | 'maintenance:dirty:after'
419
+ | 'maintenance:mutation:armed'
420
+ | 'maintenance:mutation:finished'
421
+ | 'maintenance:ensure:before'
422
+ | 'maintenance:ensure:after'
423
+ | 'maintenance:begin:before'
424
+ | 'maintenance:begin:after'
425
+ | 'maintenance:select:before'
426
+ | 'maintenance:select:after'
427
+ | 'maintenance:binding-retry:before'
428
+ | 'maintenance:binding-retry:after'
429
+ | 'maintenance:recovery-status:before'
430
+ | 'maintenance:recovery-status:after'
431
+ | 'maintenance:retry:before'
432
+ | 'maintenance:retry:after'
433
+ | 'maintenance:checkpoint:before'
434
+ | 'maintenance:checkpoint:after'
435
+ | 'maintenance:finish:before'
436
+ | 'maintenance:finish:after'
437
+
438
+ export type ThreadMaintenanceFailpointHandler = (
439
+ location: ThreadMaintenanceFailpointLocation,
440
+ ) => Effect.Effect<void>
441
+
442
+ /** Test-only fault authority; production uses the inert layer. */
443
+ export class ThreadMaintenanceFailpoint extends Context.Service<
444
+ ThreadMaintenanceFailpoint,
445
+ {
446
+ readonly hit: ThreadMaintenanceFailpointHandler
447
+ }
448
+ >()('@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint') {
449
+ static readonly layer = Layer.succeed(this)({ hit: () => Effect.void })
450
+ }
451
+
452
+ /**
453
+ * Durable host publication of canonical records and ledger approval/abort/resolution intents.
454
+ * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery
455
+ * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.
456
+ *
457
+ * `invalidate` and `prepareGeneration` must be bounded local operations.
458
+ * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated
459
+ * calls must preserve partial scan progress. It runs with no source mutation in flight.
460
+ * Use this gate only for publication required before dependent native execution. Independent
461
+ * UI relays and outboxes belong to ThreadHostMaintenance.
462
+ * `drain` performs bounded delivery and returns its next deadline (None when caught up),
463
+ * after persisting receipts and retries. A pending deadline
464
+ * defers runtime recovery/Attempts, allowing committed host publications to drain first.
465
+ * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call
466
+ * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need
467
+ * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.
468
+ */
469
+ export interface ThreadPublicationService {
470
+ readonly invalidate: Effect.Effect<void, DurableAlarmError>
471
+ readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>
472
+ readonly drain: Effect.Effect<Option.Option<number>, DurableAlarmError>
473
+ }
474
+
475
+ const emptyPublication: ThreadPublicationService = {
476
+ invalidate: Effect.void,
477
+ prepareGeneration: () => Effect.void,
478
+ drain: Effect.succeedNone,
479
+ }
480
+
481
+ /** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
482
+ export class ThreadPublication extends Context.Service<
483
+ ThreadPublication,
484
+ ThreadPublicationService
485
+ >()('@effect-agent/platform-cloudflare/ThreadPublication') {
486
+ static readonly layer = Layer.succeed(this)(emptyPublication)
487
+ }
488
+
489
+ // Only the actual empty default can waive required publication. Missing or replaced
490
+ // services retain the barrier, including hosts that rebuild maintenance Layers.
491
+ const requiresPublication = Effect.map(
492
+ Effect.serviceOption(ThreadPublication),
493
+ (service) => Option.isNone(service) || service.value !== emptyPublication,
494
+ )
495
+
496
+ /**
497
+ * Host-assembled native message recovery. Preparation is a bounded local selection; the
498
+ * driver bounds each actual Claim and persists its timeout/retry before `run` returns.
499
+ * The alarm must not add a timer starting at selection: Claim setup and retry commits belong
500
+ * to the driver. The prepared allowance decides only whether a wave fits this event.
501
+ */
502
+ export const ThreadMessageDelivery = Context.Reference<{
503
+ readonly prepare: Effect.Effect<
504
+ {
505
+ readonly timeoutMillis: number
506
+ readonly run: Effect.Effect<Option.Option<number>, DurableAlarmError>
507
+ },
508
+ DurableAlarmError
509
+ >
510
+ }>('@effect-agent/platform-cloudflare/ThreadMessageDelivery', {
511
+ defaultValue: () => ({
512
+ prepare: Effect.succeed({ timeoutMillis: 1, run: Effect.succeedNone }),
513
+ }),
514
+ })
515
+
516
+ /**
517
+ * One explicitly scheduled application obligation. IDs are stable and unique within the
518
+ * physical Object; the `@systemfsoftware/agent:` prefix is reserved. There is no initial host wave.
519
+ * Producers enroll only affected IDs through ThreadMutationGate.withMutation({ lanes })
520
+ * or schedule(id, dueAt). A lane returns its next epoch-millisecond deadline (None = idle)
521
+ * with its finite wave, after persisting claims, receipts and retries. No deadline callback
522
+ * or polling is used. A racing producer keeps its newer revision due.
523
+ *
524
+ * The 1..300000ms allowance includes selection, dispatch, commits and scoped cleanup.
525
+ * Failed waves retain independent backoff and are not retried in the same event. Delivery
526
+ * remains at least once: persist exact envelopes and deduplicate by domain receipt identity.
527
+ * Hooks never write the alarm slot. Required execution gates belong to ThreadPublication.
528
+ */
529
+ export interface ThreadHostMaintenanceLane {
530
+ readonly id: string
531
+ /** Omission runs concurrently with native work. After-native lanes get one due wave
532
+ * after all admitted native Attempts and their scoped cleanup, even on native failure.
533
+ * They share the event deadline and remain inside the maintenance pass permit.
534
+ * Newly enrolled concurrent work yields this phase after scoped cleanup; unfinished
535
+ * waves retain their due revision and domain receipts for the next alarm.
536
+ */
537
+ readonly phase?: 'concurrent' | 'after-native'
538
+ readonly dispatchTimeoutMillis: number
539
+ readonly run: Effect.Effect<Option.Option<number>, DurableAlarmError, Scope.Scope>
540
+ }
541
+
542
+ /** Independent lanes share the existing alarm; compose hosts by concatenating their lanes. */
543
+ export const ThreadHostMaintenance = Context.Reference<{
544
+ readonly lanes: ReadonlyArray<ThreadHostMaintenanceLane>
545
+ }>('@effect-agent/platform-cloudflare/ThreadHostMaintenance', {
546
+ defaultValue: () => ({ lanes: [] }),
547
+ })
548
+
549
+ /** @internal Framework handlers are separate from host registrations and their namespace. */
550
+ export const ThreadNativeMaintenance = Context.Reference<{
551
+ readonly lanes: ReadonlyArray<ThreadHostMaintenanceLane>
552
+ /** Exact runtime built over a single-Thread placement; never apply to a replacement. */
553
+ readonly singleThreadRuntime?: DurableAgentRuntime['Service']
554
+ }>('@effect-agent/platform-cloudflare/ThreadNativeMaintenance', {
555
+ defaultValue: () => ({ lanes: [] }),
556
+ })
557
+
558
+ /** @internal Required host publication only; native lifecycle facts use a maintenance lane. */
559
+ export const publishCommitted = Effect.gen(function*() {
560
+ const publication = yield* ThreadPublication
561
+
562
+ yield* publication.invalidate
563
+ yield* publication.drain
564
+ }).pipe(
565
+ Effect.catchCause((cause) =>
566
+ Cause.hasInterrupts(cause)
567
+ ? Effect.interrupt
568
+ : Effect.logError('Thread publication deferred after source commit', cause)
569
+ ),
570
+ )
571
+
572
+ const MaintenanceGeneration = Schema.BigIntFromString.check(
573
+ Schema.isGreaterThanOrEqualToBigInt(0n),
574
+ )
575
+
576
+ /** A committed recovery transition for one affected Submission; never a Settlement. */
577
+ export class ThreadRecoveryFaultEvent extends Schema.Class<ThreadRecoveryFaultEvent>(
578
+ '@effect-agent/platform-cloudflare/ThreadRecoveryFaultEvent',
579
+ )({
580
+ schemaVersion: Schema.Literal(1),
581
+ /** Monotonic within the physical Object; retained unchanged on delivery retries. */
582
+ sequence: MaintenanceGeneration,
583
+ transition: Schema.Literals(['created', 'changed', 'cleared']),
584
+ threadId: ThreadId,
585
+ submissionId: SubmissionId,
586
+ occurredAt: Schema.Finite,
587
+ firstFailedAt: Schema.Finite,
588
+ /** The current failure, or the last failure for a cleared event. */
589
+ failure: RecoveryFailure,
590
+ }) {}
591
+
592
+ const recoveryEventKey = (sequence: bigint) => `effect-agent:thread-recovery-event:v1:${sequence}`
593
+ const encodeRecoveryEvent = Schema.encodeSync(ThreadRecoveryFaultEvent)
594
+ const decodeRecoveryEvent = Schema.decodeUnknownSync(ThreadRecoveryFaultEvent)
595
+
596
+ /**
597
+ * Ordered, at-least-once delivery through the existing host maintenance lane. Return only
598
+ * after durably applying the event or retaining it in a host outbox. Deduplicate by physical
599
+ * Object and sequence; callbacks may repeat after interruption. This is a trusted host hook,
600
+ * not pre-authorized UI data: the host owns recipient authorization and safe presentation.
601
+ * Capture services in the Layer. Do not call producers or write the raw alarm slot.
602
+ * Without this service, maintenance acknowledges and discards transitions. Install the
603
+ * handler before the first maintenance pass if the application needs that event stream.
604
+ */
605
+ export class ThreadRecoveryEvents extends Context.Service<
606
+ ThreadRecoveryEvents,
607
+ { readonly publish: (event: ThreadRecoveryFaultEvent) => Effect.Effect<void, DurableAlarmError> }
608
+ >()('@effect-agent/platform-cloudflare/ThreadRecoveryEvents') {}
609
+
610
+ class BindingWait extends Schema.Class<BindingWait>('BindingWait')({
611
+ threadId: ThreadId,
612
+ submissionId: SubmissionId,
613
+ reportedAt: Schema.Finite,
614
+ }) {}
615
+
616
+ /**
617
+ * A durable observation of blocked recovery, independent of the execution journal. This is
618
+ * neither a Settlement nor proof that external effects did not happen. A successful recovery
619
+ * sweep clears it; repair must preserve canonical history and the original admission identity.
620
+ */
621
+ class ThreadRecoveryFault extends Schema.Class<ThreadRecoveryFault>(
622
+ '@effect-agent/platform-cloudflare/ThreadRecoveryFault',
623
+ )({
624
+ schemaVersion: Schema.Literal(1),
625
+ threadId: ThreadId,
626
+ firstFailedAt: Schema.Finite,
627
+ lastFailedAt: Schema.Finite,
628
+ /** Earliest automatic recovery retry; new admissions do not erase this deadline. */
629
+ retryAt: Schema.Finite,
630
+ /** Saturates at 2^31 - 1; one observation per Thread per recovery sweep. */
631
+ attempts: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2_147_483_647)),
632
+ failure: RecoveryFailure,
633
+ /** Individually retained recipients survive settlement until their clear commits. */
634
+ recipientCount: Schema.optionalKey(Schema.Natural),
635
+ }) {}
636
+
637
+ const recoveryFaultKey = (threadId: ThreadId) => `effect-agent:thread-recovery-fault:v1:${threadId}`
638
+
639
+ const decodeRecoveryFaultValue = Schema.decodeUnknownSync(ThreadRecoveryFault)
640
+
641
+ const decodeRecoveryFault = (threadId: ThreadId, encoded: unknown) => {
642
+ const fault = decodeRecoveryFaultValue(encoded)
643
+
644
+ // oxlint-disable-next-line effect/no-untyped-throw, effect/no-native-error -- Native Durable Object transaction decoder must abort before corrupt persisted data can be committed.
645
+ if (fault.threadId !== threadId) throw new Error('Recovery status does not match its Thread key')
646
+
647
+ return fault
648
+ }
649
+
650
+ const encodeRecoveryFault = Schema.encodeSync(ThreadRecoveryFault)
651
+ const sameRecoveryFailure = Schema.toEquivalence(RecoveryFailure)
652
+ const decodeRecoveryRecipient = Schema.decodeUnknownSync(SubmissionId)
653
+ const encodeRecoveryRecipient = Schema.encodeSync(SubmissionId)
654
+
655
+ const recoveryRecipientKey = (threadId: ThreadId, index: number) =>
656
+ `effect-agent:recovery-recipient:v1:${threadId.length}:${threadId}:${index}`
657
+
658
+ const recoveryRecipientKeys = (fault: ThreadRecoveryFault, start: number) =>
659
+ Array.from(
660
+ { length: Math.min(128, (fault.recipientCount ?? 0) - start) },
661
+ (_, offset) => recoveryRecipientKey(fault.threadId, start + offset),
662
+ )
663
+
664
+ const readRecoveryRecipients = async (
665
+ storage: Pick<DurableObjectTransaction, 'get'>,
666
+ fault: ThreadRecoveryFault,
667
+ ): Promise<Array<SubmissionId>> => {
668
+ const ids: Array<SubmissionId> = []
669
+
670
+ for (let start = 0; start < (fault.recipientCount ?? 0); start += 128) {
671
+ const keys = recoveryRecipientKeys(fault, start)
672
+ const values = await storage.get(keys)
673
+
674
+ for (const key of keys) ids.push(decodeRecoveryRecipient(values.get(key)))
675
+ }
676
+
677
+ return ids
678
+ }
679
+
680
+ const appendRecoveryRecipients = async (
681
+ transaction: MaintenanceStorage,
682
+ threadId: ThreadId,
683
+ count: number,
684
+ added: ReadonlyArray<SubmissionId>,
685
+ ) => {
686
+ for (let start = 0; start < added.length; start += 128) {
687
+ await transaction.put(
688
+ Object.fromEntries(
689
+ added
690
+ .slice(start, start + 128)
691
+ .map((id, offset) => [
692
+ recoveryRecipientKey(threadId, count + start + offset),
693
+ encodeRecoveryRecipient(id),
694
+ ]),
695
+ ),
696
+ )
697
+ }
698
+ }
699
+
700
+ const recoveryEvent = (
701
+ fault: ThreadRecoveryFault,
702
+ submissionId: SubmissionId,
703
+ transition: ThreadRecoveryFaultEvent['transition'],
704
+ occurredAt: number,
705
+ ): Omit<ThreadRecoveryFaultEvent, 'sequence'> => ({
706
+ schemaVersion: 1,
707
+ transition,
708
+ threadId: fault.threadId,
709
+ submissionId,
710
+ occurredAt,
711
+ firstFailedAt: fault.firstFailedAt,
712
+ failure: fault.failure,
713
+ })
714
+
715
+ interface NativePassResult {
716
+ readonly phase: 'caught-up' | 'actionable'
717
+ readonly nonterminal: number
718
+ readonly nextAttemptAt: number | undefined
719
+ readonly dispatched?: boolean
720
+ }
721
+
722
+ /** Independent Threads share bounded native slots; one active head per Thread. */
723
+ interface NativeDispatch {
724
+ readonly scope: Scope.Scope
725
+ readonly active: Map<ThreadId, Fiber.Fiber<number, MaintenancePassFailure>>
726
+ readonly deferred: Set<ThreadId>
727
+ dispatched: number
728
+ settled: number
729
+ progressed: boolean
730
+ needsCheckpoint: boolean
731
+ generation?: bigint
732
+ sourceRevision?: number
733
+ scanGeneration?: bigint
734
+ scanRevision?: number
735
+ }
736
+
737
+ /** Observe already-owned waves without creating one waiter fiber for each wave. */
738
+ const awaitAnyCompletion = Effect.fnUntraced(function*(
739
+ fibers: ReadonlyArray<Fiber.Fiber<unknown, MaintenancePassFailure>>,
740
+ revision: number,
741
+ ) {
742
+ const mutations = yield* ThreadMutationGate
743
+
744
+ return yield* Effect.acquireUseRelease(
745
+ Effect.sync<Array<() => void>>(() => []),
746
+ (observers) =>
747
+ Effect.callback<'completed' | 'scan'>((resume) => {
748
+ observers.push(mutations.observeChange(revision, () => resume(Effect.succeed('scan'))))
749
+ for (const fiber of fibers) {
750
+ observers.push(fiber.addObserver(() => resume(Effect.succeed('completed'))))
751
+ }
752
+ }),
753
+ (observers) => Effect.sync(() => observers.forEach((remove) => remove())),
754
+ )
755
+ })
756
+
757
+ /** Post-native delivery shares a finite connection budget across independent host lanes. */
758
+ const afterNativeDispatchConcurrency = 2
759
+
760
+ /** Event-local observations only; durable ingress keeps racing mutations dirty. */
761
+ interface NativeRecovery {
762
+ readonly queue: Deferred.Deferred<ReadonlyArray<ThreadId>>
763
+ readonly pending: Set<ThreadId>
764
+ readonly loaded: Set<ThreadId>
765
+ readonly reports: Map<SubmissionId, RecoveryReport>
766
+ readonly faults: Map<ThreadId, ThreadRecoveryFault>
767
+ readonly recipients: Map<ThreadId, ReadonlySet<SubmissionId>>
768
+ observation?: {
769
+ readonly generation: bigint
770
+ readonly activeAtStart: number
771
+ }
772
+ started: boolean
773
+ needsCheckpoint: boolean
774
+ recovered: number
775
+ repaired: boolean
776
+ discoveryPending: boolean
777
+ retryAtMillis?: number
778
+ }
779
+
780
+ const NativeWorkCursor = Schema.Struct({
781
+ threadId: ThreadId,
782
+ cursor: Schema.NonEmptyString.check(Schema.isMaxLength(8192)),
783
+ })
784
+
785
+ const workCursorKey = (threadId: ThreadId) => `effect-agent:work-recovery-cursor:v1:${threadId}`
786
+
787
+ interface MaintenanceObservation {
788
+ readonly queue: Map<string, DueQueue.DueLane>
789
+ readonly charged: Map<string, number>
790
+ /** Initially available or serviced revisions; active producers are only failure observations. */
791
+ readonly available: Map<string, number>
792
+ generation?: bigint
793
+ nativeOnly: boolean
794
+ }
795
+
796
+ class MaintenanceRetry extends Schema.Class<MaintenanceRetry>('MaintenanceRetry')({
797
+ generation: MaintenanceGeneration,
798
+ notBefore: Schema.Finite,
799
+ nativeOnly: Schema.Boolean,
800
+ stalls: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(30)),
801
+ }) {}
802
+
803
+ /** Versioned, platform-private maintenance state stored through Durable Object KV. */
804
+ class ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(
805
+ '@effect-agent/platform-cloudflare/ThreadMaintenanceState',
806
+ )({
807
+ schemaVersion: Schema.Literal(1),
808
+ dirty: MaintenanceGeneration,
809
+ processed: MaintenanceGeneration,
810
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
811
+ /** One physical-owner cursor; old single-lane records need no conversion. */
812
+ lastServedThreadId: Schema.optionalKey(ThreadId),
813
+ /** Rotate old recovery independently of dispatch, including after eviction or timeout. */
814
+ lastRecoveredThreadId: Schema.optionalKey(ThreadId),
815
+ /** Rotate bounded post-native admission across full events and Object eviction. */
816
+ lastAfterNativeLaneId: Schema.optionalKey(DueQueue.LaneId),
817
+ bindingRegistryKey: Schema.optionalKey(Schema.String),
818
+ bindingWaits: Schema.optionalKey(Schema.Array(BindingWait)),
819
+ recoveryEventSequence: Schema.optionalKey(MaintenanceGeneration),
820
+ recoveryEventAcknowledged: Schema.optionalKey(MaintenanceGeneration),
821
+ /** Absent on older records. A newer mutation makes this retry obsolete. */
822
+ retry: Schema.optionalKey(MaintenanceRetry),
823
+ }) {}
824
+
825
+ const MAINTENANCE_STATE_KEY = 'effect-agent:thread-maintenance:v1'
826
+ const decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState)
827
+ const encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState)
828
+
829
+ const hasRecoveryEvents = (state: ThreadMaintenanceState) =>
830
+ (state.recoveryEventSequence ?? 0n) > (state.recoveryEventAcknowledged ?? 0n)
831
+
832
+ const initialMaintenanceState = (): ThreadMaintenanceState =>
833
+ ThreadMaintenanceState.make({
834
+ schemaVersion: 1,
835
+ // Bootstrap Objects created by the pre-generation release without scanning the ledger in
836
+ // the constructor. One useful pass classifies and acknowledges any existing obligation.
837
+ dirty: 1n,
838
+ processed: 0n,
839
+ nonterminal: 0,
840
+ })
841
+
842
+ const readMaintenanceState = async (
843
+ transaction: Pick<DurableObjectTransaction, 'get'>,
844
+ ): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {
845
+ const encoded = await transaction.get(MAINTENANCE_STATE_KEY)
846
+
847
+ return encoded === undefined
848
+ ? { state: initialMaintenanceState(), initialized: false }
849
+ : { state: decodeMaintenanceState(encoded), initialized: true }
850
+ }
851
+
852
+ const stableExternalWait = (
853
+ snapshot: SubmissionWorkItem,
854
+ reports: ReadonlyMap<string, RecoveryReport>,
855
+ ): boolean => {
856
+ const report = reports.get(snapshot.submissionId)
857
+ const decision = report?.decision._tag
858
+
859
+ // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.
860
+ if (decision === 'SettleAborted') return false
861
+ switch (snapshot.state) {
862
+ case 'suspended':
863
+ case 'joined':
864
+ return true
865
+ case 'unknown':
866
+ return report?.disposition === 'unknown'
867
+ case 'admitted':
868
+ return reports.get(snapshot.submissionId)?.decision._tag === 'AwaitParentEstablishment'
869
+ case 'input-applied':
870
+ case 'joining':
871
+ case 'ready':
872
+ case 'settled':
873
+ return false
874
+ }
875
+ }
876
+
877
+ /**
878
+ * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
879
+ * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
880
+ * Layers must reuse that instance; a second gate cannot observe the native producers' activity.
881
+ */
882
+ const CurrentMutationLanes = Context.Reference<ReadonlyArray<string>>(
883
+ '@effect-agent/platform-cloudflare/CurrentMutationLanes',
884
+ {
885
+ defaultValue: () => [],
886
+ },
887
+ )
888
+
889
+ // Source changes made by this pass are certified after its Attempts join. External
890
+ // producers still advance the dirty generation and fence that certification.
891
+ export class ThreadMutationGate extends Context.Service<
892
+ ThreadMutationGate,
893
+ {
894
+ /** Commit source facts and their scheduling intent together. Mutate from this callback's
895
+ * fiber, or use an explicit child transaction. The flush runs before native commit;
896
+ * failed or interrupted transactions discard their queue view. */
897
+ readonly withTransaction: <A, E, R>(
898
+ body: Effect.Effect<A, E, R>,
899
+ ) => Effect.Effect<A, E | SqlError.SqlError, R>
900
+ readonly withMutation: <A, E, R>(
901
+ body: Effect.Effect<A, E, R>,
902
+ /**
903
+ * Call outside SQL transactions so prearming commits before the body runs.
904
+ * Native admission, approval, abort and unknown resolution keep the default true.
905
+ * Host producers use false and name only the lanes for which they create work.
906
+ * Receipt-only bookkeeping with no new obligation names no lanes. Enrollment preserves
907
+ * a pending retry budget; idle completion or actual source progress replenishes it.
908
+ * Actual new work must record that progress in its source transaction, so a commit
909
+ * after parking cannot be stranded by eviction before this body returns.
910
+ */
911
+ options?: {
912
+ readonly invalidatesRecovery?: boolean
913
+ readonly lanes?: ReadonlyArray<string>
914
+ },
915
+ ) => Effect.Effect<A, E | DurableAlarmError, R>
916
+ /** Enroll a known lane without accelerating its retry floor. A strictly increasing
917
+ * source cursor replenishes its budget; equal/older notices are replayed hints.
918
+ * Cursors identify committed source facts, never clocks, attempts or retry counters.
919
+ * Local sources call inside their source transaction. Remote sources retain the cursor
920
+ * notice with their work and retry delivery here; this call atomically accepts that
921
+ * notice and its alarm. Prearming alone cannot fence a later remote commit. */
922
+ readonly schedule: (
923
+ id: string,
924
+ dueAt: number,
925
+ progressCursor?: bigint,
926
+ ) => Effect.Effect<void, DurableAlarmError>
927
+ /** Record an actual new fact inside its local source SQL transaction. The source
928
+ * transaction owns duplicate detection. Claims, lease renewals and retries are not progress.
929
+ * Also enrolls the lanes selected by this producer's enclosing withMutation boundary. */
930
+ readonly recordProgress: (
931
+ lanes: ReadonlyArray<string>,
932
+ ) => Effect.Effect<void, DurableAlarmError>
933
+ /** In-incarnation notification; the durable due queue is the recovery authority. */
934
+ readonly activeLanes: Effect.Effect<ReadonlySet<string>>
935
+ readonly revision: Effect.Effect<number>
936
+ readonly awaitChange: (revision: number) => Effect.Effect<void>
937
+ /** Register an incarnation-local observer; its caller must detach it on completion. */
938
+ readonly observeChange: (revision: number, notify: () => void) => () => void
939
+ readonly withSnapshot: <A, E, R>(
940
+ body: (active: number) => Effect.Effect<A, E, R>,
941
+ ) => Effect.Effect<A, E, R>
942
+ }
943
+ >()('@effect-agent/platform-cloudflare/internal/ThreadMutationGate') {
944
+ static readonly layer = Layer.effect(this)(
945
+ Effect.gen(function*() {
946
+ const { ctx } = yield* DurableObjectContext
947
+ const sql = yield* SqlClient.SqlClient
948
+ const dueQueue = DueQueue.make(ctx.storage)
949
+ const placement = yield* Effect.serviceOption(ThreadObjectPlacement)
950
+ const singleThread = Option.isSome(placement) && placement.value.threadId !== undefined
951
+
952
+ const config = yield* CloudflareDurableRuntimeConfig
953
+ const failpoint = yield* ThreadMaintenanceFailpoint
954
+ // A fresh incarnation has no live mutations; durable generations survive eviction.
955
+ const activeMutations = yield* Ref.make(0)
956
+ const activeLanes = new Map<string, number>()
957
+ const generationGate = yield* Semaphore.make(1)
958
+ let revision = 0
959
+ const listeners = new Set<() => void>()
960
+
961
+ const observeChange = (observed: number, listener: () => void): () => void => {
962
+ if (observed !== revision) {
963
+ listener()
964
+
965
+ return () => {}
966
+ }
967
+ listeners.add(listener)
968
+
969
+ return () => {
970
+ listeners.delete(listener)
971
+ }
972
+ }
973
+
974
+ const notify = Effect.sync(() => {
975
+ revision++
976
+ const pending = [...listeners]
977
+
978
+ listeners.clear()
979
+ for (const listener of pending) listener()
980
+ })
981
+
982
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2))
983
+ const recoveryDelay = config.recoveryWindowMillis || minimumAlarmDelay
984
+
985
+ const runTransaction = yield* makeStorageOperation
986
+ const { run: runAlarmTransaction, withTransaction } = yield* makeAlarmOperation
987
+
988
+ const validateSourceBoundary = Effect.flatMap(
989
+ Effect.serviceOption(sql.transactionService),
990
+ (current) =>
991
+ current._tag === 'Some' &&
992
+ DueQueue.buffering(ctx.storage) &&
993
+ !DueQueue.ownsTransaction(ctx.storage, current.value[1])
994
+ ? Effect.fail(
995
+ DurableAlarmError.make({
996
+ operation: 'enroll maintenance source',
997
+ message: 'Nested source scheduling requires ThreadMutationGate.withTransaction',
998
+ }),
999
+ )
1000
+ : Effect.void,
1001
+ )
1002
+
1003
+ yield* runTransaction('initialize maintenance due queue', async () => {
1004
+ dueQueue.initialize()
1005
+ dueQueue.register(DueQueue.Native)
1006
+ })
1007
+
1008
+ const schedule = Effect.fnUntraced(function*(
1009
+ id: string,
1010
+ dueAt: number,
1011
+ progressCursor?: bigint,
1012
+ ) {
1013
+ yield* validateSourceBoundary
1014
+ const now = yield* Clock.currentTimeMillis
1015
+ const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration
1016
+
1017
+ const enroll = async (transaction: MaintenanceStorage, checkpoint: CheckpointIntent) => {
1018
+ if (progressCursor === undefined) dueQueue.dirty(id, dueAt)
1019
+ else if (
1020
+ dueQueue.progress(id, dueAt, progressCursor) &&
1021
+ (id === DueQueue.Native || id === DueQueue.Publication)
1022
+ ) {
1023
+ // Required publication is progress for its dependent native execution too.
1024
+ if (id === DueQueue.Publication) dueQueue.dirty(DueQueue.Native, dueAt, true)
1025
+ const { state } = await readMaintenanceState(transaction)
1026
+
1027
+ await transaction.put(
1028
+ MAINTENANCE_STATE_KEY,
1029
+ encodeMaintenanceState(
1030
+ ThreadMaintenanceState.make({
1031
+ ...Struct.omit(state, ['retry']),
1032
+ dirty: state.dirty + 1n,
1033
+ }),
1034
+ ),
1035
+ )
1036
+ }
1037
+ const next = DueQueue.next(dueQueue.read())
1038
+
1039
+ if (Number.isFinite(next)) {
1040
+ checkpoint.earlier(
1041
+ Math.max(
1042
+ next,
1043
+ now + (scheduling.dispatchAfterEvent === true ? 0 : minimumAlarmDelay),
1044
+ ),
1045
+ )
1046
+ }
1047
+ }
1048
+
1049
+ yield* runAlarmTransaction('schedule maintenance lane', enroll)
1050
+ yield* notify
1051
+ })
1052
+
1053
+ const beginMutation = Effect.fnUntraced(function*(
1054
+ invalidatesRecovery: boolean,
1055
+ lanes: ReadonlyArray<string>,
1056
+ ) {
1057
+ yield* failpoint.hit('maintenance:dirty:before')
1058
+ const now = yield* Clock.currentTimeMillis
1059
+ const nativeSource = yield* CurrentNativeSource
1060
+ const publicationRequired = yield* requiresPublication
1061
+
1062
+ if (invalidatesRecovery || lanes.length > 0) {
1063
+ yield* runAlarmTransaction(
1064
+ 'advance maintenance generation',
1065
+ async (transaction, checkpoint) => {
1066
+ const { state, initialized } = await readMaintenanceState(transaction)
1067
+
1068
+ if (invalidatesRecovery) {
1069
+ dueQueue.dirty(DueQueue.Native, now)
1070
+ if (publicationRequired) dueQueue.dirty(DueQueue.Publication, now)
1071
+ }
1072
+ // Enrollment is a crash fallback, not evidence that the body committed.
1073
+ for (const id of lanes) dueQueue.dirty(id, now, false)
1074
+
1075
+ if (!initialized || (invalidatesRecovery && !nativeSource)) {
1076
+ await transaction.put(
1077
+ MAINTENANCE_STATE_KEY,
1078
+ encodeMaintenanceState(
1079
+ ThreadMaintenanceState.make({
1080
+ ...state,
1081
+ dirty: state.dirty + (invalidatesRecovery && !nativeSource ? 1n : 0n),
1082
+ }),
1083
+ ),
1084
+ )
1085
+ }
1086
+ // Commit recovery before the producer. Source progress separately starts work
1087
+ // promptly; a retained earlier wake already covers this recovery window.
1088
+ const deadline = DueQueue.next(dueQueue.read())
1089
+
1090
+ if (Number.isFinite(deadline)) {
1091
+ checkpoint.earlier(Math.max(deadline, now + recoveryDelay))
1092
+ }
1093
+ },
1094
+ )
1095
+ }
1096
+ yield* failpoint.hit('maintenance:dirty:after')
1097
+ yield* Ref.update(activeMutations, (active) => active + 1)
1098
+
1099
+ const enrolled = new Set([
1100
+ ...lanes,
1101
+ ...(invalidatesRecovery
1102
+ ? [DueQueue.Native, ...(publicationRequired ? [DueQueue.Publication] : [])]
1103
+ : []),
1104
+ ])
1105
+
1106
+ for (const id of enrolled) activeLanes.set(id, (activeLanes.get(id) ?? 0) + 1)
1107
+
1108
+ return enrolled
1109
+ })
1110
+
1111
+ const releaseLanes = (enrolled: Set<string>, committed = false) =>
1112
+ Effect.sync(() => {
1113
+ for (const id of enrolled) {
1114
+ if (committed && (id === DueQueue.Native || id === DueQueue.Publication)) continue
1115
+ const remaining = (activeLanes.get(id) ?? 1) - 1
1116
+
1117
+ if (remaining === 0) activeLanes.delete(id)
1118
+ else activeLanes.set(id, remaining)
1119
+ enrolled.delete(id)
1120
+ }
1121
+ })
1122
+
1123
+ const endMutation = (enrolled: Set<string>) =>
1124
+ generationGate.withPermit(
1125
+ releaseLanes(enrolled).pipe(
1126
+ Effect.andThen(Ref.update(activeMutations, (active) => Math.max(0, active - 1))),
1127
+ ),
1128
+ )
1129
+
1130
+ const withMutation = <A, E, R>(
1131
+ body: Effect.Effect<A, E, R>,
1132
+ options?: {
1133
+ readonly invalidatesRecovery?: boolean
1134
+ readonly lanes?: ReadonlyArray<string>
1135
+ },
1136
+ ): Effect.Effect<A, E | DurableAlarmError, R> =>
1137
+ Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) =>
1138
+ // Reject before the generation gate: a prearmer may already be waiting
1139
+ // for this caller's SQL connection while holding that gate.
1140
+ Option.isSome(current)
1141
+ ? Effect.fail(
1142
+ DurableAlarmError.make({
1143
+ operation: 'prearm maintenance mutation',
1144
+ message: 'Run withMutation outside the source SQL transaction so prearming commits first',
1145
+ }),
1146
+ )
1147
+ : Effect.acquireUseRelease(
1148
+ generationGate.withPermit(
1149
+ beginMutation(options?.invalidatesRecovery ?? true, options?.lanes ?? []),
1150
+ ),
1151
+ (enrolled) =>
1152
+ failpoint.hit('maintenance:mutation:armed').pipe(
1153
+ Effect.andThen(
1154
+ Effect.flatMap(CurrentMutationLanes, (current) =>
1155
+ body.pipe(
1156
+ Effect.provideService(CurrentMutationLanes, [
1157
+ ...new Set([...current, ...enrolled]),
1158
+ ]),
1159
+ )),
1160
+ ),
1161
+ // The committed outbox may be claimed by the alarm even while the caller
1162
+ // is suspended after commit. This synchronous decrement does not acquire the
1163
+ // native snapshot gate: a snapshot may conservatively retain its active count.
1164
+ // Native certification keeps its broader guard until the mutation is released.
1165
+ Effect.tap(() => releaseLanes(enrolled, true).pipe(Effect.andThen(notify))),
1166
+ Effect.tap(() => failpoint.hit('maintenance:mutation:finished')),
1167
+ ),
1168
+ (enrolled) => endMutation(enrolled).pipe(Effect.andThen(notify)),
1169
+ ))
1170
+
1171
+ const recordProgress = Effect.fnUntraced(function*(lanes: ReadonlyArray<string>) {
1172
+ yield* validateSourceBoundary
1173
+ if (Option.isNone(yield* Effect.serviceOption(sql.transactionService))) {
1174
+ return yield* DurableAlarmError.make({
1175
+ operation: 'record source progress',
1176
+ message: 'Source progress requires its authoritative SQL transaction',
1177
+ })
1178
+ }
1179
+ const affected = new Set([...lanes, ...(yield* CurrentMutationLanes)])
1180
+
1181
+ if (!(yield* requiresPublication)) affected.delete(DueQueue.Publication)
1182
+
1183
+ if (affected.has(DueQueue.Publication)) affected.add(DueQueue.Native)
1184
+
1185
+ if (affected.size === 0) return
1186
+ const now = yield* Clock.currentTimeMillis
1187
+ const nativeSource = yield* CurrentNativeSource
1188
+ const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration
1189
+
1190
+ yield* runAlarmTransaction(
1191
+ 'record maintenance producer progress',
1192
+ async (transaction, checkpoint) => {
1193
+ for (const id of affected) {
1194
+ // Shared hosts need every revision to discover newly actionable sibling Threads.
1195
+ if (singleThread && nativeSource && id === DueQueue.Native) {
1196
+ dueQueue.progressNative(now)
1197
+ } else dueQueue.dirty(id, now, true)
1198
+ }
1199
+ if (affected.has(DueQueue.Native)) {
1200
+ const { state, initialized } = await readMaintenanceState(transaction)
1201
+
1202
+ // Native progress already belongs to this generation. Persist only
1203
+ // initialization, external progress, or the removal of a retry budget.
1204
+ if (!initialized || !nativeSource || state.retry !== undefined) {
1205
+ await transaction.put(
1206
+ MAINTENANCE_STATE_KEY,
1207
+ encodeMaintenanceState(
1208
+ ThreadMaintenanceState.make({
1209
+ ...Struct.omit(state, ['retry']),
1210
+ dirty: state.dirty + (nativeSource ? 0n : 1n),
1211
+ }),
1212
+ ),
1213
+ )
1214
+ }
1215
+ }
1216
+ // New source work is eligible for the configured post-response dispatcher.
1217
+ // Native progress and alarm-only hosts retain their ordinary recovery delay.
1218
+ checkpoint.earlier(
1219
+ now +
1220
+ (scheduling.dispatchAfterEvent === true && !nativeSource ? 0 : minimumAlarmDelay),
1221
+ )
1222
+ },
1223
+ )
1224
+ // Maintenance already awaits this native fiber's completion. With one Thread,
1225
+ // native-only progress cannot free another dispatch slot or enroll an auxiliary lane.
1226
+ if (!(singleThread && nativeSource && affected.size === 1 && affected.has(DueQueue.Native))) {
1227
+ yield* notify
1228
+ }
1229
+ })
1230
+
1231
+ return ThreadMutationGate.of({
1232
+ withTransaction,
1233
+ withMutation,
1234
+ schedule,
1235
+ recordProgress,
1236
+ activeLanes: Effect.sync(() => new Set(activeLanes.keys())),
1237
+ revision: Effect.sync(() => revision),
1238
+ observeChange,
1239
+ awaitChange: (observed) =>
1240
+ Effect.callback((resume) => {
1241
+ const remove = observeChange(observed, () => resume(Effect.void))
1242
+
1243
+ return Effect.sync(remove)
1244
+ }),
1245
+ withSnapshot: (body) => generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),
1246
+ })
1247
+ }),
1248
+ )
1249
+ }
1250
+
1251
+ export type MaintenancePassFailure =
1252
+ | DurableWorkerFailure
1253
+ | DurableBindingFailure
1254
+ | DurableAlarmError
1255
+ | ThreadProjectionError
1256
+
1257
+ /**
1258
+ * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
1259
+ *
1260
+ * One physical event owns native scheduling, auxiliary delivery and final alarm rearming.
1261
+ *
1262
+ * 1. Prearm before any work. A caught-up native step uses the O(1) generation record without
1263
+ * recovery, ledger scans or canonical-history reads.
1264
+ * 2. Reconcile before each head Attempt, then checkpoint only the observed generation. A racing
1265
+ * producer keeps its generation dirty and immediately eligible. Quiescent native retries
1266
+ * retain their durable backoff.
1267
+ * 3. Admit one Attempt for a single-Thread runtime, or at most two independent Thread
1268
+ * Attempts for a shared host, with one active head per Thread.
1269
+ * Keep native and delivery admission open together while finite waves remain active, so
1270
+ * fresh replies and abort controls can progress during unrelated cleanup. Close atomically
1271
+ * at quiescence, or at the original ten-minute yield deadline, then join admitted waves.
1272
+ * 4. Native message delivery retains its driver-owned Claim deadline. Host/backfill waves are
1273
+ * bounded independently; incoming native work never restarts or cancels their attempts.
1274
+ * Auxiliary failures are reported after the current native opportunity.
1275
+ * 5. Close every event resource before the final gated deadline snapshot and alarm decision.
1276
+ * The whole event retains one fourteen-minute cooperative timeout.
1277
+ */
1278
+ export class ThreadMaintenance extends Context.Service<
1279
+ ThreadMaintenance,
1280
+ {
1281
+ /** One idempotent pass; failures propagate after durably scheduling bounded recovery. */
1282
+ readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>
1283
+ /** Start a committed admission under the same bounded processing and recovery guard. */
1284
+ readonly start: (
1285
+ admission: Pick<SubmissionWorkItem, 'threadId' | 'submissionId'>,
1286
+ ) => Effect.Effect<void>
1287
+ /**
1288
+ * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty
1289
+ * generation has an alarm. It never scans the ledger or canonical history.
1290
+ */
1291
+ readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>
1292
+ /**
1293
+ * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty
1294
+ * generation and arm the alarm in one transaction BEFORE running the caller's mutation.
1295
+ * A pass cannot acknowledge while that mutation remains in flight.
1296
+ */
1297
+ readonly withMutation: <A, E, R>(
1298
+ body: Effect.Effect<A, E, R>,
1299
+ ) => Effect.Effect<A, E | DurableAlarmError, R>
1300
+ }
1301
+ >()('@effect-agent/platform-cloudflare/ThreadMaintenance') {
1302
+ static readonly layer: Layer.Layer<
1303
+ ThreadMaintenance,
1304
+ DurableAlarmError,
1305
+ | ThreadMutationGate
1306
+ | ThreadPublication
1307
+ | ThreadProjectionMaintenance
1308
+ | DurableAgentRuntime
1309
+ | DurableRuntimeConfig
1310
+ | SubmissionLedger
1311
+ | WakeScheduler
1312
+ | DurableAlarmService
1313
+ | ThreadMaintenanceAlarm
1314
+ | ThreadMaintenanceFailpoint
1315
+ | CloudflareDurableRuntimeConfig
1316
+ | DurableObjectContext
1317
+ | SqlClient.SqlClient
1318
+ | SecureRandom.SecureRandom
1319
+ > = Layer.effect(ThreadMaintenance)(
1320
+ Effect.gen(function*() {
1321
+ const runtime = yield* DurableAgentRuntime
1322
+ const recoveryConfig = yield* DurableRuntimeConfig
1323
+ const ledger = yield* SubmissionLedger
1324
+ const listNonterminal = ledger.listNonterminal ?? Stream.runCollect(ledger.scanNonterminal)
1325
+ const wakes = yield* WakeScheduler
1326
+ const hints = yield* DurableAlarmService
1327
+ const alarms = yield* ThreadMaintenanceAlarm
1328
+ const config = yield* CloudflareDurableRuntimeConfig
1329
+ const { ctx } = yield* DurableObjectContext
1330
+ const execution = DurableObjectState.fromDurableObjectState(ctx)
1331
+ const dueQueue = DueQueue.make(ctx.storage)
1332
+ const storage = DurableObjectStorage.fromDurableObjectStorage(ctx.storage)
1333
+ const runStorage = yield* makeStorageEffect
1334
+ const failpoint = yield* ThreadMaintenanceFailpoint
1335
+
1336
+ const mutations = yield* ThreadMutationGate
1337
+ const publication = yield* ThreadPublication
1338
+
1339
+ const publicationContext = yield* Effect.context<
1340
+ ThreadPublication | DurableObjectContext | SqlClient.SqlClient
1341
+ >()
1342
+
1343
+ const projection = yield* ThreadProjectionMaintenance
1344
+ const messages = yield* ThreadMessageDelivery
1345
+ const host = yield* ThreadHostMaintenance
1346
+ const framework = yield* ThreadNativeMaintenance
1347
+ const placement = yield* Effect.serviceOption(ThreadObjectPlacement)
1348
+ const nativeThread = Option.isSome(placement) ? placement.value.threadId : undefined
1349
+
1350
+ const nativeDispatchConcurrency = () => (framework.singleThreadRuntime === runtime ? 1 : 2)
1351
+
1352
+ for (const lane of host.lanes) {
1353
+ yield* Schema.decodeEffect(DueQueue.HostLaneId)(lane.id).pipe(
1354
+ Effect.mapError(alarmFailure('maintenance lane ID')),
1355
+ )
1356
+ }
1357
+
1358
+ const recoveryEvents = Option.getOrElse(
1359
+ yield* Effect.serviceOption(ThreadRecoveryEvents),
1360
+ () => ThreadRecoveryEvents.of({ publish: () => Effect.void }),
1361
+ )
1362
+
1363
+ // Hydrated by the existing maintenance-record reads, never by a status scan. All
1364
+ // queue mutations update this hint under the same storage reservation. Eviction
1365
+ // reconstructs it in ensureAlarm/beginPass; the durable queue remains authoritative.
1366
+ let recoveryEventsPending = false
1367
+
1368
+ const maintenancePassGate = yield* Semaphore.make(1)
1369
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2))
1370
+ const runTransaction = yield* makeStorageOperation
1371
+ const { run: runAlarmTransaction } = yield* makeAlarmOperation
1372
+
1373
+ const queueSnapshot = runTransaction('read maintenance due queue', async () => dueQueue.read())
1374
+
1375
+ const reportParked = Effect.gen(function*() {
1376
+ if (!(yield* queueSnapshot).some((row) => row.state === 'parked' && row.reported === 0)) {
1377
+ return
1378
+ }
1379
+
1380
+ const rows = yield* runTransaction(
1381
+ 'mark parked maintenance reports',
1382
+ () => dueQueue.transaction(async () => dueQueue.takeParkedReports()),
1383
+ )
1384
+
1385
+ for (const row of rows) {
1386
+ const lane = [
1387
+ DueQueue.Native,
1388
+ DueQueue.Publication,
1389
+ DueQueue.Projection,
1390
+ DueQueue.Messages,
1391
+ DueQueue.RecoveryEvents,
1392
+ DueQueue.Lifecycle,
1393
+ ].includes(row.id)
1394
+ ? row.id.slice('effect-agent:'.length)
1395
+ : 'host'
1396
+
1397
+ yield* ErrorReporter.report(
1398
+ Cause.fail(
1399
+ MaintenanceRetryParked.make({
1400
+ lane,
1401
+ retryAfterMillis: DueQueue.ParkedRetryMillis,
1402
+ }),
1403
+ ),
1404
+ )
1405
+ }
1406
+ }).pipe(Effect.catchCause((cause) => ErrorReporter.report(cause)))
1407
+
1408
+ yield* runTransaction('register native maintenance lanes', () =>
1409
+ dueQueue.transaction(async () => {
1410
+ for (
1411
+ const id of [
1412
+ DueQueue.Publication,
1413
+ DueQueue.Projection,
1414
+ DueQueue.Messages,
1415
+ ...framework.lanes.map((lane) => lane.id),
1416
+ ]
1417
+ ) {
1418
+ dueQueue.register(id)
1419
+ }
1420
+
1421
+ // Earlier releases split this one outbox across start and after-native lanes.
1422
+ // Retire only scheduling metadata, retaining revision fencing and domain retries.
1423
+ if (framework.lanes.some((lane) => lane.id === DueQueue.Lifecycle)) {
1424
+ const start = dueQueue.read().find((row) => row.id === 'effect-agent:lifecycle-start')
1425
+
1426
+ if (start !== undefined && start.dueAt !== null) {
1427
+ dueQueue.dirty(DueQueue.Lifecycle, start.dueAt)
1428
+ dueQueue.complete(start, null)
1429
+ }
1430
+ }
1431
+ }))
1432
+
1433
+ const runQueued = <E, R>(
1434
+ selected: DueQueue.DueLane,
1435
+ work: Effect.Effect<Option.Option<number>, E, R>,
1436
+ observed: MaintenanceObservation,
1437
+ yielded?: () => boolean,
1438
+ ) => {
1439
+ let row = selected
1440
+ let charged = false
1441
+
1442
+ return Effect.gen(function*() {
1443
+ const now = yield* Clock.currentTimeMillis
1444
+
1445
+ const claimed = yield* runAlarmTransaction(
1446
+ 'charge maintenance attempt',
1447
+ async (_transaction, checkpoint) => {
1448
+ const claimed = dueQueue.claim(selected, now)
1449
+ const next = DueQueue.next(dueQueue.read())
1450
+
1451
+ if (Number.isFinite(next)) checkpoint.at(Math.max(now + minimumAlarmDelay, next))
1452
+ else checkpoint.cancel()
1453
+
1454
+ return claimed
1455
+ },
1456
+ )
1457
+
1458
+ if (claimed === undefined) return Option.none<number>()
1459
+ row = claimed
1460
+ charged = true
1461
+ observed.charged.set(row.id, row.revision)
1462
+ // Include mid-pass enrollments in failure rearming if their checkpoint is
1463
+ // interrupted. CAS still protects completed waves and racing producers.
1464
+ observed.queue.set(row.id, row)
1465
+ observed.available.set(row.id, row.revision)
1466
+
1467
+ return yield* work
1468
+ }).pipe(
1469
+ Effect.onExit((exit) => {
1470
+ if (!charged) return Effect.void
1471
+ if (
1472
+ yielded?.() === true &&
1473
+ Exit.isFailure(exit) &&
1474
+ Cause.hasInterruptsOnly(exit.cause)
1475
+ ) {
1476
+ // A promptness yield is neither completion nor a failed delivery. Keep the
1477
+ // exact due revision; pass-level failure rearming must not back off this wave.
1478
+ observed.queue.delete(row.id)
1479
+
1480
+ return Effect.void
1481
+ }
1482
+
1483
+ return mutations
1484
+ .withSnapshot(() =>
1485
+ Effect.gen(function*() {
1486
+ const active = (yield* mutations.activeLanes).has(row.id)
1487
+ const now = yield* Clock.currentTimeMillis
1488
+ const failed = Exit.isFailure(exit)
1489
+
1490
+ const next = failed
1491
+ ? now + backoffDelay(row.stalls, yield* Random.next)
1492
+ : Option.getOrNull(exit.value)
1493
+
1494
+ const checkpointed = yield* runTransaction('checkpoint maintenance lane', () =>
1495
+ dueQueue.transaction(async () => {
1496
+ // A producer can be between enrollment and its source commit. Never acknowledge
1497
+ // that observation; its completion will notify the event or retain the alarm.
1498
+ if (active) {
1499
+ return
1500
+ }
1501
+ const current = dueQueue.read().find((lane) =>
1502
+ lane.id === row.id
1503
+ )
1504
+
1505
+ if (current?.revision !== row.revision) return
1506
+
1507
+ return dueQueue.complete(row, next)?.revision
1508
+ }))
1509
+
1510
+ // This pass's own checkpoint is not fresh producer enrollment. Record it
1511
+ // only after commit, while the snapshot gate still excludes a new producer.
1512
+ if (checkpointed !== undefined) observed.available.set(row.id, checkpointed)
1513
+ })
1514
+ )
1515
+ .pipe(
1516
+ // Waiting for a producer or the SQL connection belongs to the wave budget.
1517
+ // An interrupted checkpoint leaves its revision due for event rearming;
1518
+ // the short storage transaction itself remains atomic.
1519
+ Effect.interruptible,
1520
+ )
1521
+ }),
1522
+ )
1523
+ }
1524
+
1525
+ const appendRecoveryEvents = async (
1526
+ transaction: MaintenanceStorage,
1527
+ events: ReadonlyArray<Omit<ThreadRecoveryFaultEvent, 'sequence'>>,
1528
+ ) => {
1529
+ if (events.length === 0) return
1530
+ const { state } = await readMaintenanceState(transaction)
1531
+ let sequence = state.recoveryEventSequence ?? 0n
1532
+
1533
+ for (const event of events) {
1534
+ sequence++
1535
+ await transaction.put(
1536
+ recoveryEventKey(sequence),
1537
+ encodeRecoveryEvent(ThreadRecoveryFaultEvent.make({ ...event, sequence })),
1538
+ )
1539
+ }
1540
+ await transaction.put(
1541
+ MAINTENANCE_STATE_KEY,
1542
+ encodeMaintenanceState(
1543
+ ThreadMaintenanceState.make({
1544
+ ...state,
1545
+ recoveryEventSequence: sequence,
1546
+ }),
1547
+ ),
1548
+ )
1549
+ dueQueue.dirty(DueQueue.RecoveryEvents, 0, true)
1550
+ recoveryEventsPending = true
1551
+ }
1552
+
1553
+ const recoveryEventLane: ThreadHostMaintenanceLane = {
1554
+ id: DueQueue.RecoveryEvents,
1555
+ dispatchTimeoutMillis: 30_000,
1556
+ run: Effect.gen(function*() {
1557
+ if (!recoveryEventsPending) return Option.none<number>()
1558
+
1559
+ const range = yield* runTransaction(
1560
+ 'select recovery events',
1561
+ () =>
1562
+ dueQueue.transaction(async (transaction) => {
1563
+ const { state } = await readMaintenanceState(transaction)
1564
+
1565
+ return {
1566
+ next: (state.recoveryEventAcknowledged ?? 0n) + 1n,
1567
+ through: state.recoveryEventSequence ?? 0n,
1568
+ }
1569
+ }),
1570
+ )
1571
+
1572
+ for (let sequence = range.next; sequence <= range.through; sequence++) {
1573
+ const event = yield* runTransaction(
1574
+ 'read recovery event',
1575
+ async () => decodeRecoveryEvent(await ctx.storage.get(recoveryEventKey(sequence))),
1576
+ )
1577
+
1578
+ if (event.sequence !== sequence) {
1579
+ return yield* DurableAlarmError.make({
1580
+ operation: 'read recovery event',
1581
+ message: 'Recovery event does not match its sequence key',
1582
+ })
1583
+ }
1584
+
1585
+ // No storage reservation or source mutation gate is held during host delivery.
1586
+ yield* recoveryEvents.publish(event)
1587
+ const acknowledgedAt = yield* Clock.currentTimeMillis
1588
+
1589
+ yield* runTransaction('acknowledge recovery event', () =>
1590
+ dueQueue.transaction(async (transaction) => {
1591
+ const { state } = await readMaintenanceState(transaction)
1592
+
1593
+ const next = ThreadMaintenanceState.make({
1594
+ ...state,
1595
+ recoveryEventAcknowledged: sequence,
1596
+ })
1597
+
1598
+ await transaction.delete(recoveryEventKey(sequence))
1599
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next))
1600
+ recoveryEventsPending = hasRecoveryEvents(next)
1601
+ dueQueue.progress(DueQueue.RecoveryEvents, acknowledgedAt, sequence)
1602
+ const lane = dueQueue.read().find((row) => row.id === DueQueue.RecoveryEvents)
1603
+
1604
+ if (lane !== undefined) {
1605
+ dueQueue.complete(lane, recoveryEventsPending ? acknowledgedAt : null)
1606
+ }
1607
+ }))
1608
+ }
1609
+
1610
+ return recoveryEventsPending ? Option.some(0) : Option.none<number>()
1611
+ }),
1612
+ }
1613
+
1614
+ const recordRecoveryFaults = Effect.fnUntraced(function*(
1615
+ result: RecoverySweepResult,
1616
+ recovery: NativeRecovery,
1617
+ current?: ReadonlyArray<SubmissionWorkItem>,
1618
+ selectedThread?: ThreadId,
1619
+ ) {
1620
+ const threads = new Map<ThreadId, RecoveryFailure | undefined>()
1621
+
1622
+ if (selectedThread !== undefined) threads.set(selectedThread, undefined)
1623
+ for (const report of result.reports) threads.set(report.threadId, undefined)
1624
+ for (const report of result.workReports ?? []) threads.set(report.threadId, undefined)
1625
+ for (const blocked of result.blocked) threads.set(blocked.threadId, blocked.failure)
1626
+
1627
+ // This pass owns fault writes. Known absence needs no second transaction;
1628
+ // blocked results and retained faults still commit their transitions.
1629
+ if (
1630
+ threads.size === 0 ||
1631
+ [...threads].every(
1632
+ ([threadId, failure]) =>
1633
+ failure === undefined &&
1634
+ recovery.loaded.has(threadId) &&
1635
+ !recovery.faults.has(threadId),
1636
+ )
1637
+ ) {
1638
+ return new Map<ThreadId, ThreadRecoveryFault>()
1639
+ }
1640
+
1641
+ const now = yield* Clock.currentTimeMillis
1642
+
1643
+ // Fault-only discovery uses control state even when retained payloads cannot decode.
1644
+ const submissions = current ?? (result.blocked.length === 0 ? [] : yield* listNonterminal)
1645
+
1646
+ yield* failpoint.hit('maintenance:recovery-status:before')
1647
+
1648
+ const retained = yield* runTransaction(
1649
+ 'record Thread recovery faults',
1650
+ () =>
1651
+ dueQueue.transaction(async (transaction) => {
1652
+ const events: Array<Omit<ThreadRecoveryFaultEvent, 'sequence'>> = []
1653
+ const newlyBlocked: Array<ThreadRecoveryFault> = []
1654
+ const faults = new Map<ThreadId, ThreadRecoveryFault>()
1655
+ const recipients = new Map<ThreadId, ReadonlySet<SubmissionId>>()
1656
+
1657
+ for (const [threadId, failure] of threads) {
1658
+ const key = recoveryFaultKey(threadId)
1659
+ const encoded = await transaction.get(key)
1660
+
1661
+ const previous = encoded === undefined ? undefined : decodeRecoveryFault(threadId, encoded)
1662
+
1663
+ const previousIds = previous === undefined ? [] : await readRecoveryRecipients(transaction, previous)
1664
+
1665
+ const known = new Set(previousIds)
1666
+
1667
+ recipients.set(threadId, known)
1668
+
1669
+ if (failure === undefined) {
1670
+ if (previous !== undefined) {
1671
+ await transaction.delete(key)
1672
+ for (let start = 0; start < (previous.recipientCount ?? 0); start += 128) {
1673
+ await transaction.delete(recoveryRecipientKeys(previous, start))
1674
+ }
1675
+ for (
1676
+ const id of previous.recipientCount === undefined
1677
+ ? result.reports
1678
+ .filter((report) => report.threadId === threadId)
1679
+ .map((report) => report.submissionId)
1680
+ : previousIds
1681
+ ) {
1682
+ events.push(recoveryEvent(previous, id, 'cleared', now))
1683
+ }
1684
+ }
1685
+ continue
1686
+ }
1687
+
1688
+ const added = submissions
1689
+ .filter((row) => row.threadId === threadId && !known.has(row.submissionId))
1690
+ .map((row) => row.submissionId)
1691
+
1692
+ await appendRecoveryRecipients(transaction, threadId, previousIds.length, added)
1693
+
1694
+ const fault = ThreadRecoveryFault.make({
1695
+ schemaVersion: 1,
1696
+ threadId,
1697
+ firstFailedAt: previous?.firstFailedAt ?? now,
1698
+ lastFailedAt: now,
1699
+ attempts: Math.min(2_147_483_647, (previous?.attempts ?? 0) + 1),
1700
+ retryAt: now + Math.min(60_000, 5_000 * 2 ** Math.min(30, previous?.attempts ?? 0)),
1701
+ failure,
1702
+ recipientCount: previousIds.length + added.length,
1703
+ })
1704
+
1705
+ await transaction.put(key, encodeRecoveryFault(fault))
1706
+ if (previous !== undefined && !sameRecoveryFailure(previous.failure, failure)) {
1707
+ for (const id of previousIds) events.push(recoveryEvent(fault, id, 'changed', now))
1708
+ }
1709
+ for (const id of added) {
1710
+ known.add(id)
1711
+ events.push(recoveryEvent(fault, id, 'created', now))
1712
+ }
1713
+ faults.set(threadId, fault)
1714
+ if (previous === undefined) newlyBlocked.push(fault)
1715
+ }
1716
+
1717
+ await appendRecoveryEvents(transaction, events)
1718
+
1719
+ return {
1720
+ changed: new Set(events.map((event) => event.threadId)),
1721
+ newlyBlocked,
1722
+ faults,
1723
+ recipients,
1724
+ }
1725
+ }),
1726
+ )
1727
+
1728
+ yield* failpoint.hit('maintenance:recovery-status:after')
1729
+ for (const [threadId, ids] of retained.recipients) recovery.recipients.set(threadId, ids)
1730
+ // A healthy unchanged head must not wake its own maintenance loop.
1731
+ for (const threadId of retained.changed) yield* wakes.notify(threadId)
1732
+ for (const fault of retained.newlyBlocked) {
1733
+ yield* Effect.logError(
1734
+ 'Native Thread recovery blocked; accepted work remains pending',
1735
+ fault.failure.reason === 'defect'
1736
+ ? Cause.die(fault.failure)
1737
+ : Cause.fail(fault.failure),
1738
+ ).pipe(Effect.annotateLogs({ threadId: fault.threadId }))
1739
+ }
1740
+
1741
+ return retained.faults
1742
+ })
1743
+
1744
+ const recoverThread = Effect.fnUntraced(function*(
1745
+ threadId: ThreadId,
1746
+ recovery: NativeRecovery,
1747
+ ) {
1748
+ const retained = yield* runTransaction('read work recovery cursor', async () => {
1749
+ const value = await ctx.storage.get(workCursorKey(threadId))
1750
+
1751
+ return value === undefined
1752
+ ? undefined
1753
+ : Schema.decodeUnknownSync(NativeWorkCursor)(value)
1754
+ })
1755
+
1756
+ if (retained !== undefined && retained.threadId !== threadId) {
1757
+ return yield* DurableAlarmError.make({
1758
+ operation: 'read work recovery cursor',
1759
+ message: 'Work cursor belongs to another Thread',
1760
+ })
1761
+ }
1762
+ let cursor = retained?.cursor
1763
+
1764
+ do {
1765
+ const result = yield* runtime
1766
+ .runRecovery({
1767
+ threadId,
1768
+ deferUnclaimedAdmissions: true,
1769
+ ...(cursor === undefined ? {} : { cursor }),
1770
+ })
1771
+ .pipe(Effect.provideService(CurrentNativeSource, true))
1772
+
1773
+ // Persist each bounded pass before a claim; eviction resumes past consumed metadata.
1774
+ const faults = yield* recordRecoveryFaults(result, recovery, undefined, threadId)
1775
+
1776
+ if (cursor !== undefined || result.cursor !== undefined) {
1777
+ yield* runTransaction('checkpoint work recovery cursor', async () => {
1778
+ if (result.cursor === undefined) await ctx.storage.delete(workCursorKey(threadId))
1779
+ else {
1780
+ await ctx.storage.put(
1781
+ workCursorKey(threadId),
1782
+ Schema.encodeSync(NativeWorkCursor)({ threadId, cursor: result.cursor }),
1783
+ )
1784
+ }
1785
+ })
1786
+ }
1787
+ for (const report of result.reports) recovery.reports.set(report.submissionId, report)
1788
+ recovery.faults.delete(threadId)
1789
+ for (const [id, fault] of faults) recovery.faults.set(id, fault)
1790
+ recovery.recovered += (result.workReports?.length ?? result.reports.length) + result.blocked.length
1791
+ recovery.repaired ||= (result.workReports ?? result.reports).some(
1792
+ (report) => report.disposition === 'repaired',
1793
+ )
1794
+ for (const report of result.workReports ?? []) {
1795
+ if (report.retryAtMillis !== undefined) {
1796
+ recovery.retryAtMillis = Math.min(
1797
+ recovery.retryAtMillis ?? Infinity,
1798
+ report.retryAtMillis,
1799
+ )
1800
+ }
1801
+ }
1802
+ cursor = result.blocked.length > 0 ? undefined : result.cursor
1803
+ } while (cursor !== undefined)
1804
+ })
1805
+
1806
+ // Registry changes, including upgrades from timed binding retries, create one native
1807
+ // opportunity. Unchanged registries leave parked work dormant across Object eviction.
1808
+ const readCurrentMaintenanceState = async (transaction: MaintenanceStorage) => {
1809
+ const current = await readMaintenanceState(transaction)
1810
+
1811
+ if (current.state.bindingRegistryKey === runtime.bindingRegistryKey) return current
1812
+
1813
+ const state = ThreadMaintenanceState.make({
1814
+ ...Struct.omit(current.state, ['retry']),
1815
+ bindingRegistryKey: runtime.bindingRegistryKey,
1816
+ bindingWaits: [],
1817
+ dirty: current.state.dirty + 1n,
1818
+ })
1819
+
1820
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state))
1821
+ dueQueue.dirty(DueQueue.Native, 0, true)
1822
+
1823
+ return { state, initialized: true }
1824
+ }
1825
+
1826
+ const ensureAlarm = Effect.fnUntraced(function*() {
1827
+ yield* failpoint.hit('maintenance:ensure:before')
1828
+ const now = yield* Clock.currentTimeMillis
1829
+
1830
+ yield* runAlarmTransaction('ensure maintenance alarm', async (transaction, checkpoint) => {
1831
+ const { state, initialized } = await readCurrentMaintenanceState(transaction)
1832
+
1833
+ recoveryEventsPending = hasRecoveryEvents(state)
1834
+ const rows = dueQueue.read()
1835
+
1836
+ if (recoveryEventsPending && !rows.some((row) => row.id === DueQueue.RecoveryEvents)) {
1837
+ dueQueue.dirty(DueQueue.RecoveryEvents, now)
1838
+ }
1839
+ if (!initialized) {
1840
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state))
1841
+ }
1842
+
1843
+ const native = state.dirty > state.processed
1844
+ ? state.retry?.generation === state.dirty
1845
+ ? state.retry.notBefore
1846
+ : (rows.find((row) => row.id === DueQueue.Native)?.dueAt ?? now + minimumAlarmDelay)
1847
+ : null
1848
+
1849
+ dueQueue.checkpointNative(native)
1850
+ const next = DueQueue.next(dueQueue.read())
1851
+
1852
+ if (Number.isFinite(next)) checkpoint.earlier(Math.max(now + minimumAlarmDelay, next))
1853
+ })
1854
+ yield* failpoint.hit('maintenance:ensure:after')
1855
+ })
1856
+
1857
+ const beginPass = Effect.fnUntraced(function*(observed: MaintenanceObservation) {
1858
+ yield* failpoint.hit('maintenance:begin:before')
1859
+ const now = yield* Clock.currentTimeMillis
1860
+
1861
+ const result = yield* runAlarmTransaction(
1862
+ 'begin maintenance pass',
1863
+ async (transaction, checkpoint) => {
1864
+ const { state, initialized } = await readCurrentMaintenanceState(transaction)
1865
+
1866
+ recoveryEventsPending = hasRecoveryEvents(state)
1867
+
1868
+ observed.generation = state.dirty
1869
+ if (!initialized) {
1870
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state))
1871
+ }
1872
+ const retryAt = state.retry?.generation === state.dirty ? state.retry.notBefore : 0
1873
+
1874
+ const rows = dueQueue.read()
1875
+ const native = rows.find((row) => row.id === DueQueue.Native)
1876
+ const publication = rows.find((row) => row.id === DueQueue.Publication)
1877
+
1878
+ if (
1879
+ state.processed >= state.dirty ||
1880
+ retryAt > now ||
1881
+ native === undefined ||
1882
+ native.dueAt === null ||
1883
+ native.notBefore > now ||
1884
+ publication?.state === 'parked'
1885
+ ) {
1886
+ return {
1887
+ _tag: 'CaughtUp' as const,
1888
+ nonterminal: state.nonterminal,
1889
+ }
1890
+ }
1891
+
1892
+ // One debit per native progress revision in this event. Source progress may
1893
+ // legitimately admit another wave; a generation change alone cannot.
1894
+ const alreadyCharged = observed.charged.get(DueQueue.Native) === native.revision
1895
+ const charged = alreadyCharged ? native : dueQueue.claim(native, now, true)
1896
+
1897
+ if (charged === undefined) {
1898
+ return { _tag: 'CaughtUp' as const, nonterminal: state.nonterminal }
1899
+ }
1900
+ observed.queue.set(DueQueue.Native, charged)
1901
+ observed.charged.set(DueQueue.Native, charged.revision)
1902
+ const deadline = DueQueue.next(dueQueue.read())
1903
+
1904
+ if (Number.isFinite(deadline)) {
1905
+ checkpoint.at(Math.max(now + minimumAlarmDelay, deadline))
1906
+ } else checkpoint.cancel()
1907
+
1908
+ return {
1909
+ _tag: 'Actionable' as const,
1910
+ generation: state.dirty,
1911
+ sourceRevision: charged.revision,
1912
+ nonterminal: state.nonterminal,
1913
+ stalls: charged.stalls,
1914
+ }
1915
+ },
1916
+ )
1917
+
1918
+ yield* failpoint.hit('maintenance:begin:after')
1919
+
1920
+ return result
1921
+ })
1922
+
1923
+ const backoffDelay = (priorStalls: number, jitter: number) => {
1924
+ const backoff = Math.min(
1925
+ config.alarmBackoffCap,
1926
+ config.alarmBackoffBase * 2 ** Math.min(priorStalls, 30),
1927
+ )
1928
+
1929
+ // Jitter over [backoff/2, backoff] spreads retries without exceeding the cap.
1930
+ return Math.ceil(backoff / 2 + (backoff / 2) * jitter)
1931
+ }
1932
+
1933
+ const rearmDelay = Effect.fnUntraced(function*(progressed: boolean, priorStalls: number) {
1934
+ return progressed ? config.alarmBackoffBase : backoffDelay(priorStalls, yield* Random.next)
1935
+ })
1936
+
1937
+ const rearmFailure = Effect.fnUntraced(function*(observed: MaintenanceObservation) {
1938
+ const { generation, nativeOnly } = observed
1939
+
1940
+ if (generation === undefined) return
1941
+ yield* failpoint.hit('maintenance:retry:before')
1942
+ yield* mutations.withSnapshot((active) =>
1943
+ Effect.gen(function*() {
1944
+ const now = yield* Clock.currentTimeMillis
1945
+
1946
+ const jitter = yield* Random.next
1947
+
1948
+ yield* runAlarmTransaction(
1949
+ 'back off failed maintenance',
1950
+ async (transaction, checkpoint) => {
1951
+ const { state } = await readMaintenanceState(transaction)
1952
+
1953
+ const previous = state.retry?.generation === generation && state.retry.nativeOnly === nativeOnly
1954
+ ? state.retry
1955
+ : undefined
1956
+
1957
+ const retry = state.retry?.generation === generation && state.retry.nativeOnly
1958
+ ? state.retry
1959
+ : MaintenanceRetry.make({
1960
+ generation,
1961
+ notBefore: Math.max(
1962
+ previous?.notBefore ?? 0,
1963
+ now + backoffDelay(previous?.stalls ?? 0, jitter),
1964
+ ),
1965
+ nativeOnly,
1966
+ stalls: Math.min(30, (previous?.stalls ?? 0) + 1),
1967
+ })
1968
+
1969
+ await transaction.put(
1970
+ MAINTENANCE_STATE_KEY,
1971
+ encodeMaintenanceState(ThreadMaintenanceState.make({ ...state, retry })),
1972
+ )
1973
+
1974
+ // Never postpone a producer that raced the failed observation. Host work
1975
+ // retains its own deadline; an early delivery skips native recovery below.
1976
+ const nativeDeadline = active > 0 || state.dirty !== generation
1977
+ ? now + minimumAlarmDelay
1978
+ : retry.notBefore
1979
+
1980
+ dueQueue.checkpointNative(
1981
+ state.dirty > state.processed || active > 0 ? nativeDeadline : null,
1982
+ )
1983
+ // Defer only the unacknowledged observations from this failed event. A
1984
+ // completed wave or racing enrollment has a different revision.
1985
+ for (const row of observed.queue.values()) {
1986
+ if (row.id !== DueQueue.Native && row.dueAt !== null && row.dueAt <= now) {
1987
+ const charged = observed.charged.get(row.id) === row.revision
1988
+ ? row
1989
+ : dueQueue.claim(row, now)
1990
+
1991
+ if (charged !== undefined) {
1992
+ dueQueue.complete(charged, now + backoffDelay(charged.stalls, jitter))
1993
+ }
1994
+ }
1995
+ }
1996
+ const next = DueQueue.next(dueQueue.read())
1997
+
1998
+ if (Number.isFinite(next)) checkpoint.at(Math.max(now + minimumAlarmDelay, next))
1999
+ else checkpoint.cancel()
2000
+ },
2001
+ )
2002
+ })
2003
+ )
2004
+ yield* failpoint.hit('maintenance:retry:after')
2005
+ })
2006
+
2007
+ const beginNative = (observed: MaintenanceObservation) =>
2008
+ mutations.withSnapshot((activeAtStart) =>
2009
+ Effect.gen(function*() {
2010
+ const generation = yield* beginPass(observed)
2011
+
2012
+ if (activeAtStart === 0) {
2013
+ const native = (yield* queueSnapshot).find((row) => row.id === DueQueue.Native)
2014
+
2015
+ if (native !== undefined) observed.available.set(native.id, native.revision)
2016
+ }
2017
+
2018
+ return { ...generation, activeAtStart }
2019
+ })
2020
+ )
2021
+
2022
+ const attemptSelected = Effect.fnUntraced(function*(
2023
+ selected: Pick<SubmissionWorkItem, 'threadId' | 'submissionId'>,
2024
+ previousWaits: ReadonlyArray<BindingWait>,
2025
+ yieldAfter: DateTime.Utc,
2026
+ recovery: NativeRecovery,
2027
+ admitted = false,
2028
+ ): Effect.fn.Return<number, MaintenancePassFailure> {
2029
+ if (!admitted) yield* recoverThread(selected.threadId, recovery)
2030
+
2031
+ let bindingFailure: DurableBindingFailure | undefined
2032
+
2033
+ // A missing binding releases its slot after retaining this exact Submission
2034
+ // and committing its registry wait below.
2035
+ const settlement = recovery.faults.has(selected.threadId)
2036
+ ? Option.none()
2037
+ : yield* runtime
2038
+ .processThreadHead(selected.threadId, {
2039
+ yieldAfter,
2040
+ ...(admitted ? { admittedSubmissionId: selected.submissionId } : {}),
2041
+ })
2042
+ .pipe(
2043
+ Effect.provideService(CurrentNativeSource, true),
2044
+ Effect.catchTag('BindingUnavailable', (failure) => {
2045
+ bindingFailure = failure
2046
+
2047
+ return Effect.succeedNone
2048
+ }),
2049
+ )
2050
+
2051
+ const previous = previousWaits.find((wait) => wait.submissionId === selected.submissionId)
2052
+
2053
+ const wait = bindingFailure === undefined
2054
+ ? undefined
2055
+ : BindingWait.make({
2056
+ threadId: selected.threadId,
2057
+ submissionId: selected.submissionId,
2058
+ reportedAt: previous?.reportedAt ?? (yield* Clock.currentTimeMillis),
2059
+ })
2060
+
2061
+ // Report before recording reportedAt. Interruption before the write may repeat a
2062
+ // report, but a durable wait must never suppress a report that was not delivered.
2063
+ if (bindingFailure !== undefined && previous === undefined) {
2064
+ yield* Effect.logError(
2065
+ 'Thread parked until its agent binding registry changes; original work remains pending',
2066
+ Cause.fail(bindingFailure),
2067
+ ).pipe(
2068
+ Effect.annotateLogs({
2069
+ threadId: selected.threadId,
2070
+ submissionId: selected.submissionId,
2071
+ }),
2072
+ )
2073
+ }
2074
+
2075
+ if (wait !== undefined || previous !== undefined) {
2076
+ // The Attempt released its Claim. Commit its binding wait (or clear) once,
2077
+ // before joining fallible auxiliary work. This local fact neither acknowledges
2078
+ // a generation nor changes the shared alarm.
2079
+ yield* failpoint.hit('maintenance:binding-retry:before')
2080
+ yield* runStorage(
2081
+ 'record submission binding wait',
2082
+ storage
2083
+ .transaction((transaction) =>
2084
+ Effect.gen(function*() {
2085
+ const encoded = yield* transaction.get(MAINTENANCE_STATE_KEY)
2086
+
2087
+ const state = encoded === undefined
2088
+ ? initialMaintenanceState()
2089
+ : yield* Schema.decodeUnknownEffect(ThreadMaintenanceState)(encoded)
2090
+
2091
+ const bindingWaits = [
2092
+ ...(state.bindingWaits ?? []).filter(
2093
+ (entry) => entry.submissionId !== selected.submissionId,
2094
+ ),
2095
+ ...(wait === undefined ? [] : [wait]),
2096
+ ]
2097
+
2098
+ yield* transaction.put(
2099
+ MAINTENANCE_STATE_KEY,
2100
+ yield* Schema.encodeEffect(ThreadMaintenanceState)(
2101
+ ThreadMaintenanceState.make({ ...state, bindingWaits }),
2102
+ ),
2103
+ )
2104
+ })
2105
+ )
2106
+ .pipe(Effect.mapError(alarmFailure('record submission binding wait'))),
2107
+ )
2108
+ yield* failpoint.hit('maintenance:binding-retry:after')
2109
+ }
2110
+
2111
+ return Option.isSome(settlement) ? 1 : 0
2112
+ })
2113
+
2114
+ const advance = Effect.fnUntraced(function*(
2115
+ started: Effect.Success<ReturnType<typeof beginNative>>,
2116
+ yieldAfter: DateTime.Utc,
2117
+ observed: MaintenanceObservation,
2118
+ recovery: NativeRecovery,
2119
+ native: NativeDispatch,
2120
+ dispatch = true,
2121
+ reserved: ReadonlySet<ThreadId> = new Set(native.active.keys()),
2122
+ ): Effect.fn.Return<NativePassResult, MaintenancePassFailure> {
2123
+ let publicationRow = (yield* queueSnapshot).find((row) => row.id === DueQueue.Publication)
2124
+
2125
+ if (
2126
+ publicationRow !== undefined &&
2127
+ publicationRow.dueAt !== null &&
2128
+ publicationRow.dueAt <= (yield* Clock.currentTimeMillis)
2129
+ ) {
2130
+ yield* runQueued(
2131
+ publicationRow,
2132
+ mutations
2133
+ .withSnapshot((active) =>
2134
+ started._tag === 'Actionable' && active === 0
2135
+ ? publication.prepareGeneration(started.generation)
2136
+ : Effect.void
2137
+ )
2138
+ .pipe(Effect.andThen(publication.drain)),
2139
+ observed,
2140
+ )
2141
+ publicationRow = (yield* queueSnapshot).find((row) => row.id === DueQueue.Publication)
2142
+ }
2143
+ const pending = Option.fromNullishOr(publicationRow?.dueAt)
2144
+
2145
+ if (
2146
+ started._tag === 'CaughtUp' ||
2147
+ Option.isSome(pending) ||
2148
+ publicationRow?.state === 'parked'
2149
+ ) {
2150
+ const nextAttemptAt = yield* mutations.withSnapshot((active) =>
2151
+ Effect.gen(function*() {
2152
+ const now = yield* Clock.currentTimeMillis
2153
+
2154
+ const { state } = yield* runTransaction('read native maintenance deadline', () =>
2155
+ dueQueue.transaction((transaction) => readMaintenanceState(transaction)))
2156
+
2157
+ const native = active > 0 || state.dirty > state.processed
2158
+ ? state.retry?.generation === state.dirty && active === 0
2159
+ ? state.retry.notBefore
2160
+ : now + minimumAlarmDelay
2161
+ : Infinity
2162
+
2163
+ const next = Option.isSome(pending) ? pending.value : native
2164
+
2165
+ return Number.isFinite(next) ? Math.max(now + minimumAlarmDelay, next) : undefined
2166
+ })
2167
+ )
2168
+
2169
+ return {
2170
+ phase: 'caught-up',
2171
+ nonterminal: started.nonterminal,
2172
+ nextAttemptAt,
2173
+ }
2174
+ }
2175
+ if (
2176
+ native.generation !== started.generation ||
2177
+ native.sourceRevision !== started.sourceRevision
2178
+ ) {
2179
+ native.deferred.clear()
2180
+ native.generation = started.generation
2181
+ native.sourceRevision = started.sourceRevision
2182
+ }
2183
+ // A stable generation with no freed slot needs no second ledger/history scan.
2184
+ // Enrollment precedes admission: never cache a scan overlapping a producer body,
2185
+ // which may make a head ready later without another generation increment.
2186
+ if (
2187
+ native.active.size > 0 &&
2188
+ native.scanGeneration === started.generation &&
2189
+ native.scanRevision === started.sourceRevision
2190
+ ) {
2191
+ return {
2192
+ phase: 'actionable',
2193
+ nonterminal: started.nonterminal,
2194
+ nextAttemptAt: undefined,
2195
+ }
2196
+ }
2197
+ native.scanGeneration = started.activeAtStart === 0 ? started.generation : undefined
2198
+ native.scanRevision = started.activeAtStart === 0 ? started.sourceRevision : undefined
2199
+
2200
+ // Select from control state before reading execution history. A recovering or faulted
2201
+ // Thread cannot enter dispatch; old cleanup has its own scoped opportunity below.
2202
+ observed.nativeOnly = true
2203
+
2204
+ // Every checkpoint keeps the producer overlap that belongs to this recovery wave.
2205
+ const observation = (recovery.observation ??= {
2206
+ generation: started.generation,
2207
+ activeAtStart: started.activeAtStart,
2208
+ })
2209
+
2210
+ const { scannedGeneration, afterWorkThread } = yield* runTransaction(
2211
+ 'read work discovery position',
2212
+ async () => {
2213
+ const { state } = await readMaintenanceState(ctx.storage)
2214
+
2215
+ return {
2216
+ scannedGeneration: state.dirty,
2217
+ // Single-Thread placement would immediately wrap past its own cursor.
2218
+ afterWorkThread: framework.singleThreadRuntime === runtime &&
2219
+ state.lastRecoveredThreadId === nativeThread
2220
+ ? undefined
2221
+ : state.lastRecoveredThreadId,
2222
+ }
2223
+ },
2224
+ )
2225
+
2226
+ const current = yield* listNonterminal
2227
+
2228
+ // A current admission proves this native placement is materialized. Empty Objects
2229
+ // still discover retained canonical obligations without inventing a recovery owner.
2230
+ let workOwners = framework.singleThreadRuntime === runtime &&
2231
+ nativeThread !== undefined &&
2232
+ current.some((submission) => submission.threadId === nativeThread)
2233
+ ? { threadIds: [nativeThread], afterThreadId: undefined }
2234
+ : yield* runtime
2235
+ .discoverWorkThreads({
2236
+ limit: 32,
2237
+ ...(afterWorkThread === undefined ? {} : { afterThreadId: afterWorkThread }),
2238
+ })
2239
+ .pipe(Effect.provideService(CurrentNativeSource, true))
2240
+
2241
+ if (workOwners.threadIds.length === 0 && afterWorkThread !== undefined) {
2242
+ workOwners = yield* runtime
2243
+ .discoverWorkThreads({ limit: 32 })
2244
+ .pipe(Effect.provideService(CurrentNativeSource, true))
2245
+ }
2246
+ recovery.discoveryPending ||= workOwners.afterThreadId !== undefined
2247
+ const selectionTime = yield* Clock.currentTimeMillis
2248
+ const submissionsByThread = new Map<ThreadId, Array<SubmissionId>>()
2249
+
2250
+ for (const row of current) {
2251
+ const ids = submissionsByThread.get(row.threadId) ?? []
2252
+
2253
+ ids.push(row.submissionId)
2254
+ submissionsByThread.set(row.threadId, ids)
2255
+ }
2256
+ // Canonical obligations survive their last Submission. Reload their retained backoff
2257
+ // before selecting recovery, including after eviction or a newer host mutation.
2258
+ for (const threadId of workOwners.threadIds) {
2259
+ if (!submissionsByThread.has(threadId)) submissionsByThread.set(threadId, [])
2260
+ }
2261
+
2262
+ yield* runTransaction('read Thread recovery deadlines', async () => {
2263
+ for (const [threadId, ids] of submissionsByThread) {
2264
+ if (!recovery.loaded.has(threadId)) {
2265
+ const encoded = await ctx.storage.get(recoveryFaultKey(threadId))
2266
+
2267
+ if (encoded !== undefined) {
2268
+ const fault = decodeRecoveryFault(threadId, encoded)
2269
+
2270
+ recovery.faults.set(threadId, fault)
2271
+ recovery.recipients.set(
2272
+ threadId,
2273
+ new Set(await readRecoveryRecipients(ctx.storage, fault)),
2274
+ )
2275
+ }
2276
+ recovery.loaded.add(threadId)
2277
+ }
2278
+ const fault = recovery.faults.get(threadId)
2279
+
2280
+ if (
2281
+ fault === undefined ||
2282
+ ids.every((id) => recovery.recipients.get(threadId)?.has(id))
2283
+ ) {
2284
+ continue
2285
+ }
2286
+
2287
+ // Admissions during backoff need visibility without accelerating recovery.
2288
+ // Preserve recipients even if recovery later settles them before clearing.
2289
+ await dueQueue.transaction(async (transaction) => {
2290
+ const encoded = await transaction.get(recoveryFaultKey(threadId))
2291
+
2292
+ if (encoded === undefined) return
2293
+ const previous = decodeRecoveryFault(threadId, encoded)
2294
+ const previousIds = await readRecoveryRecipients(transaction, previous)
2295
+ const known = new Set(previousIds)
2296
+ const added = ids.filter((id) => !known.has(id))
2297
+
2298
+ if (added.length === 0) return
2299
+
2300
+ const updated = ThreadRecoveryFault.make({
2301
+ ...previous,
2302
+ recipientCount: previousIds.length + added.length,
2303
+ })
2304
+
2305
+ await appendRecoveryRecipients(transaction, threadId, previousIds.length, added)
2306
+ await transaction.put(recoveryFaultKey(threadId), encodeRecoveryFault(updated))
2307
+ await appendRecoveryEvents(
2308
+ transaction,
2309
+ added.map((id) => recoveryEvent(updated, id, 'created', selectionTime)),
2310
+ )
2311
+ recovery.faults.set(threadId, updated)
2312
+ recovery.recipients.set(threadId, new Set([...previousIds, ...added]))
2313
+ })
2314
+ }
2315
+ })
2316
+ const reports = recovery.reports
2317
+ const recoveryFaults = recovery.faults
2318
+
2319
+ const bindingWaits = yield* runTransaction(
2320
+ 'read binding waits',
2321
+ async () => (await readMaintenanceState(ctx.storage)).state.bindingWaits ?? [],
2322
+ )
2323
+
2324
+ const parked = new Set(bindingWaits.map((wait) => wait.submissionId))
2325
+
2326
+ const waiting = (row: SubmissionWorkItem) =>
2327
+ !recovery.pending.has(row.threadId) &&
2328
+ !recoveryFaults.has(row.threadId) &&
2329
+ (parked.has(row.submissionId) || stableExternalWait(row, reports))
2330
+
2331
+ const heads = new Map<ThreadId, SubmissionWorkItem>()
2332
+
2333
+ for (const row of current) {
2334
+ // Only recovered uncertainty may release later input; accepted aborts retain FIFO.
2335
+ if (row.state === 'unknown' && waiting(row)) continue
2336
+ if (!heads.has(row.threadId)) heads.set(row.threadId, row)
2337
+ }
2338
+ const stopping = new Set<ThreadId>()
2339
+
2340
+ for (const head of heads.values()) {
2341
+ if (
2342
+ head.state !== 'ready' ||
2343
+ native.active.has(head.threadId) ||
2344
+ recovery.pending.has(head.threadId) ||
2345
+ recoveryFaults.has(head.threadId)
2346
+ ) {
2347
+ continue
2348
+ }
2349
+
2350
+ // An accepted abort is cleanup even when its input was never claimed. This
2351
+ // control-only read must not decode the execution journal or a recovery snapshot.
2352
+ const intent = yield* isolateRecovery(
2353
+ ledger.readAbortIntent(AbortIntentRequest.make({ submissionId: head.submissionId })),
2354
+ {
2355
+ timeout: recoveryConfig.recoveryTimeout,
2356
+ phase: () => 'recovery',
2357
+ operation: 'read abort intent',
2358
+ },
2359
+ )
2360
+
2361
+ if (Result.isSuccess(intent)) {
2362
+ if (intent.success !== undefined) stopping.add(head.threadId)
2363
+ } else {
2364
+ const faults = yield* recordRecoveryFaults(
2365
+ RecoverySweepResult.make({
2366
+ reports: [],
2367
+ blocked: [
2368
+ RecoveryBlocked.make({ threadId: head.threadId, failure: intent.failure }),
2369
+ ],
2370
+ }),
2371
+ recovery,
2372
+ current,
2373
+ )
2374
+
2375
+ for (const [threadId, fault] of faults) recoveryFaults.set(threadId, fault)
2376
+ recovery.recovered++
2377
+ }
2378
+ }
2379
+
2380
+ const eligible = [...heads.values()]
2381
+ .filter(
2382
+ (head) =>
2383
+ !recovery.pending.has(head.threadId) &&
2384
+ !stopping.has(head.threadId) &&
2385
+ !recoveryFaults.has(head.threadId) &&
2386
+ !waiting(head) &&
2387
+ (head.state === 'ready' || reports.has(head.submissionId)),
2388
+ )
2389
+ .map((head) => head.threadId)
2390
+ .sort()
2391
+
2392
+ yield* failpoint.hit('maintenance:select:before')
2393
+
2394
+ const selection = yield* runTransaction(
2395
+ 'select maintenance lane',
2396
+ () =>
2397
+ dueQueue.transaction(async (transaction) => {
2398
+ const { state } = await readMaintenanceState(transaction)
2399
+
2400
+ const waits = (state.bindingWaits ?? []).filter(
2401
+ (retry) => heads.get(retry.threadId)?.submissionId === retry.submissionId,
2402
+ )
2403
+
2404
+ const runnable = eligible.filter(
2405
+ (threadId) =>
2406
+ !reserved.has(threadId) &&
2407
+ !native.active.has(threadId) &&
2408
+ !native.deferred.has(threadId) &&
2409
+ !waits.some((wait) => wait.threadId === threadId),
2410
+ )
2411
+
2412
+ const pivot = Math.max(
2413
+ 0,
2414
+ runnable.findIndex(
2415
+ (threadId) => state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,
2416
+ ),
2417
+ )
2418
+
2419
+ const selected = dispatch
2420
+ ? [...runnable.slice(pivot), ...runnable.slice(0, pivot)].slice(
2421
+ 0,
2422
+ nativeDispatchConcurrency() - reserved.size,
2423
+ )
2424
+ : []
2425
+
2426
+ const next = selected.at(-1)
2427
+
2428
+ if (next !== undefined && next !== state.lastServedThreadId) {
2429
+ await transaction.put(
2430
+ MAINTENANCE_STATE_KEY,
2431
+ encodeMaintenanceState(
2432
+ ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),
2433
+ ),
2434
+ )
2435
+ }
2436
+
2437
+ const backlog = recovery.started
2438
+ ? []
2439
+ : [...new Set([...heads.keys(), ...workOwners.threadIds])].filter((threadId) => {
2440
+ const fault = recoveryFaults.get(threadId)
2441
+
2442
+ return (
2443
+ !eligible.includes(threadId) &&
2444
+ (fault === undefined || fault.retryAt <= selectionTime)
2445
+ )
2446
+ })
2447
+
2448
+ // One finite wave, one Thread at a time, with the runtime's per-Thread deadline.
2449
+ // This cursor ensures an event deadline/eviction cannot always restart at the front.
2450
+ const after = backlog.filter(
2451
+ (threadId) => state.lastRecoveredThreadId === undefined || threadId > state.lastRecoveredThreadId,
2452
+ )
2453
+
2454
+ const before = backlog.filter(
2455
+ (threadId) =>
2456
+ state.lastRecoveredThreadId !== undefined &&
2457
+ threadId <= state.lastRecoveredThreadId,
2458
+ )
2459
+
2460
+ return {
2461
+ selected,
2462
+ waits,
2463
+ backlog: [...after, ...before].slice(0, 32),
2464
+ discoveryPending: backlog.length > 32,
2465
+ }
2466
+ }),
2467
+ )
2468
+
2469
+ yield* failpoint.hit('maintenance:select:after')
2470
+ if (!recovery.started) {
2471
+ recovery.started = true
2472
+ recovery.needsCheckpoint = selection.backlog.length > 0
2473
+ recovery.discoveryPending ||= selection.discoveryPending
2474
+ for (const threadId of selection.backlog) recovery.pending.add(threadId)
2475
+ yield* Deferred.succeed(recovery.queue, selection.backlog)
2476
+ }
2477
+
2478
+ for (const threadId of selection.selected) {
2479
+ const selected = heads.get(threadId)
2480
+
2481
+ if (selected === undefined) continue
2482
+ // Reserve before recovery or claim acquisition. The durable Claim remains the
2483
+ // authority; this event-local reservation only prevents duplicate dispatch.
2484
+ native.dispatched++
2485
+ native.active.set(
2486
+ threadId,
2487
+ yield* Effect.forkIn(
2488
+ attemptSelected(selected, selection.waits, yieldAfter, recovery),
2489
+ native.scope,
2490
+ ),
2491
+ )
2492
+ }
2493
+
2494
+ if (native.active.size > 0) {
2495
+ // Active Attempts own their claims and may still append/settle. Only acknowledge
2496
+ // a generation after joining every admitted native Attempt.
2497
+ return {
2498
+ phase: 'actionable',
2499
+ nonterminal: current.length,
2500
+ nextAttemptAt: undefined,
2501
+ dispatched: selection.selected.length > 0,
2502
+ }
2503
+ }
2504
+
2505
+ const remaining = yield* listNonterminal
2506
+ const waitingHeads = new Map<ThreadId, boolean>()
2507
+
2508
+ // Selected recovery must finish before its generation can be acknowledged: terminal
2509
+ // owners can supply a retry deadline only after their evidence read completes.
2510
+ const autonomous = recovery.pending.size > 0 ||
2511
+ recovery.discoveryPending ||
2512
+ recoveryFaults.size > 0 ||
2513
+ recovery.retryAtMillis !== undefined ||
2514
+ remaining.some((snapshot) => {
2515
+ if (snapshot.state === 'unknown' && waiting(snapshot)) return false
2516
+ const headWaiting = waitingHeads.get(snapshot.threadId)
2517
+
2518
+ if (headWaiting === undefined) waitingHeads.set(snapshot.threadId, waiting(snapshot))
2519
+ // FIFO followers cannot execute through a stable external wait. Only plain queued
2520
+ // input is dormant here; admission repairs and accepted aborts still need a pass.
2521
+ if (
2522
+ headWaiting === true &&
2523
+ snapshot.state === 'ready' &&
2524
+ reports.get(snapshot.submissionId)?.decision._tag === 'ApplyInput'
2525
+ ) {
2526
+ return false
2527
+ }
2528
+
2529
+ return !waiting(snapshot)
2530
+ })
2531
+
2532
+ const progressed = native.progressed || recovery.repaired
2533
+
2534
+ const now = yield* Clock.currentTimeMillis
2535
+ const ordinaryDelay = autonomous ? yield* rearmDelay(progressed, started.stalls) : 0
2536
+
2537
+ const nextEligible = [...recoveryFaults.values()]
2538
+ .map((fault) => fault.retryAt)
2539
+ .concat(
2540
+ eligible
2541
+ .filter((threadId) => !selection.waits.some((wait) => wait.threadId === threadId))
2542
+ .map(() => now),
2543
+ )
2544
+
2545
+ if (recovery.retryAtMillis !== undefined) nextEligible.push(recovery.retryAtMillis)
2546
+
2547
+ const retryDelay = nextEligible.length === 0 ? 0 : Math.max(0, Math.min(...nextEligible) - now)
2548
+
2549
+ const delay = Math.max(ordinaryDelay, retryDelay)
2550
+
2551
+ // Checkpoint native progress without changing the physical alarm. Auxiliary
2552
+ // delivery remains live; later mutations still advance the shared generation.
2553
+ yield* failpoint.hit('maintenance:checkpoint:before')
2554
+
2555
+ const nextAttemptAt = yield* mutations.withSnapshot((active) =>
2556
+ runTransaction('checkpoint native maintenance', () =>
2557
+ dueQueue.transaction(async (transaction) => {
2558
+ const { state } = await readMaintenanceState(transaction)
2559
+
2560
+ const mutationOverlap = observation.activeAtStart > 0 || started.activeAtStart > 0 || active > 0
2561
+
2562
+ // Only a scan without ledger work or canonical obligations can certify a newer
2563
+ // generation without another recovery wave. Read its generation before discovery
2564
+ // so progress committed during the scan retains its own recovery opportunity.
2565
+ const generation = remaining.length === 0 &&
2566
+ workOwners.threadIds.length === 0 &&
2567
+ !mutationOverlap &&
2568
+ state.dirty === scannedGeneration
2569
+ ? scannedGeneration
2570
+ : observation.generation
2571
+
2572
+ const processed = autonomous || mutationOverlap
2573
+ ? state.processed
2574
+ : state.processed > generation
2575
+ ? state.processed
2576
+ : generation
2577
+
2578
+ // Enrollment precedes the mutation body. A retry from an overlapping snapshot
2579
+ // must not defer work that becomes ready later in that same generation.
2580
+ const canBackoff = !mutationOverlap && state.dirty === started.generation
2581
+
2582
+ const next = ThreadMaintenanceState.make({
2583
+ ...Struct.omit(state, ['retry']),
2584
+ processed,
2585
+ nonterminal: remaining.length,
2586
+ bindingWaits: (state.bindingWaits ?? []).filter((retry) =>
2587
+ remaining.some((row) => row.submissionId === retry.submissionId)
2588
+ ),
2589
+ ...(autonomous && !progressed && canBackoff
2590
+ ? {
2591
+ retry: MaintenanceRetry.make({
2592
+ generation: started.generation,
2593
+ notBefore: now + delay,
2594
+ nativeOnly: true,
2595
+ stalls: Math.min(30, started.stalls + 1),
2596
+ }),
2597
+ }
2598
+ : {}),
2599
+ })
2600
+
2601
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next))
2602
+
2603
+ const dueAt = autonomous
2604
+ ? now + (canBackoff ? delay : minimumAlarmDelay)
2605
+ : mutationOverlap || next.dirty > next.processed
2606
+ ? now + minimumAlarmDelay
2607
+ : null
2608
+
2609
+ dueQueue.checkpointNative(dueAt)
2610
+
2611
+ return dueAt ?? undefined
2612
+ }))
2613
+ )
2614
+
2615
+ yield* failpoint.hit('maintenance:checkpoint:after')
2616
+ // A fresh empty scan may clear earlier producer overlap, but this pass has only
2617
+ // recovered its original generation. Retain that boundary for later canonical work.
2618
+ if (remaining.length === 0 && recovery.pending.size === 0) {
2619
+ recovery.observation = { generation: observation.generation, activeAtStart: 0 }
2620
+ }
2621
+ native.deferred.clear()
2622
+ native.progressed = false
2623
+ native.needsCheckpoint = false
2624
+
2625
+ return {
2626
+ phase: 'actionable',
2627
+ nonterminal: remaining.length,
2628
+ nextAttemptAt,
2629
+ }
2630
+ })
2631
+
2632
+ const validateLanes = Effect.fnUntraced(function*(
2633
+ lanes: ReadonlyArray<ThreadHostMaintenanceLane>,
2634
+ queued: ReadonlyArray<DueQueue.DueLane>,
2635
+ ) {
2636
+ const ids = new Set([
2637
+ DueQueue.Native,
2638
+ DueQueue.Publication,
2639
+ DueQueue.Projection,
2640
+ DueQueue.Messages,
2641
+ ])
2642
+
2643
+ for (const lane of lanes) {
2644
+ yield* Schema.decodeEffect(DueQueue.LaneId)(lane.id).pipe(
2645
+ Effect.mapError(alarmFailure('maintenance lane ID')),
2646
+ )
2647
+ if (ids.has(lane.id)) {
2648
+ return yield* DurableAlarmError.make({
2649
+ operation: 'maintenance lane ID',
2650
+ message: `Duplicate maintenance lane: ${lane.id}`,
2651
+ })
2652
+ }
2653
+ ids.add(lane.id)
2654
+ }
2655
+ for (const row of queued) {
2656
+ if (row.dueAt !== null && !ids.has(row.id)) {
2657
+ return yield* DurableAlarmError.make({
2658
+ operation: 'maintenance lane ID',
2659
+ message: `No handler registered for scheduled lane: ${row.id}`,
2660
+ })
2661
+ }
2662
+ }
2663
+ })
2664
+
2665
+ const dispatch = Effect.fnUntraced(function*(
2666
+ yieldAfter: DateTime.Utc,
2667
+ dispatchUntil: DateTime.Utc,
2668
+ observed: MaintenanceObservation,
2669
+ admission?: Pick<SubmissionWorkItem, 'threadId' | 'submissionId'>,
2670
+ ) {
2671
+ const leanSelection = framework.singleThreadRuntime === runtime &&
2672
+ publication === emptyPublication &&
2673
+ host.lanes.length === 0 &&
2674
+ framework.lanes.length === 0
2675
+
2676
+ // Subscribe before the first snapshot. Durable enrollment recovers eviction;
2677
+ // producer completion and wake hints make work visible during this incarnation.
2678
+ // Native source mutations already notify the revision waiter below. A replacement
2679
+ // or shared runtime keeps the generic wake stream; hints confer no authority.
2680
+ const notified = leanSelection
2681
+ ? Effect.never
2682
+ : (yield* Stream.toPull(wakes.wakes)).pipe(
2683
+ Effect.asVoid,
2684
+ Effect.catch(() => Effect.never),
2685
+ )
2686
+
2687
+ // A wake may observe temporary backoff while this event's recovery is still running.
2688
+ // Its completion must retain the original actionable observation for acknowledgement.
2689
+ const started = yield* beginNative(observed)
2690
+
2691
+ yield* mutations.withSnapshot(() =>
2692
+ Effect.gen(function*() {
2693
+ const queued = yield* queueSnapshot
2694
+ const producing = yield* mutations.activeLanes
2695
+
2696
+ for (const row of queued) {
2697
+ observed.queue.set(row.id, row)
2698
+ if (!producing.has(row.id)) observed.available.set(row.id, row.revision)
2699
+ }
2700
+ })
2701
+ )
2702
+
2703
+ // This scope owns every admitted finite wave, including native advancement.
2704
+ // Close it before final alarm rearming, including on failure or event interruption.
2705
+ const auxiliaryScope = yield* Effect.acquireRelease(
2706
+ Scope.make('parallel'),
2707
+ (scope, exit) => Scope.close(scope, exit),
2708
+ )
2709
+
2710
+ const fork = <A, E>(work: Effect.Effect<A, E>) => Effect.forkIn(work, auxiliaryScope)
2711
+
2712
+ // Each lane has at most one finite wave. A completion is retained until the single
2713
+ // scheduling loop observes it; a busy sibling cannot consume another lane's hint.
2714
+ const lanes = [recoveryEventLane, ...framework.lanes, ...host.lanes].map((lane) => ({
2715
+ ...lane,
2716
+ exhausted: false,
2717
+ fiber: undefined as Fiber.Fiber<Option.Option<number>, DurableAlarmError> | undefined,
2718
+ }))
2719
+
2720
+ let messageExhausted = false
2721
+ let delivery: Fiber.Fiber<void, DurableAlarmError> | undefined
2722
+ let failure: Cause.Cause<MaintenancePassFailure> | undefined
2723
+
2724
+ const recovery: NativeRecovery = {
2725
+ queue: yield* Deferred.make<ReadonlyArray<ThreadId>>(),
2726
+ pending: new Set(),
2727
+ loaded: new Set(),
2728
+ reports: new Map(),
2729
+ faults: new Map(),
2730
+ recipients: new Map(),
2731
+ started: false,
2732
+ needsCheckpoint: false,
2733
+ recovered: 0,
2734
+ repaired: false,
2735
+ discoveryPending: false,
2736
+ }
2737
+
2738
+ let recoveryFiber: Fiber.Fiber<void, MaintenancePassFailure> | undefined
2739
+ let backfill: Fiber.Fiber<void, DurableAlarmError | ThreadProjectionError> | undefined
2740
+
2741
+ const dispatch: NativeDispatch = {
2742
+ scope: auxiliaryScope,
2743
+ active: new Map(),
2744
+ deferred: new Set(),
2745
+ dispatched: 0,
2746
+ settled: 0,
2747
+ progressed: false,
2748
+ needsCheckpoint: false,
2749
+ }
2750
+
2751
+ // Selection is bounded local work, not an independently owned wave. It opens
2752
+ // actual Attempt scopes, then returns; empty lanes create no fibers.
2753
+ let native: Fiber.Fiber<NativePassResult, MaintenancePassFailure> | undefined
2754
+ let result: NativePassResult
2755
+ let backlog: ReadonlyArray<ThreadId> | undefined
2756
+
2757
+ if (leanSelection && admission !== undefined && started._tag === 'Actionable') {
2758
+ // Admission already identified the work. Its exact FIFO claim and owner generation
2759
+ // remain authoritative; the normal loop discovers and acknowledges everything after it.
2760
+ dispatch.dispatched++
2761
+ dispatch.active.set(
2762
+ admission.threadId,
2763
+ yield* fork(attemptSelected(admission, [], yieldAfter, recovery, true)),
2764
+ )
2765
+ result = {
2766
+ phase: 'actionable',
2767
+ nonterminal: started.nonterminal,
2768
+ nextAttemptAt: undefined,
2769
+ dispatched: true,
2770
+ }
2771
+ } else if (leanSelection) {
2772
+ result = yield* advance(started, yieldAfter, observed, recovery, dispatch)
2773
+ recovery.started = true
2774
+ yield* Deferred.succeed(recovery.queue, [])
2775
+ backlog = yield* Deferred.await(recovery.queue)
2776
+ } else {
2777
+ // Required publication and arbitrary host lanes keep independent opportunities
2778
+ // while selection is suspended in an application callback.
2779
+ native = yield* fork(advance(started, yieldAfter, observed, recovery, dispatch))
2780
+ result = {
2781
+ phase: 'caught-up',
2782
+ nonterminal: started.nonterminal,
2783
+ nextAttemptAt: undefined,
2784
+ }
2785
+ }
2786
+
2787
+ if (backlog === undefined || backlog.length > 0) {
2788
+ recoveryFiber = yield* fork(
2789
+ Effect.gen(function*() {
2790
+ for (const threadId of backlog ?? (yield* Deferred.await(recovery.queue))) {
2791
+ yield* failpoint.hit('maintenance:select:before')
2792
+ yield* runTransaction('select old recovery lane', () =>
2793
+ dueQueue.transaction(async (transaction) => {
2794
+ const { state } = await readMaintenanceState(transaction)
2795
+
2796
+ await transaction.put(
2797
+ MAINTENANCE_STATE_KEY,
2798
+ encodeMaintenanceState(
2799
+ ThreadMaintenanceState.make({
2800
+ ...state,
2801
+ lastRecoveredThreadId: threadId,
2802
+ }),
2803
+ ),
2804
+ )
2805
+ }))
2806
+ yield* failpoint.hit('maintenance:select:after')
2807
+ yield* recoverThread(threadId, recovery)
2808
+ recovery.pending.delete(threadId)
2809
+ if (!recovery.faults.has(threadId)) yield* wakes.notify(threadId)
2810
+ }
2811
+ }),
2812
+ )
2813
+ }
2814
+ const projectionRow = (yield* queueSnapshot).find((row) => row.id === DueQueue.Projection)
2815
+
2816
+ if (
2817
+ projectionRow !== undefined &&
2818
+ projectionRow.dueAt !== null &&
2819
+ projectionRow.dueAt <= (yield* Clock.currentTimeMillis) &&
2820
+ !(yield* mutations.activeLanes).has(DueQueue.Projection)
2821
+ ) {
2822
+ backfill = yield* fork(
2823
+ runQueued(
2824
+ projectionRow,
2825
+ projection.drain.pipe(Effect.andThen(projection.pendingDeadline)),
2826
+ observed,
2827
+ ).pipe(Effect.timeoutOption(config.projectionDispatchTimeoutMillis), Effect.asVoid),
2828
+ )
2829
+ }
2830
+
2831
+ let phase = result.phase
2832
+
2833
+ let nativeCheck = result.dispatched === true && dispatch.active.size < nativeDispatchConcurrency()
2834
+
2835
+ observed.nativeOnly = dispatch.active.size > 0
2836
+ const until = DateTime.toEpochMillis(yieldAfter)
2837
+ const dispatchEnd = DateTime.toEpochMillis(dispatchUntil)
2838
+
2839
+ while (true) {
2840
+ if (native?.pollUnsafe() !== undefined) {
2841
+ result = yield* Fiber.join(native)
2842
+ native = undefined
2843
+ if (result.phase === 'actionable') phase = 'actionable'
2844
+ observed.nativeOnly = dispatch.active.size > 0
2845
+ if (result.dispatched === true && dispatch.active.size < nativeDispatchConcurrency()) {
2846
+ dispatch.scanGeneration = undefined
2847
+ nativeCheck = true
2848
+ }
2849
+ // An empty initial scan still opens exactly one old-recovery opportunity.
2850
+ recovery.started = true
2851
+ yield* Deferred.succeed(recovery.queue, [])
2852
+ }
2853
+ for (const [threadId, attempt] of dispatch.active) {
2854
+ const exit = attempt.pollUnsafe()
2855
+
2856
+ if (exit === undefined) continue
2857
+ dispatch.active.delete(threadId)
2858
+ dispatch.scanGeneration = undefined
2859
+ if (Exit.isFailure(exit)) return yield* Effect.failCause(exit.cause)
2860
+ dispatch.settled += exit.value
2861
+ dispatch.progressed ||= exit.value > 0
2862
+ dispatch.needsCheckpoint = true
2863
+ if (exit.value === 0) dispatch.deferred.add(threadId)
2864
+ nativeCheck = true
2865
+ }
2866
+ if (recoveryFiber?.pollUnsafe() !== undefined) {
2867
+ yield* Fiber.join(recoveryFiber)
2868
+ recoveryFiber = undefined
2869
+ dispatch.scanGeneration = undefined
2870
+ nativeCheck ||= recovery.needsCheckpoint
2871
+ }
2872
+ const backfillExit = backfill?.pollUnsafe()
2873
+
2874
+ if (backfillExit !== undefined) {
2875
+ backfill = undefined
2876
+ if (Exit.isFailure(backfillExit)) failure ??= backfillExit.cause
2877
+ }
2878
+ for (const lane of lanes) {
2879
+ const exit = lane.fiber?.pollUnsafe()
2880
+
2881
+ if (exit === undefined) continue
2882
+ lane.fiber = undefined
2883
+ if (Exit.isFailure(exit)) {
2884
+ failure ??= exit.cause
2885
+ lane.exhausted = true
2886
+ }
2887
+ }
2888
+ const deliveryExit = delivery?.pollUnsafe()
2889
+
2890
+ if (deliveryExit !== undefined) {
2891
+ delivery = undefined
2892
+ if (Exit.isFailure(deliveryExit)) {
2893
+ failure ??= deliveryExit.cause
2894
+ messageExhausted = true
2895
+ }
2896
+ }
2897
+
2898
+ // A failed auxiliary lane is exhausted for this event. Its error must not
2899
+ // retire healthy admission, delivery or native work that still has an allowance.
2900
+ const now = yield* Clock.currentTimeMillis
2901
+
2902
+ if (now >= until) break
2903
+
2904
+ const queueRevision = yield* mutations.revision
2905
+ const queued = yield* queueSnapshot
2906
+ const producing = yield* mutations.activeLanes
2907
+
2908
+ yield* validateLanes(lanes, queued)
2909
+ for (const lane of lanes) {
2910
+ if (
2911
+ lane.phase === 'after-native' ||
2912
+ lane.fiber !== undefined ||
2913
+ lane.exhausted ||
2914
+ producing.has(lane.id)
2915
+ ) {
2916
+ continue
2917
+ }
2918
+ const row = queued.find((row) => row.id === lane.id)
2919
+
2920
+ if (row === undefined || row.dueAt === null || row.dueAt > now) continue
2921
+ const dueAt = row.dueAt
2922
+
2923
+ lane.fiber = yield* fork(
2924
+ Effect.gen(function*() {
2925
+ yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(
2926
+ lane.dispatchTimeoutMillis,
2927
+ ).pipe(Effect.mapError(alarmFailure('host dispatch allowance')))
2928
+ const selectedAt = yield* Clock.currentTimeMillis
2929
+
2930
+ if (selectedAt >= until || selectedAt + lane.dispatchTimeoutMillis > dispatchEnd) {
2931
+ lane.exhausted = true
2932
+
2933
+ return Option.some(dueAt)
2934
+ }
2935
+
2936
+ return yield* runQueued(row, lane.run.pipe(Effect.scoped), observed).pipe(
2937
+ Effect.timeoutOrElse({
2938
+ duration: lane.dispatchTimeoutMillis,
2939
+ orElse: () =>
2940
+ DurableAlarmError.make({
2941
+ operation: 'host dispatch allowance',
2942
+ message: 'The admitted host wave exceeded its allowance; durable work remains pending',
2943
+ }),
2944
+ }),
2945
+ )
2946
+ }),
2947
+ )
2948
+ }
2949
+ if (delivery === undefined && !messageExhausted && !producing.has(DueQueue.Messages)) {
2950
+ // Selection is bounded local work. Fork only an actual due wave, so an empty
2951
+ // deadline check cannot extend retirement or consume another scheduling turn.
2952
+ const row = queued.find((row) => row.id === DueQueue.Messages)
2953
+
2954
+ if (row !== undefined && row.dueAt !== null && row.dueAt <= now) {
2955
+ // Selection can fail too, so charge its attempt before preparing the wave.
2956
+ delivery = yield* fork(
2957
+ runQueued(
2958
+ row,
2959
+ Effect.gen(function*() {
2960
+ const wave = yield* messages.prepare
2961
+ const selectedAt = yield* Clock.currentTimeMillis
2962
+
2963
+ if (selectedAt >= until || selectedAt + wave.timeoutMillis > dispatchEnd) {
2964
+ messageExhausted = true
2965
+
2966
+ return Option.fromNullishOr(row.dueAt)
2967
+ }
2968
+
2969
+ // No second timeout: the driver owes the Claim's timeout/retry commit.
2970
+ return yield* wave.run
2971
+ }),
2972
+ observed,
2973
+ ).pipe(Effect.asVoid),
2974
+ )
2975
+ }
2976
+ }
2977
+
2978
+ // Retire a quiet event before consuming hints queued during its native Attempt.
2979
+ // Recovery still gets its checkpoint and, if needed, initial dispatch opportunity.
2980
+ if (
2981
+ native === undefined &&
2982
+ dispatch.active.size === 0 &&
2983
+ recoveryFiber === undefined &&
2984
+ !recovery.needsCheckpoint &&
2985
+ backfill === undefined &&
2986
+ delivery === undefined &&
2987
+ lanes.every((lane) => lane.fiber === undefined)
2988
+ ) {
2989
+ break
2990
+ }
2991
+
2992
+ if (
2993
+ native === undefined &&
2994
+ nativeCheck &&
2995
+ dispatch.active.size < nativeDispatchConcurrency()
2996
+ ) {
2997
+ nativeCheck = false
2998
+ const nativeCheckpoint = dispatch.needsCheckpoint && dispatch.active.size === 0
2999
+
3000
+ const checkpoint = (recoveryFiber === undefined && recovery.needsCheckpoint) || nativeCheckpoint
3001
+
3002
+ if (checkpoint) recovery.needsCheckpoint = false
3003
+ // Keep this opportunity's reservations across beginNative's storage awaits.
3004
+ // A finishing Attempt cannot turn a refill into another same-Thread Attempt.
3005
+ const reserved = new Set(dispatch.active.keys())
3006
+
3007
+ native = yield* fork(
3008
+ Effect.gen(function*() {
3009
+ const awakened = checkpoint ? started : yield* beginNative(observed)
3010
+
3011
+ return yield* advance(
3012
+ awakened,
3013
+ yieldAfter,
3014
+ observed,
3015
+ recovery,
3016
+ dispatch,
3017
+ !nativeCheckpoint && (!checkpoint || dispatch.settled === 0),
3018
+ reserved,
3019
+ )
3020
+ }),
3021
+ )
3022
+ }
3023
+
3024
+ const next = Math.min(
3025
+ native === undefined ? (result.nextAttemptAt ?? Infinity) : Infinity,
3026
+ ...queued.flatMap((row) =>
3027
+ row.id !== DueQueue.Native && row.dueAt !== null && row.dueAt > now
3028
+ ? [row.dueAt]
3029
+ : []
3030
+ ),
3031
+ until,
3032
+ )
3033
+
3034
+ const completing = [
3035
+ native,
3036
+ ...dispatch.active.values(),
3037
+ recoveryFiber,
3038
+ backfill,
3039
+ delivery,
3040
+ ...lanes.map((lane) => lane.fiber),
3041
+ ].filter((fiber) => fiber !== undefined)
3042
+
3043
+ const changed = awaitAnyCompletion(completing, queueRevision)
3044
+
3045
+ // An occupied native-only slot cannot admit another Attempt. With no auxiliary
3046
+ // wake before yield, the timer would only switch to joining that same Attempt.
3047
+ // Incoming work still wakes this callback; all new waves recheck the deadline.
3048
+ const joiningNative = leanSelection &&
3049
+ native === undefined &&
3050
+ dispatch.active.size === 1 &&
3051
+ completing.length === 1 &&
3052
+ !queued.some(
3053
+ (row) =>
3054
+ row.id !== DueQueue.Native &&
3055
+ row.dueAt !== null &&
3056
+ row.dueAt > now &&
3057
+ row.dueAt < until,
3058
+ )
3059
+
3060
+ const ready = yield* joiningNative
3061
+ ? changed
3062
+ : Effect.raceAllFirst([
3063
+ changed,
3064
+ ...(leanSelection ? [] : [notified.pipe(Effect.as('scan' as const))]),
3065
+ Effect.sleep(Math.max(0, next - now)).pipe(Effect.as('scan' as const)),
3066
+ ])
3067
+
3068
+ if (ready === 'scan') {
3069
+ nativeCheck = true
3070
+ }
3071
+ }
3072
+ // Dispatch is closed. Join each admitted wave without renewing its allowance.
3073
+ // Message Claims retain their driver's own timer and local retry commit.
3074
+ if (native !== undefined) {
3075
+ result = yield* Fiber.join(native)
3076
+ if (result.phase === 'actionable') phase = 'actionable'
3077
+ observed.nativeOnly = dispatch.active.size > 0
3078
+ recovery.started = true
3079
+ yield* Deferred.succeed(recovery.queue, [])
3080
+ }
3081
+ for (const attempt of dispatch.active.values()) {
3082
+ const settled = yield* Fiber.join(attempt)
3083
+
3084
+ dispatch.settled += settled
3085
+ dispatch.progressed ||= settled > 0
3086
+ }
3087
+ dispatch.active.clear()
3088
+ observed.nativeOnly = false
3089
+ for (
3090
+ const fiber of [
3091
+ recoveryFiber,
3092
+ backfill,
3093
+ delivery,
3094
+ ...lanes.map((lane) => lane.fiber),
3095
+ ]
3096
+ ) {
3097
+ if (fiber === undefined) continue
3098
+ // Await exits without failing fast: every admitted wave owns its original
3099
+ // bounded allowance and cleanup even if another wave has already failed.
3100
+ const exit = yield* Fiber.await<unknown, MaintenancePassFailure>(fiber)
3101
+
3102
+ if (Exit.isFailure(exit)) failure ??= exit.cause
3103
+ }
3104
+ if (failure !== undefined) return yield* Effect.failCause(failure)
3105
+ if (recovery.needsCheckpoint || dispatch.dispatched > 0) {
3106
+ result = yield* advance(started, yieldAfter, observed, recovery, dispatch, false)
3107
+ if (result.phase === 'actionable') phase = 'actionable'
3108
+ }
3109
+ yield* Scope.close(auxiliaryScope, Exit.void)
3110
+
3111
+ return { result, phase, recovered: recovery.recovered, settled: dispatch.settled }
3112
+ })
3113
+
3114
+ const pass = Effect.fnUntraced(function*(
3115
+ yieldAfter: DateTime.Utc,
3116
+ dispatchUntil: DateTime.Utc,
3117
+ observed: MaintenanceObservation,
3118
+ admission?: Pick<SubmissionWorkItem, 'threadId' | 'submissionId'>,
3119
+ ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure, Scope.Scope> {
3120
+ const concurrent = yield* Effect.exit(
3121
+ Effect.scoped(dispatch(yieldAfter, dispatchUntil, observed, admission)).pipe(
3122
+ Effect.provideService(ThreadMutationGate, mutations),
3123
+ ),
3124
+ )
3125
+
3126
+ // Closing the concurrent scope first releases every native Attempt and its resources.
3127
+ // Select fresh revisions: finalizers may have retained the last host obligation.
3128
+ const afterNative = yield* Effect.gen(function*() {
3129
+ const lanes = [recoveryEventLane, ...framework.lanes, ...host.lanes]
3130
+ const selected = lanes.filter((lane) => lane.phase === 'after-native')
3131
+
3132
+ if (selected.length === 0) return []
3133
+ const queued = yield* queueSnapshot
3134
+ const producing = yield* mutations.activeLanes
3135
+
3136
+ // Finished native work may have produced new source facts. They are already
3137
+ // present at this phase boundary; only arrivals during the host wave preempt it.
3138
+ for (const row of queued) {
3139
+ if (!producing.has(row.id)) observed.available.set(row.id, row.revision)
3140
+ }
3141
+ const dispatchEnd = DateTime.toEpochMillis(dispatchUntil)
3142
+ const afterNativeIds = new Set(selected.map((lane) => lane.id))
3143
+ const completed: Array<Exit.Exit<void, DurableAlarmError>> = []
3144
+ let yielded = false
3145
+
3146
+ // Subscribe by revision before reading the queue, so an enrollment racing the
3147
+ // snapshot cannot be lost. Only producer notifications rescan scheduling state;
3148
+ // there is no timer or application deadline read. New arrivals renew no budget.
3149
+ const yieldToConcurrent = Effect.gen(function*() {
3150
+ while (true) {
3151
+ const revision = yield* mutations.revision
3152
+ const now = yield* Clock.currentTimeMillis
3153
+
3154
+ const current = yield* queueSnapshot
3155
+ const active = yield* mutations.activeLanes
3156
+
3157
+ if (
3158
+ current.some(
3159
+ (row) =>
3160
+ !afterNativeIds.has(row.id) &&
3161
+ !active.has(row.id) &&
3162
+ row.dueAt !== null &&
3163
+ row.dueAt <= now &&
3164
+ row.revision !== observed.available.get(row.id),
3165
+ )
3166
+ ) {
3167
+ yielded = true
3168
+
3169
+ return completed
3170
+ }
3171
+ yield* mutations.awaitChange(revision)
3172
+ }
3173
+ })
3174
+
3175
+ yield* validateLanes(lanes, queued)
3176
+
3177
+ const cursor = yield* mutations.withSnapshot(() =>
3178
+ runTransaction('read post-native dispatch cursor', () =>
3179
+ dueQueue.transaction(
3180
+ async (transaction) => (await readMaintenanceState(transaction)).state.lastAfterNativeLaneId,
3181
+ ))
3182
+ )
3183
+
3184
+ const ordered = selected.toSorted((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0)
3185
+
3186
+ const after = cursor === undefined ? 0 : ordered.findIndex((lane) => lane.id > cursor)
3187
+
3188
+ const rotated = after <= 0 ? ordered : [...ordered.slice(after), ...ordered.slice(0, after)]
3189
+
3190
+ const waves = Effect.forEach(
3191
+ rotated,
3192
+ (lane) =>
3193
+ Effect.gen(function*() {
3194
+ const row = queued.find((row) => row.id === lane.id)
3195
+ const now = yield* Clock.currentTimeMillis
3196
+
3197
+ if (
3198
+ row === undefined ||
3199
+ row.dueAt === null ||
3200
+ row.dueAt > now ||
3201
+ producing.has(lane.id)
3202
+ ) {
3203
+ return
3204
+ }
3205
+ yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(
3206
+ lane.dispatchTimeoutMillis,
3207
+ ).pipe(Effect.mapError(alarmFailure('host dispatch allowance')))
3208
+ if (now + lane.dispatchTimeoutMillis > dispatchEnd) return
3209
+
3210
+ // Persist admission, not completion: slow or failing early lanes must not
3211
+ // monopolize the next event's remaining allowance. Domain receipts stay local
3212
+ // to the lane and its due-queue revision still fences acknowledgement.
3213
+ const admit = mutations.withSnapshot(() =>
3214
+ runTransaction('advance post-native dispatch cursor', () =>
3215
+ dueQueue.transaction(async (transaction) => {
3216
+ const { state } = await readMaintenanceState(transaction)
3217
+
3218
+ await transaction.put(
3219
+ MAINTENANCE_STATE_KEY,
3220
+ encodeMaintenanceState(
3221
+ ThreadMaintenanceState.make({ ...state, lastAfterNativeLaneId: lane.id }),
3222
+ ),
3223
+ )
3224
+ }))
3225
+ )
3226
+
3227
+ yield* runQueued(
3228
+ row,
3229
+ admit.pipe(Effect.andThen(lane.run.pipe(Effect.scoped))),
3230
+ observed,
3231
+ () =>
3232
+ yielded,
3233
+ ).pipe(
3234
+ Effect.timeoutOrElse({
3235
+ duration: lane.dispatchTimeoutMillis,
3236
+ orElse: () =>
3237
+ DurableAlarmError.make({
3238
+ operation: 'host dispatch allowance',
3239
+ message: 'The admitted host wave exceeded its allowance; durable work remains pending',
3240
+ }),
3241
+ }),
3242
+ )
3243
+ }).pipe(
3244
+ Effect.exit,
3245
+ Effect.tap((exit) =>
3246
+ Effect.sync(() => {
3247
+ if (!yielded || Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) {
3248
+ completed.push(exit)
3249
+ }
3250
+ })
3251
+ ),
3252
+ ),
3253
+ { concurrency: afterNativeDispatchConcurrency },
3254
+ ).pipe(Effect.as(completed))
3255
+
3256
+ // raceFirst waits for interrupted wave scopes to close before the alarm can
3257
+ // retire and admit native work in its next event. Finished receipts stay finished.
3258
+ return yield* Effect.raceFirst(waves, yieldToConcurrent)
3259
+ }).pipe(Effect.exit)
3260
+
3261
+ let failure = Exit.isFailure(concurrent) ? concurrent.cause : Cause.empty
3262
+
3263
+ if (Exit.isFailure(afterNative)) failure = Cause.combine(failure, afterNative.cause)
3264
+ else {
3265
+ for (const exit of afterNative.value) {
3266
+ if (Exit.isFailure(exit)) failure = Cause.combine(failure, exit.cause)
3267
+ }
3268
+ }
3269
+ if (Exit.isFailure(concurrent) || failure.reasons.length > 0) {
3270
+ return yield* Effect.failCause(failure)
3271
+ }
3272
+ const { result, phase, recovered, settled } = concurrent.value
3273
+
3274
+ yield* failpoint.hit('maintenance:finish:before')
3275
+
3276
+ const disposition = yield* mutations.withSnapshot((active) =>
3277
+ Effect.gen(function*() {
3278
+ const now = yield* Clock.currentTimeMillis
3279
+
3280
+ return yield* runAlarmTransaction(
3281
+ 'finish maintenance event',
3282
+ async (transaction, checkpoint) => {
3283
+ const { state } = await readMaintenanceState(transaction)
3284
+
3285
+ const native = active > 0 || state.dirty > state.processed
3286
+ ? state.retry?.generation === state.dirty && active === 0
3287
+ ? Math.max(now + minimumAlarmDelay, state.retry.notBefore)
3288
+ : state.dirty === observed.generation && active === 0
3289
+ ? (result.nextAttemptAt ?? now + minimumAlarmDelay)
3290
+ : now + minimumAlarmDelay
3291
+ : Infinity
3292
+
3293
+ dueQueue.checkpointNative(Number.isFinite(native) ? native : null)
3294
+ const next = DueQueue.next(dueQueue.read())
3295
+
3296
+ if (Number.isFinite(next)) {
3297
+ checkpoint.at(Math.max(now + minimumAlarmDelay, next))
3298
+
3299
+ return 'rearmed' as const
3300
+ }
3301
+ // A productive event retains one recovery opportunity for nearby ingress.
3302
+ // Its later empty delivery has no charged work and removes the checkpoint.
3303
+ if (config.recoveryWindowMillis > 0 && observed.charged.size > 0) {
3304
+ checkpoint.at(now + config.recoveryWindowMillis)
3305
+
3306
+ return 'rearmed' as const
3307
+ }
3308
+ checkpoint.cancel()
3309
+
3310
+ return 'cleared' as const
3311
+ },
3312
+ )
3313
+ })
3314
+ )
3315
+
3316
+ yield* failpoint.hit('maintenance:finish:after')
3317
+
3318
+ const report = MaintenancePassReport.make({
3319
+ phase,
3320
+ recovered,
3321
+ settled,
3322
+ nonterminal: result.nonterminal,
3323
+ alarm: disposition,
3324
+ })
3325
+
3326
+ yield* Effect.annotateCurrentSpan({
3327
+ phase: report.phase,
3328
+ recovered: report.recovered,
3329
+ settled: report.settled,
3330
+ nonterminal: report.nonterminal,
3331
+ alarm: report.alarm,
3332
+ })
3333
+
3334
+ return report
3335
+ })
3336
+
3337
+ // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.
3338
+ const runPass = Effect.fnUntraced(
3339
+ function*(admission: Pick<SubmissionWorkItem, 'threadId' | 'submissionId'> | undefined) {
3340
+ const now = yield* Clock.currentTimeMillis
3341
+ const yieldAfter = DateTime.makeUnsafe(now + 10 * 60_000)
3342
+ const dispatchUntil = DateTime.makeUnsafe(now + 14 * 60_000)
3343
+
3344
+ const observed: MaintenanceObservation = {
3345
+ nativeOnly: false,
3346
+ queue: new Map(),
3347
+ charged: new Map(),
3348
+ available: new Map(),
3349
+ }
3350
+
3351
+ return yield* alarms
3352
+ .deferWakes(
3353
+ maintenancePassGate.withPermit(
3354
+ dueQueue
3355
+ .withView(Effect.scoped(pass(yieldAfter, dispatchUntil, observed, admission)))
3356
+ .pipe(
3357
+ // Close event-owned auxiliary work and release Attempt ownership before
3358
+ // failure rearming, while still holding the pass permit.
3359
+ Effect.onErrorIf(
3360
+ () => true,
3361
+ () => rearmFailure(observed),
3362
+ ),
3363
+ ),
3364
+ ),
3365
+ )
3366
+ .pipe(
3367
+ hints.withHintsDeferred,
3368
+ Effect.catchTags({
3369
+ StorageOperationError: (error) => alarmFailure('defer maintenance wakes')(error),
3370
+ InvalidScheduleConfigurationError: (error) => alarmFailure('defer maintenance wakes')(error),
3371
+ }),
3372
+ )
3373
+ },
3374
+ // Include permit waiting, recovery and acknowledgement in the event deadline.
3375
+ // Interruption releases Attempt ownership, leaving the prearmed dirty generation
3376
+ // for recovery. It never changes the logical Run duration or settles a policy failure.
3377
+ // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.
3378
+ Effect.timeoutOrElse({
3379
+ duration: '14 minutes',
3380
+ orElse: () =>
3381
+ DurableAlarmError.make({
3382
+ operation: 'maintenance pass deadline',
3383
+ message: 'The maintenance event exceeded its 14 minute deadline; durable recovery remains pending',
3384
+ }),
3385
+ }),
3386
+ Effect.ensuring(reportParked),
3387
+ )
3388
+
3389
+ return ThreadMaintenance.of({
3390
+ pass: runPass(undefined),
3391
+ start: (admission) => execution.waitUntil(runPass(admission)),
3392
+ ensureAlarm: mutations
3393
+ .withSnapshot(() => ensureAlarm())
3394
+ .pipe(Effect.tap(() => reportParked)),
3395
+ withMutation: (body) =>
3396
+ mutations.withMutation(
3397
+ body.pipe(Effect.tap(() => publishCommitted.pipe(Effect.provide(publicationContext)))),
3398
+ ),
3399
+ })
3400
+ }),
3401
+ )
3402
+ }