@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0-beta.192

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
@@ -0,0 +1,1931 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
+ import { CurrentNativeSource } from "@systemfsoftware/agent-storage-cloudflare/port-routing";
3
+ import "@systemfsoftware/agent/agent-registration";
4
+ import { DurableAgentRuntime, DurableRuntimeConfig, RecoveryBlocked, RecoveryFailure, RecoverySweepResult, isolateRecovery } from "@systemfsoftware/agent/durable-agent-runtime";
5
+ import { SubmissionId, ThreadId } from "@systemfsoftware/agent/identifiers";
6
+ import { AbortIntentRequest, SubmissionLedger } from "@systemfsoftware/agent/submission-ledger";
7
+ import { ThreadProjectionMaintenance } from "@systemfsoftware/agent/thread-projection-maintenance";
8
+ import { WakeScheduler } from "@systemfsoftware/agent/wake-scheduler";
9
+ import { DurableObjectAlarm, DurableObjectState, DurableObjectStorage } from "effect-cf";
10
+ import * as Cause from "effect/Cause";
11
+ import * as Clock from "effect/Clock";
12
+ import * as Context from "effect/Context";
13
+ import * as SecureRandom from "effect/crypto/SecureRandom";
14
+ import * as DateTime from "effect/DateTime";
15
+ import * as Deferred from "effect/Deferred";
16
+ import * as Effect from "effect/Effect";
17
+ import * as ErrorReporter from "effect/ErrorReporter";
18
+ import * as Exit from "effect/Exit";
19
+ import * as Fiber from "effect/Fiber";
20
+ import * as Layer from "effect/Layer";
21
+ import * as Option from "effect/Option";
22
+ import * as Random from "effect/Random";
23
+ import * as Ref from "effect/Ref";
24
+ import * as Result from "effect/Result";
25
+ import * as Scheduler from "effect/Scheduler";
26
+ import * as Schema from "effect/Schema";
27
+ import * as Scope from "effect/Scope";
28
+ import * as Semaphore from "effect/Semaphore";
29
+ import * as SqlClient from "effect/sql/SqlClient";
30
+ import * as SqlError from "effect/sql/SqlError";
31
+ import * as Stream from "effect/Stream";
32
+ import * as Struct from "effect/Struct";
33
+ import { i as DurableObjectContext, r as DurableAlarmError, s as ThreadObjectPlacement } from "./CloudflareBindings-Dylkir84.mjs";
34
+ import { n as AuxiliaryDispatchMillis, s as CloudflareDurableRuntimeConfig } from "./CloudflareConfig-rBlbPSIZ.mjs";
35
+ import { r as safeCauseMessage } from "./boundary-YrOnE2zO.mjs";
36
+ // src/internal/due-queue.ts
37
+ const LaneId = Schema.NonEmptyString.check(Schema.isMaxLength(256));
38
+ const HostLaneId = LaneId.check(Schema.isPattern(/^(?!effect-agent:)/, { message: "The effect-agent: namespace is reserved for framework maintenance lanes" }));
39
+ const Deadline = Schema.NullOr(Schema.Finite);
40
+ const MinimumRetryMillis = 1e3;
41
+ const ParkedRetryMillis = 36e5;
42
+ /** Scheduling metadata only. Domain outboxes, claims and receipts remain authoritative. */
43
+ var DueLane = class extends Schema.Class("CloudflareDueLane")({
44
+ id: LaneId,
45
+ revision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
46
+ dueAt: Deadline,
47
+ stalls: Schema.Int.check(Schema.isBetween({
48
+ minimum: 0,
49
+ maximum: 30
50
+ })),
51
+ progressKey: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(512))),
52
+ notBefore: Schema.Finite,
53
+ state: Schema.Literals([
54
+ "idle",
55
+ "pending",
56
+ "parked"
57
+ ]),
58
+ reported: Schema.Literals([0, 1])
59
+ }) {};
60
+ const Native = "effect-agent:native";
61
+ const Publication = "effect-agent:publication";
62
+ const Projection = "effect-agent:projection";
63
+ const Messages = "effect-agent:messages";
64
+ const RecoveryEvents = "effect-agent:recovery-events";
65
+ const Lifecycle = "effect-agent:lifecycle";
66
+ const decode = Schema.decodeUnknownSync(Schema.Array(DueLane));
67
+ const equivalent = Schema.toEquivalence(DueLane);
68
+ const views = /* @__PURE__ */ new WeakMap();
69
+ /** Only the explicit source boundary may retain speculative rows across operations. */
70
+ const buffering = (storage) => views.get(storage)?.frame !== void 0;
71
+ const ownsTransaction = (storage, depth) => views.get(storage)?.frame?.sqlDepth === depth;
72
+ const invalidate = (storage) => {
73
+ const view = views.get(storage);
74
+ if (view !== void 0) view.rows = void 0;
75
+ };
76
+ /** Callers reserve the shared SQL connection through commit. Keep the complete view
77
+ * during a transaction, then retain at most 128 lanes between transactions. Intent
78
+ * flushes before source commit; claims and prearming commit before fallible work. */
79
+ const make = (storage) => {
80
+ const sql = storage.sql;
81
+ let view = views.get(storage);
82
+ if (view === void 0) {
83
+ view = {
84
+ rows: void 0,
85
+ frame: void 0,
86
+ retained: 0,
87
+ changes: /* @__PURE__ */ new Map(),
88
+ deadlines: /* @__PURE__ */ new Map()
89
+ };
90
+ views.set(storage, view);
91
+ }
92
+ const current = view;
93
+ const trim = () => {
94
+ if (current.frame === void 0 && current.retained === 0 && (current.rows?.length ?? 0) > 128) current.rows = void 0;
95
+ };
96
+ /** Retain the pass's write-through view without deferring claims or source commits.
97
+ * Failed source transactions still invalidate it; large views are released at exit. */
98
+ const withView = (body) => Effect.acquireUseRelease(Effect.sync(() => {
99
+ current.retained++;
100
+ }), () => body, () => Effect.sync(() => {
101
+ current.retained--;
102
+ trim();
103
+ }));
104
+ const begin = (sqlDepth) => {
105
+ const frame = {
106
+ parent: current.frame,
107
+ sqlDepth,
108
+ rows: current.rows,
109
+ changes: current.changes,
110
+ deadlines: current.deadlines
111
+ };
112
+ current.frame = frame;
113
+ current.changes = new Map(current.changes);
114
+ current.deadlines = new Map(current.deadlines);
115
+ return frame;
116
+ };
117
+ const finish = (frame, success) => {
118
+ current.frame = frame.parent;
119
+ if (!success) {
120
+ current.rows = frame.parent === void 0 ? void 0 : frame.rows;
121
+ current.changes = frame.changes;
122
+ current.deadlines = frame.deadlines;
123
+ }
124
+ if (frame.parent === void 0) {
125
+ current.changes.clear();
126
+ current.deadlines.clear();
127
+ trim();
128
+ }
129
+ };
130
+ const write = (changes) => {
131
+ if (sql.exec(`WITH changes (id, revision, dueAt, stalls, progressKey, notBefore, state, reported, expected_revision) AS (
132
+ VALUES ${changes.map(() => "(?, ?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
133
+ ) INSERT INTO platform_cloudflare_due_queue
134
+ (id, revision, dueAt, stalls, progressKey, notBefore, state, reported)
135
+ SELECT id, revision, dueAt, stalls, progressKey, notBefore, state, reported FROM changes WHERE 1
136
+ ON CONFLICT(id) DO UPDATE SET revision = excluded.revision, dueAt = excluded.dueAt,
137
+ stalls = excluded.stalls, progressKey = excluded.progressKey,
138
+ notBefore = excluded.notBefore, state = excluded.state, reported = excluded.reported
139
+ WHERE platform_cloudflare_due_queue.revision = (
140
+ SELECT expected_revision FROM changes WHERE changes.id = excluded.id
141
+ ) RETURNING 1`, ...changes.flatMap(({ before, after }) => [
142
+ after.id,
143
+ after.revision,
144
+ after.dueAt,
145
+ after.stalls,
146
+ after.progressKey,
147
+ after.notBefore,
148
+ after.state,
149
+ after.reported,
150
+ before?.revision ?? -1
151
+ ])).toArray().length !== changes.length) throw new Error("Maintenance due revision changed during transaction");
152
+ };
153
+ const flush = (frame) => {
154
+ if (frame.parent !== void 0) return;
155
+ const changes = [...current.changes.values()].filter(({ before, after }) => before === void 0 || !equivalent(before, after));
156
+ for (let offset = 0; offset < changes.length; offset += 11) write(changes.slice(offset, offset + 11));
157
+ };
158
+ const transaction = async (body) => {
159
+ let frame;
160
+ try {
161
+ const result = await storage.transaction(async (transaction) => {
162
+ frame = begin();
163
+ const result = await body(transaction);
164
+ flush(frame);
165
+ return result;
166
+ });
167
+ if (frame !== void 0) finish(frame, true);
168
+ return result;
169
+ } catch (cause) {
170
+ if (frame !== void 0) finish(frame, false);
171
+ throw cause;
172
+ }
173
+ };
174
+ const initialize = () => {
175
+ sql.exec(`CREATE TABLE IF NOT EXISTS platform_cloudflare_due_queue (
176
+ id TEXT PRIMARY KEY, revision INTEGER NOT NULL, dueAt REAL, stalls INTEGER NOT NULL,
177
+ progressKey TEXT, notBefore REAL NOT NULL DEFAULT 0, state TEXT NOT NULL DEFAULT 'pending',
178
+ reported INTEGER NOT NULL DEFAULT 0
179
+ )`);
180
+ const columns = new Set(sql.exec("PRAGMA table_info(platform_cloudflare_due_queue)").toArray().map((row) => row.name));
181
+ if (!columns.has("reported")) sql.exec("ALTER TABLE platform_cloudflare_due_queue ADD COLUMN reported INTEGER NOT NULL DEFAULT 0");
182
+ if (!columns.has("progressKey")) sql.exec("ALTER TABLE platform_cloudflare_due_queue ADD COLUMN progressKey TEXT");
183
+ if (!columns.has("notBefore")) sql.exec("ALTER TABLE platform_cloudflare_due_queue ADD COLUMN notBefore REAL NOT NULL DEFAULT 0");
184
+ if (!columns.has("state")) {
185
+ sql.exec("ALTER TABLE platform_cloudflare_due_queue ADD COLUMN state TEXT NOT NULL DEFAULT 'pending'");
186
+ sql.exec("UPDATE platform_cloudflare_due_queue SET state = 'idle' WHERE dueAt IS NULL");
187
+ }
188
+ };
189
+ /** Keep dormant rows so delete/reinsert cannot reuse a revision held by an older wave. */
190
+ const read = () => {
191
+ if (current.rows !== void 0) return current.rows;
192
+ const rows = decode(sql.exec("SELECT id, revision, dueAt, stalls, progressKey, notBefore, state, reported FROM platform_cloudflare_due_queue").toArray());
193
+ if (current.frame !== void 0 || current.retained > 0 || rows.length <= 128) current.rows = rows;
194
+ return rows;
195
+ };
196
+ const set = (after) => {
197
+ const rows = read();
198
+ const before = rows.find((row) => row.id === after.id);
199
+ if (before !== void 0 && equivalent(before, after)) return before;
200
+ const previous = current.changes.get(after.id);
201
+ const change = {
202
+ before: previous === void 0 ? before : previous.before,
203
+ after
204
+ };
205
+ if (current.frame === void 0) write([change]);
206
+ else current.changes.set(after.id, change);
207
+ current.rows = [...rows.filter((row) => row.id !== after.id), after];
208
+ trim();
209
+ return after;
210
+ };
211
+ const dirty = (id, dueAt, progress = false, progressKey) => {
212
+ Schema.decodeSync(LaneId)(id);
213
+ Schema.decodeSync(Schema.Finite)(dueAt);
214
+ const row = read().find((row) => row.id === id);
215
+ const earliest = Math.min(current.deadlines.get(id) ?? dueAt, dueAt);
216
+ if (current.frame !== void 0) current.deadlines.set(id, earliest);
217
+ return set(DueLane.make({
218
+ id,
219
+ revision: row === void 0 ? 1 : row.revision + Number(progress),
220
+ dueAt: row === void 0 || progress ? earliest : Math.max(row.notBefore, Math.min(row.dueAt ?? 1e400, earliest)),
221
+ state: progress || (row?.stalls ?? 0) < 8 ? "pending" : row?.state ?? "pending",
222
+ stalls: progress ? 0 : row?.stalls ?? 0,
223
+ notBefore: progress ? 0 : row?.notBefore ?? 0,
224
+ reported: progress ? 0 : row?.reported ?? 0,
225
+ progressKey: progressKey ?? row?.progressKey ?? null
226
+ }));
227
+ };
228
+ /** Native checkpoints fence the generation, not each source commit. Once progress
229
+ * resets a claimed lane, further native commits owe the same recovery opportunity.
230
+ * A new claim, deadline, or retry budget makes the next commit advance it again. */
231
+ const progressNative = (dueAt) => {
232
+ const row = read().find((row) => row.id === Native);
233
+ if (row?.state === "pending" && row.dueAt !== null && row.dueAt <= dueAt && row.stalls === 0 && row.notBefore === 0 && row.reported === 0) return;
234
+ dirty(Native, dueAt, true);
235
+ };
236
+ /** A strictly increasing source cursor; old or repeated notices cannot renew a budget. */
237
+ const progress = (id, dueAt, cursor) => {
238
+ Schema.decodeSync(Schema.BigInt.check(Schema.isGreaterThanOrEqualToBigInt(0n)))(cursor);
239
+ const previous = read().find((row) => row.id === id)?.progressKey;
240
+ if (previous !== void 0 && previous !== null && cursor <= BigInt(previous)) return false;
241
+ dirty(id, dueAt, true, String(cursor));
242
+ return true;
243
+ };
244
+ /** One initial native discovery wave; host lanes always require explicit enrollment. */
245
+ const register = (id) => {
246
+ if (read().some((row) => row.id === id)) return;
247
+ set(DueLane.make({
248
+ id,
249
+ revision: 0,
250
+ dueAt: 0,
251
+ stalls: 0,
252
+ progressKey: null,
253
+ notBefore: 0,
254
+ state: "pending",
255
+ reported: 0
256
+ }));
257
+ };
258
+ /** This transaction must commit before fallible work: never defer a debit across a wave. */
259
+ const claim = (lane, nowMillis, native = false) => {
260
+ const row = read().find((row) => row.id === lane.id);
261
+ if (row === void 0 || row.revision !== lane.revision || row.dueAt === null || !(row.dueAt <= nowMillis || native && row.notBefore <= nowMillis)) return;
262
+ const stalls = Math.min(row.stalls + 1, 8);
263
+ const notBefore = nowMillis + (stalls >= 8 ? ParkedRetryMillis : Math.min(6e4, MinimumRetryMillis * 2 ** row.stalls));
264
+ return set(DueLane.make({
265
+ ...row,
266
+ stalls,
267
+ notBefore,
268
+ dueAt: notBefore,
269
+ state: stalls >= 8 ? "parked" : "pending"
270
+ }));
271
+ };
272
+ const complete = (lane, dueAt) => {
273
+ Schema.decodeSync(Deadline)(dueAt);
274
+ const row = read().find((row) => row.id === lane.id);
275
+ if (row === void 0 || row.revision !== lane.revision) return;
276
+ const after = DueLane.make({
277
+ ...row,
278
+ dueAt: dueAt === null ? null : Math.max(dueAt, row.notBefore),
279
+ state: dueAt === null ? "idle" : row.stalls >= 8 ? "parked" : "pending",
280
+ stalls: dueAt === null ? 0 : row.stalls,
281
+ notBefore: dueAt === null ? 0 : row.notBefore,
282
+ reported: dueAt === null ? 0 : row.reported
283
+ });
284
+ return set(DueLane.make({
285
+ ...after,
286
+ revision: row.revision + 1
287
+ }));
288
+ };
289
+ /** Native checkpoints already fence their own dirty/processed generation. */
290
+ const checkpointNative = (dueAt) => {
291
+ Schema.decodeSync(Deadline)(dueAt);
292
+ const rows = read();
293
+ const row = rows.find((row) => row.id === Native);
294
+ if (row === void 0) return;
295
+ const publication = rows.find((row) => row.id === Publication);
296
+ set(DueLane.make({
297
+ ...row,
298
+ dueAt: dueAt === null || publication?.state === "parked" ? null : Math.max(dueAt, row.notBefore),
299
+ state: dueAt === null ? "idle" : row.stalls >= 8 ? "parked" : "pending",
300
+ stalls: dueAt === null ? 0 : row.stalls,
301
+ notBefore: dueAt === null ? 0 : row.notBefore,
302
+ reported: dueAt === null ? 0 : row.reported
303
+ }));
304
+ };
305
+ const takeParkedReports = () => read().filter((row) => row.state === "parked" && row.reported === 0).map((row) => set(DueLane.make({
306
+ ...row,
307
+ reported: 1
308
+ })));
309
+ return {
310
+ initialize,
311
+ withView,
312
+ begin,
313
+ flush,
314
+ finish,
315
+ transaction,
316
+ read,
317
+ dirty,
318
+ progressNative,
319
+ progress,
320
+ register,
321
+ claim,
322
+ complete,
323
+ checkpointNative,
324
+ takeParkedReports
325
+ };
326
+ };
327
+ const next = (rows) => rows.reduce((next, row) => Math.min(next, row.dueAt ?? 1e400), 1e400);
328
+ // src/Alarm.ts
329
+ var Alarm_exports = /* @__PURE__ */ __exportAll({
330
+ DurableAlarmError: () => DurableAlarmError,
331
+ DurableAlarmService: () => DurableAlarmService,
332
+ MaintenancePassReport: () => MaintenancePassReport,
333
+ ThreadHostMaintenance: () => ThreadHostMaintenance,
334
+ ThreadMaintenance: () => ThreadMaintenance,
335
+ ThreadMaintenanceAlarm: () => ThreadMaintenanceAlarm,
336
+ ThreadMaintenanceFailpoint: () => ThreadMaintenanceFailpoint,
337
+ ThreadMessageDelivery: () => ThreadMessageDelivery,
338
+ ThreadMutationGate: () => ThreadMutationGate,
339
+ ThreadNativeMaintenance: () => ThreadNativeMaintenance,
340
+ ThreadPublication: () => ThreadPublication,
341
+ ThreadRecoveryEvents: () => ThreadRecoveryEvents,
342
+ ThreadRecoveryFaultEvent: () => ThreadRecoveryFaultEvent,
343
+ publishCommitted: () => publishCommitted
344
+ });
345
+ /** Content-free operational notice: pending work now retries at the hourly ceiling. */
346
+ var MaintenanceRetryParked = class extends Schema.TaggedError()("MaintenanceRetryParked", {
347
+ lane: Schema.String,
348
+ retryAfterMillis: Schema.Finite
349
+ }) {};
350
+ const alarmFailure = (operation) => (cause) => DurableAlarmError.make({
351
+ operation,
352
+ message: safeCauseMessage(cause, "The Cloudflare alarm API failed without a diagnostic"),
353
+ cause
354
+ });
355
+ const makeStorageEffect = Effect.gen(function* () {
356
+ const sql = yield* SqlClient.SqlClient;
357
+ const { ctx } = yield* DurableObjectContext;
358
+ const invalidate$1 = Effect.sync(() => invalidate(ctx.storage));
359
+ return (operation, execute) => Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {
360
+ const body = Effect.uninterruptible(execute);
361
+ if (current._tag === "Some") {
362
+ if (buffering(ctx.storage)) return body;
363
+ return body.pipe(Effect.ensuring(invalidate$1));
364
+ }
365
+ return Effect.scoped(Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body.pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? invalidate$1 : Effect.void))));
366
+ });
367
+ });
368
+ const makeStorageOperation = Effect.map(makeStorageEffect, (run) => (operation, execute) => run(operation, Effect.tryPromise({
369
+ try: execute,
370
+ catch: alarmFailure(operation)
371
+ })));
372
+ /** One manual alarm for the entire consumer-owned maintenance queue. */
373
+ var ThreadMaintenanceAlarm = class extends DurableObjectAlarm.Tag()("@systemfsoftware/agent/thread-maintenance", { "@systemfsoftware/agent/thread-maintenance": {
374
+ payload: Schema.Null,
375
+ lifecycle: "manual"
376
+ } }) {};
377
+ const maintenanceAlarmRef = {
378
+ tag: "@systemfsoftware/agent/thread-maintenance",
379
+ id: "queue"
380
+ };
381
+ const maintenanceAlarmInput = (deadline) => ({
382
+ ...maintenanceAlarmRef,
383
+ payload: null,
384
+ runAt: DateTime.makeUnsafe(deadline)
385
+ });
386
+ /** Named maintenance checkpoint; the library owns the shared native alarm slot. */
387
+ var DurableAlarmService = class DurableAlarmService extends Context.Service()("@effect-agent/platform-cloudflare/DurableAlarmService") {
388
+ static layer = Layer.effect(DurableAlarmService)(Effect.gen(function* () {
389
+ const alarms = yield* ThreadMaintenanceAlarm;
390
+ const random = yield* SecureRandom.SecureRandom;
391
+ const { ctx } = yield* DurableObjectContext;
392
+ const run = yield* makeStorageEffect;
393
+ const inlineWork = yield* Ref.make(0);
394
+ const wrap = (operation, effect) => run(operation, effect.pipe(Effect.provideService(SecureRandom.SecureRandom, random), Effect.mapError(alarmFailure(operation))));
395
+ return DurableAlarmService.of({
396
+ scheduled: wrap("read maintenance checkpoint", alarms.getAlarmStatus(maintenanceAlarmRef)).pipe(Effect.map((at) => at === void 0 ? Option.none() : Option.some(DateTime.toEpochMillis(at.runAt)))),
397
+ scheduleAt: (at) => wrap("replace maintenance checkpoint", alarms.scheduleAlarm(maintenanceAlarmInput(at))),
398
+ ensureScheduledBy: (at) => wrap("advance maintenance checkpoint", alarms.scheduleAlarmEarlier(maintenanceAlarmInput(at))),
399
+ scheduleNow: Ref.get(inlineWork).pipe(Effect.flatMap((active) => active > 0 ? Effect.void : wrap("hint maintenance checkpoint", Effect.gen(function* () {
400
+ const now = yield* Clock.currentTimeMillis;
401
+ const next$5 = next(make(ctx.storage).read());
402
+ if (!Number.isFinite(next$5)) return;
403
+ const at = Math.max(now, next$5);
404
+ const scheduled = yield* alarms.getAlarmStatus(maintenanceAlarmRef);
405
+ if (scheduled !== void 0 && DateTime.toEpochMillis(scheduled.runAt) <= at) return;
406
+ yield* alarms.scheduleAlarmEarlier(maintenanceAlarmInput(at));
407
+ })))),
408
+ withHintsDeferred: (body) => Effect.acquireUseRelease(Ref.update(inlineWork, (active) => active + 1), () => body, () => Ref.update(inlineWork, (active) => active - 1)),
409
+ cancel: wrap("cancel maintenance checkpoint", alarms.cancelAlarm(maintenanceAlarmRef))
410
+ });
411
+ }));
412
+ };
413
+ const CurrentCheckpoint = Context.Reference("@systemfsoftware/agent/cloudflare/CurrentCheckpoint", { defaultValue: () => void 0 });
414
+ /** One source transaction owns queue intent and the library checkpoint through commit. */
415
+ const makeAlarmOperation = Effect.gen(function* () {
416
+ const alarms = yield* ThreadMaintenanceAlarm;
417
+ const random = yield* SecureRandom.SecureRandom;
418
+ const sql = yield* SqlClient.SqlClient;
419
+ const { ctx } = yield* DurableObjectContext;
420
+ const queue = make(ctx.storage);
421
+ const transaction = (body) => alarms.transaction((mutations) => Effect.withFiber((owner) => {
422
+ let active = true;
423
+ return Effect.onExitPrimitive(body(owner).pipe(Effect.provideService(CurrentCheckpoint, {
424
+ mutations,
425
+ isActive: (fiber) => active && fiber === owner
426
+ })), () => {
427
+ active = false;
428
+ });
429
+ }), { sqlClient: sql }).pipe(Effect.mapError((cause) => cause instanceof DurableObjectStorage.StorageOperationError ? SqlError.SqlError.make({ reason: SqlError.UnknownError.make({
430
+ operation: "commit maintenance checkpoint",
431
+ message: "Source facts and maintenance checkpoint could not commit",
432
+ cause
433
+ }) }) : cause));
434
+ const withTransaction = (body) => Effect.withFiber((fiber) => {
435
+ const ambient = Context.getOption(fiber.context, sql.transactionService);
436
+ if (ambient._tag === "Some" && !ownsTransaction(ctx.storage, ambient.value[1])) return Effect.fail(SqlError.SqlError.make({ reason: SqlError.UnknownError.make({
437
+ operation: "begin maintenance source transaction",
438
+ message: "Use ThreadMutationGate.withTransaction at the outermost source transaction",
439
+ cause: "Unwrapped SQL transaction cannot own buffered maintenance intent"
440
+ }) }));
441
+ let frame;
442
+ return Effect.uninterruptibleMask((restore) => Effect.onExitPrimitive(transaction((owner) => {
443
+ const current = Context.getOption(owner.context, sql.transactionService);
444
+ if (current._tag === "None") return SqlError.SqlError.make({ reason: SqlError.UnknownError.make({
445
+ operation: "begin maintenance source transaction",
446
+ message: "SQL transaction unavailable",
447
+ cause: "SQL transaction unavailable"
448
+ }) });
449
+ const started = queue.begin(current.value[1]);
450
+ frame = started;
451
+ return Effect.flatMap(restore(body), (value) => Effect.try({
452
+ try: () => {
453
+ queue.flush(started);
454
+ return value;
455
+ },
456
+ catch: (cause) => SqlError.SqlError.make({ reason: SqlError.UnknownError.make({
457
+ cause,
458
+ operation: "flush maintenance due queue",
459
+ message: "Maintenance intent could not commit"
460
+ }) })
461
+ }));
462
+ }), (exit) => {
463
+ if (frame !== void 0) queue.finish(frame, Exit.isSuccess(exit));
464
+ }).pipe(Effect.provideService(Scheduler.PreventSchedulerYield, true)));
465
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql));
466
+ const run = (operation, execute) => {
467
+ const commit = Effect.withFiber((fiber) => {
468
+ const tx = fiber.getRef(CurrentCheckpoint);
469
+ if (tx === void 0) return Effect.die(DurableAlarmError.make({
470
+ operation: "checkpoint",
471
+ message: "Maintenance checkpoint transaction unavailable"
472
+ }));
473
+ if (!tx.isActive(fiber)) return Effect.fail(DurableAlarmError.make({
474
+ operation: "enroll maintenance source",
475
+ message: "Source intent requires its active transaction callback's fiber"
476
+ }));
477
+ let checkpoint = Effect.void;
478
+ const intent = {
479
+ at: (at) => {
480
+ checkpoint = tx.mutations.scheduleAlarm(maintenanceAlarmInput(at));
481
+ },
482
+ earlier: (at) => {
483
+ checkpoint = tx.mutations.scheduleAlarmEarlier(maintenanceAlarmInput(at));
484
+ },
485
+ cancel: () => {
486
+ checkpoint = tx.mutations.cancelAlarm(maintenanceAlarmRef);
487
+ }
488
+ };
489
+ return Effect.tryPromise({
490
+ try: () => execute(ctx.storage, intent),
491
+ catch: alarmFailure(operation)
492
+ }).pipe(Effect.tap(() => checkpoint.pipe(Effect.provideService(SecureRandom.SecureRandom, random))));
493
+ });
494
+ return Effect.withFiber((fiber) => {
495
+ if (fiber.getRef(CurrentCheckpoint) !== void 0) return commit;
496
+ return Context.getOption(fiber.context, sql.transactionService)._tag === "Some" && !buffering(ctx.storage) ? transaction(() => commit).pipe(Effect.ensuring(Effect.sync(() => invalidate(ctx.storage)))) : withTransaction(commit);
497
+ }).pipe(Effect.uninterruptible, Effect.mapError(alarmFailure(operation)));
498
+ };
499
+ return {
500
+ run,
501
+ withTransaction
502
+ };
503
+ });
504
+ var MaintenancePassReport = class extends Schema.Class("@effect-agent/platform-cloudflare/MaintenancePassReport")({
505
+ /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
506
+ phase: Schema.Literals(["caught-up", "actionable"]),
507
+ /** Recovery decisions and Thread faults observed during this event. */
508
+ recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
509
+ /** Head Attempts settled during the event. Joined input may settle with each head. */
510
+ settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
511
+ /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
512
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
513
+ /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */
514
+ alarm: Schema.Literals(["rearmed", "cleared"])
515
+ }) {};
516
+ /** Test-only fault authority; production uses the inert layer. */
517
+ var ThreadMaintenanceFailpoint = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint") {
518
+ static layer = Layer.succeed(this)({ hit: () => Effect.void });
519
+ };
520
+ const emptyPublication = {
521
+ invalidate: Effect.void,
522
+ prepareGeneration: () => Effect.void,
523
+ drain: Effect.succeedNone
524
+ };
525
+ /** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
526
+ var ThreadPublication = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadPublication") {
527
+ static layer = Layer.succeed(this)(emptyPublication);
528
+ };
529
+ const requiresPublication = Effect.map(Effect.serviceOption(ThreadPublication), (service) => Option.isNone(service) || service.value !== emptyPublication);
530
+ /**
531
+ * Host-assembled native message recovery. Preparation is a bounded local selection; the
532
+ * driver bounds each actual Claim and persists its timeout/retry before `run` returns.
533
+ * The alarm must not add a timer starting at selection: Claim setup and retry commits belong
534
+ * to the driver. The prepared allowance decides only whether a wave fits this event.
535
+ */
536
+ const ThreadMessageDelivery = Context.Reference("@effect-agent/platform-cloudflare/ThreadMessageDelivery", { defaultValue: () => ({ prepare: Effect.succeed({
537
+ timeoutMillis: 1,
538
+ run: Effect.succeedNone
539
+ }) }) });
540
+ /** Independent lanes share the existing alarm; compose hosts by concatenating their lanes. */
541
+ const ThreadHostMaintenance = Context.Reference("@effect-agent/platform-cloudflare/ThreadHostMaintenance", { defaultValue: () => ({ lanes: [] }) });
542
+ /** @internal Framework handlers are separate from host registrations and their namespace. */
543
+ const ThreadNativeMaintenance = Context.Reference("@effect-agent/platform-cloudflare/ThreadNativeMaintenance", { defaultValue: () => ({ lanes: [] }) });
544
+ /** @internal Required host publication only; native lifecycle facts use a maintenance lane. */
545
+ const publishCommitted = Effect.gen(function* () {
546
+ const publication = yield* ThreadPublication;
547
+ yield* publication.invalidate;
548
+ yield* publication.drain;
549
+ }).pipe(Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.logError("Thread publication deferred after source commit", cause)));
550
+ const MaintenanceGeneration = Schema.BigIntFromString.check(Schema.isGreaterThanOrEqualToBigInt(0n));
551
+ /** A committed recovery transition for one affected Submission; never a Settlement. */
552
+ var ThreadRecoveryFaultEvent = class extends Schema.Class("@effect-agent/platform-cloudflare/ThreadRecoveryFaultEvent")({
553
+ schemaVersion: Schema.Literal(1),
554
+ /** Monotonic within the physical Object; retained unchanged on delivery retries. */
555
+ sequence: MaintenanceGeneration,
556
+ transition: Schema.Literals([
557
+ "created",
558
+ "changed",
559
+ "cleared"
560
+ ]),
561
+ threadId: ThreadId,
562
+ submissionId: SubmissionId,
563
+ occurredAt: Schema.Finite,
564
+ firstFailedAt: Schema.Finite,
565
+ /** The current failure, or the last failure for a cleared event. */
566
+ failure: RecoveryFailure
567
+ }) {};
568
+ const recoveryEventKey = (sequence) => `effect-agent:thread-recovery-event:v1:${sequence}`;
569
+ const encodeRecoveryEvent = Schema.encodeSync(ThreadRecoveryFaultEvent);
570
+ const decodeRecoveryEvent = Schema.decodeUnknownSync(ThreadRecoveryFaultEvent);
571
+ /**
572
+ * Ordered, at-least-once delivery through the existing host maintenance lane. Return only
573
+ * after durably applying the event or retaining it in a host outbox. Deduplicate by physical
574
+ * Object and sequence; callbacks may repeat after interruption. This is a trusted host hook,
575
+ * not pre-authorized UI data: the host owns recipient authorization and safe presentation.
576
+ * Capture services in the Layer. Do not call producers or write the raw alarm slot.
577
+ * Without this service, maintenance acknowledges and discards transitions. Install the
578
+ * handler before the first maintenance pass if the application needs that event stream.
579
+ */
580
+ var ThreadRecoveryEvents = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadRecoveryEvents") {};
581
+ var BindingWait = class extends Schema.Class("BindingWait")({
582
+ threadId: ThreadId,
583
+ submissionId: SubmissionId,
584
+ reportedAt: Schema.Finite
585
+ }) {};
586
+ /**
587
+ * A durable observation of blocked recovery, independent of the execution journal. This is
588
+ * neither a Settlement nor proof that external effects did not happen. A successful recovery
589
+ * sweep clears it; repair must preserve canonical history and the original admission identity.
590
+ */
591
+ var ThreadRecoveryFault = class extends Schema.Class("@effect-agent/platform-cloudflare/ThreadRecoveryFault")({
592
+ schemaVersion: Schema.Literal(1),
593
+ threadId: ThreadId,
594
+ firstFailedAt: Schema.Finite,
595
+ lastFailedAt: Schema.Finite,
596
+ /** Earliest automatic recovery retry; new admissions do not erase this deadline. */
597
+ retryAt: Schema.Finite,
598
+ /** Saturates at 2^31 - 1; one observation per Thread per recovery sweep. */
599
+ attempts: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(0x7fffffff)),
600
+ failure: RecoveryFailure,
601
+ /** Individually retained recipients survive settlement until their clear commits. */
602
+ recipientCount: Schema.optionalKey(Schema.Natural)
603
+ }) {};
604
+ const recoveryFaultKey = (threadId) => `effect-agent:thread-recovery-fault:v1:${threadId}`;
605
+ const decodeRecoveryFaultValue = Schema.decodeUnknownSync(ThreadRecoveryFault);
606
+ const decodeRecoveryFault = (threadId, encoded) => {
607
+ const fault = decodeRecoveryFaultValue(encoded);
608
+ if (fault.threadId !== threadId) throw new Error("Recovery status does not match its Thread key");
609
+ return fault;
610
+ };
611
+ const encodeRecoveryFault = Schema.encodeSync(ThreadRecoveryFault);
612
+ const sameRecoveryFailure = Schema.toEquivalence(RecoveryFailure);
613
+ const decodeRecoveryRecipient = Schema.decodeUnknownSync(SubmissionId);
614
+ const encodeRecoveryRecipient = Schema.encodeSync(SubmissionId);
615
+ const recoveryRecipientKey = (threadId, index) => `effect-agent:recovery-recipient:v1:${threadId.length}:${threadId}:${index}`;
616
+ const recoveryRecipientKeys = (fault, start) => Array.from({ length: Math.min(128, (fault.recipientCount ?? 0) - start) }, (_, offset) => recoveryRecipientKey(fault.threadId, start + offset));
617
+ const readRecoveryRecipients = async (storage, fault) => {
618
+ const ids = [];
619
+ for (let start = 0; start < (fault.recipientCount ?? 0); start += 128) {
620
+ const keys = recoveryRecipientKeys(fault, start);
621
+ const values = await storage.get(keys);
622
+ for (const key of keys) ids.push(decodeRecoveryRecipient(values.get(key)));
623
+ }
624
+ return ids;
625
+ };
626
+ const appendRecoveryRecipients = async (transaction, threadId, count, added) => {
627
+ for (let start = 0; start < added.length; start += 128) await transaction.put(Object.fromEntries(added.slice(start, start + 128).map((id, offset) => [recoveryRecipientKey(threadId, count + start + offset), encodeRecoveryRecipient(id)])));
628
+ };
629
+ const recoveryEvent = (fault, submissionId, transition, occurredAt) => ({
630
+ schemaVersion: 1,
631
+ transition,
632
+ threadId: fault.threadId,
633
+ submissionId,
634
+ occurredAt,
635
+ firstFailedAt: fault.firstFailedAt,
636
+ failure: fault.failure
637
+ });
638
+ /** Observe already-owned waves without creating one waiter fiber for each wave. */
639
+ const awaitAnyCompletion = Effect.fnUntraced(function* (fibers, revision) {
640
+ const mutations = yield* ThreadMutationGate;
641
+ return yield* Effect.acquireUseRelease(Effect.sync(() => []), (observers) => Effect.callback((resume) => {
642
+ observers.push(mutations.observeChange(revision, () => resume(Effect.succeed("scan"))));
643
+ for (const fiber of fibers) observers.push(fiber.addObserver(() => resume(Effect.succeed("completed"))));
644
+ }), (observers) => Effect.sync(() => observers.forEach((remove) => remove())));
645
+ });
646
+ /** Post-native delivery shares a finite connection budget across independent host lanes. */
647
+ const afterNativeDispatchConcurrency = 2;
648
+ const NativeWorkCursor = Schema.Struct({
649
+ threadId: ThreadId,
650
+ cursor: Schema.NonEmptyString.check(Schema.isMaxLength(8192))
651
+ });
652
+ const workCursorKey = (threadId) => `effect-agent:work-recovery-cursor:v1:${threadId}`;
653
+ var MaintenanceRetry = class extends Schema.Class("MaintenanceRetry")({
654
+ generation: MaintenanceGeneration,
655
+ notBefore: Schema.Finite,
656
+ nativeOnly: Schema.Boolean,
657
+ stalls: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(30))
658
+ }) {};
659
+ /** Versioned, platform-private maintenance state stored through Durable Object KV. */
660
+ var ThreadMaintenanceState = class extends Schema.Class("@effect-agent/platform-cloudflare/ThreadMaintenanceState")({
661
+ schemaVersion: Schema.Literal(1),
662
+ dirty: MaintenanceGeneration,
663
+ processed: MaintenanceGeneration,
664
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
665
+ /** One physical-owner cursor; old single-lane records need no conversion. */
666
+ lastServedThreadId: Schema.optionalKey(ThreadId),
667
+ /** Rotate old recovery independently of dispatch, including after eviction or timeout. */
668
+ lastRecoveredThreadId: Schema.optionalKey(ThreadId),
669
+ /** Rotate bounded post-native admission across full events and Object eviction. */
670
+ lastAfterNativeLaneId: Schema.optionalKey(LaneId),
671
+ bindingRegistryKey: Schema.optionalKey(Schema.String),
672
+ bindingWaits: Schema.optionalKey(Schema.Array(BindingWait)),
673
+ recoveryEventSequence: Schema.optionalKey(MaintenanceGeneration),
674
+ recoveryEventAcknowledged: Schema.optionalKey(MaintenanceGeneration),
675
+ /** Absent on older records. A newer mutation makes this retry obsolete. */
676
+ retry: Schema.optionalKey(MaintenanceRetry)
677
+ }) {};
678
+ const MAINTENANCE_STATE_KEY = "effect-agent:thread-maintenance:v1";
679
+ const decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);
680
+ const encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);
681
+ const hasRecoveryEvents = (state) => (state.recoveryEventSequence ?? 0n) > (state.recoveryEventAcknowledged ?? 0n);
682
+ const initialMaintenanceState = () => ThreadMaintenanceState.make({
683
+ schemaVersion: 1,
684
+ dirty: 1n,
685
+ processed: 0n,
686
+ nonterminal: 0
687
+ });
688
+ const readMaintenanceState = async (transaction) => {
689
+ const encoded = await transaction.get(MAINTENANCE_STATE_KEY);
690
+ return encoded === void 0 ? {
691
+ state: initialMaintenanceState(),
692
+ initialized: false
693
+ } : {
694
+ state: decodeMaintenanceState(encoded),
695
+ initialized: true
696
+ };
697
+ };
698
+ const stableExternalWait = (snapshot, reports) => {
699
+ const report = reports.get(snapshot.submissionId);
700
+ if (report?.decision._tag === "SettleAborted") return false;
701
+ switch (snapshot.state) {
702
+ case "suspended":
703
+ case "joined": return true;
704
+ case "unknown": return report?.disposition === "unknown";
705
+ case "admitted": return reports.get(snapshot.submissionId)?.decision._tag === "AwaitParentEstablishment";
706
+ case "input-applied":
707
+ case "joining":
708
+ case "ready":
709
+ case "settled": return false;
710
+ }
711
+ };
712
+ /**
713
+ * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
714
+ * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
715
+ * Layers must reuse that instance; a second gate cannot observe the native producers' activity.
716
+ */
717
+ const CurrentMutationLanes = Context.Reference("@effect-agent/platform-cloudflare/CurrentMutationLanes", { defaultValue: () => [] });
718
+ var ThreadMutationGate = class ThreadMutationGate extends Context.Service()("@effect-agent/platform-cloudflare/internal/ThreadMutationGate") {
719
+ static layer = Layer.effect(this)(Effect.gen(function* () {
720
+ const { ctx } = yield* DurableObjectContext;
721
+ const sql = yield* SqlClient.SqlClient;
722
+ const dueQueue = make(ctx.storage);
723
+ const placement = yield* Effect.serviceOption(ThreadObjectPlacement);
724
+ const singleThread = Option.isSome(placement) && placement.value.threadId !== void 0;
725
+ const config = yield* CloudflareDurableRuntimeConfig;
726
+ const failpoint = yield* ThreadMaintenanceFailpoint;
727
+ const activeMutations = yield* Ref.make(0);
728
+ const activeLanes = /* @__PURE__ */ new Map();
729
+ const generationGate = yield* Semaphore.make(1);
730
+ let revision = 0;
731
+ const listeners = /* @__PURE__ */ new Set();
732
+ const observeChange = (observed, listener) => {
733
+ if (observed !== revision) {
734
+ listener();
735
+ return () => {};
736
+ }
737
+ listeners.add(listener);
738
+ return () => {
739
+ listeners.delete(listener);
740
+ };
741
+ };
742
+ const notify = Effect.sync(() => {
743
+ revision++;
744
+ const pending = [...listeners];
745
+ listeners.clear();
746
+ for (const listener of pending) listener();
747
+ });
748
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
749
+ const recoveryDelay = config.recoveryWindowMillis || minimumAlarmDelay;
750
+ const runTransaction = yield* makeStorageOperation;
751
+ const { run: runAlarmTransaction, withTransaction } = yield* makeAlarmOperation;
752
+ const validateSourceBoundary = Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => current._tag === "Some" && buffering(ctx.storage) && !ownsTransaction(ctx.storage, current.value[1]) ? Effect.fail(DurableAlarmError.make({
753
+ operation: "enroll maintenance source",
754
+ message: "Nested source scheduling requires ThreadMutationGate.withTransaction"
755
+ })) : Effect.void);
756
+ yield* runTransaction("initialize maintenance due queue", async () => {
757
+ dueQueue.initialize();
758
+ dueQueue.register(Native);
759
+ });
760
+ const schedule = Effect.fnUntraced(function* (id, dueAt, progressCursor) {
761
+ yield* validateSourceBoundary;
762
+ const now = yield* Clock.currentTimeMillis;
763
+ const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration;
764
+ const enroll = async (transaction, checkpoint) => {
765
+ if (progressCursor === void 0) dueQueue.dirty(id, dueAt);
766
+ else if (dueQueue.progress(id, dueAt, progressCursor) && (id === "effect-agent:native" || id === "effect-agent:publication")) {
767
+ if (id === "effect-agent:publication") dueQueue.dirty(Native, dueAt, true);
768
+ const { state } = await readMaintenanceState(transaction);
769
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
770
+ ...Struct.omit(state, ["retry"]),
771
+ dirty: state.dirty + 1n
772
+ })));
773
+ }
774
+ const next$2 = next(dueQueue.read());
775
+ if (Number.isFinite(next$2)) checkpoint.earlier(Math.max(next$2, now + (scheduling.dispatchAfterEvent === true ? 0 : minimumAlarmDelay)));
776
+ };
777
+ yield* runAlarmTransaction("schedule maintenance lane", enroll);
778
+ yield* notify;
779
+ });
780
+ const beginMutation = Effect.fnUntraced(function* (invalidatesRecovery, lanes) {
781
+ yield* failpoint.hit("maintenance:dirty:before");
782
+ const now = yield* Clock.currentTimeMillis;
783
+ const nativeSource = yield* CurrentNativeSource;
784
+ const publicationRequired = yield* requiresPublication;
785
+ if (invalidatesRecovery || lanes.length > 0) yield* runAlarmTransaction("advance maintenance generation", async (transaction, checkpoint) => {
786
+ const { state, initialized } = await readMaintenanceState(transaction);
787
+ if (invalidatesRecovery) {
788
+ dueQueue.dirty(Native, now);
789
+ if (publicationRequired) dueQueue.dirty(Publication, now);
790
+ }
791
+ for (const id of lanes) dueQueue.dirty(id, now, false);
792
+ if (!initialized || invalidatesRecovery && !nativeSource) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
793
+ ...state,
794
+ dirty: state.dirty + (invalidatesRecovery && !nativeSource ? 1n : 0n)
795
+ })));
796
+ const deadline = next(dueQueue.read());
797
+ if (Number.isFinite(deadline)) checkpoint.earlier(Math.max(deadline, now + recoveryDelay));
798
+ });
799
+ yield* failpoint.hit("maintenance:dirty:after");
800
+ yield* Ref.update(activeMutations, (active) => active + 1);
801
+ const enrolled = /* @__PURE__ */ new Set([...lanes, ...invalidatesRecovery ? [Native, ...publicationRequired ? [Publication] : []] : []]);
802
+ for (const id of enrolled) activeLanes.set(id, (activeLanes.get(id) ?? 0) + 1);
803
+ return enrolled;
804
+ });
805
+ const releaseLanes = (enrolled, committed = false) => Effect.sync(() => {
806
+ for (const id of enrolled) {
807
+ if (committed && (id === "effect-agent:native" || id === "effect-agent:publication")) continue;
808
+ const remaining = (activeLanes.get(id) ?? 1) - 1;
809
+ if (remaining === 0) activeLanes.delete(id);
810
+ else activeLanes.set(id, remaining);
811
+ enrolled.delete(id);
812
+ }
813
+ });
814
+ const endMutation = (enrolled) => generationGate.withPermit(releaseLanes(enrolled).pipe(Effect.andThen(Ref.update(activeMutations, (active) => Math.max(0, active - 1)))));
815
+ const withMutation = (body, options) => Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => Option.isSome(current) ? Effect.fail(DurableAlarmError.make({
816
+ operation: "prearm maintenance mutation",
817
+ message: "Run withMutation outside the source SQL transaction so prearming commits first"
818
+ })) : Effect.acquireUseRelease(generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true, options?.lanes ?? [])), (enrolled) => failpoint.hit("maintenance:mutation:armed").pipe(Effect.andThen(Effect.flatMap(CurrentMutationLanes, (current) => body.pipe(Effect.provideService(CurrentMutationLanes, [.../* @__PURE__ */ new Set([...current, ...enrolled])])))), Effect.tap(() => releaseLanes(enrolled, true).pipe(Effect.andThen(notify))), Effect.tap(() => failpoint.hit("maintenance:mutation:finished"))), (enrolled) => endMutation(enrolled).pipe(Effect.andThen(notify))));
819
+ const recordProgress = Effect.fnUntraced(function* (lanes) {
820
+ yield* validateSourceBoundary;
821
+ if (Option.isNone(yield* Effect.serviceOption(sql.transactionService))) return yield* DurableAlarmError.make({
822
+ operation: "record source progress",
823
+ message: "Source progress requires its authoritative SQL transaction"
824
+ });
825
+ const affected = /* @__PURE__ */ new Set([...lanes, ...yield* CurrentMutationLanes]);
826
+ if (!(yield* requiresPublication)) affected.delete(Publication);
827
+ if (affected.has("effect-agent:publication")) affected.add(Native);
828
+ if (affected.size === 0) return;
829
+ const now = yield* Clock.currentTimeMillis;
830
+ const nativeSource = yield* CurrentNativeSource;
831
+ const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration;
832
+ yield* runAlarmTransaction("record maintenance producer progress", async (transaction, checkpoint) => {
833
+ for (const id of affected) if (singleThread && nativeSource && id === "effect-agent:native") dueQueue.progressNative(now);
834
+ else dueQueue.dirty(id, now, true);
835
+ if (affected.has("effect-agent:native")) {
836
+ const { state, initialized } = await readMaintenanceState(transaction);
837
+ if (!initialized || !nativeSource || state.retry !== void 0) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
838
+ ...Struct.omit(state, ["retry"]),
839
+ dirty: state.dirty + (nativeSource ? 0n : 1n)
840
+ })));
841
+ }
842
+ checkpoint.earlier(now + (scheduling.dispatchAfterEvent === true && !nativeSource ? 0 : minimumAlarmDelay));
843
+ });
844
+ if (!(singleThread && nativeSource && affected.size === 1 && affected.has("effect-agent:native"))) yield* notify;
845
+ });
846
+ return ThreadMutationGate.of({
847
+ withTransaction,
848
+ withMutation,
849
+ schedule,
850
+ recordProgress,
851
+ activeLanes: Effect.sync(() => new Set(activeLanes.keys())),
852
+ revision: Effect.sync(() => revision),
853
+ observeChange,
854
+ awaitChange: (observed) => Effect.callback((resume) => {
855
+ const remove = observeChange(observed, () => resume(Effect.void));
856
+ return Effect.sync(remove);
857
+ }),
858
+ withSnapshot: (body) => generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body))
859
+ });
860
+ }));
861
+ };
862
+ /**
863
+ * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
864
+ *
865
+ * One physical event owns native scheduling, auxiliary delivery and final alarm rearming.
866
+ *
867
+ * 1. Prearm before any work. A caught-up native step uses the O(1) generation record without
868
+ * recovery, ledger scans or canonical-history reads.
869
+ * 2. Reconcile before each head Attempt, then checkpoint only the observed generation. A racing
870
+ * producer keeps its generation dirty and immediately eligible. Quiescent native retries
871
+ * retain their durable backoff.
872
+ * 3. Admit one Attempt for a single-Thread runtime, or at most two independent Thread
873
+ * Attempts for a shared host, with one active head per Thread.
874
+ * Keep native and delivery admission open together while finite waves remain active, so
875
+ * fresh replies and abort controls can progress during unrelated cleanup. Close atomically
876
+ * at quiescence, or at the original ten-minute yield deadline, then join admitted waves.
877
+ * 4. Native message delivery retains its driver-owned Claim deadline. Host/backfill waves are
878
+ * bounded independently; incoming native work never restarts or cancels their attempts.
879
+ * Auxiliary failures are reported after the current native opportunity.
880
+ * 5. Close every event resource before the final gated deadline snapshot and alarm decision.
881
+ * The whole event retains one fourteen-minute cooperative timeout.
882
+ */
883
+ var ThreadMaintenance = class ThreadMaintenance extends Context.Service()("@effect-agent/platform-cloudflare/ThreadMaintenance") {
884
+ static layer = Layer.effect(ThreadMaintenance)(Effect.gen(function* () {
885
+ const runtime = yield* DurableAgentRuntime;
886
+ const recoveryConfig = yield* DurableRuntimeConfig;
887
+ const ledger = yield* SubmissionLedger;
888
+ const listNonterminal = ledger.listNonterminal ?? Stream.runCollect(ledger.scanNonterminal);
889
+ const wakes = yield* WakeScheduler;
890
+ const hints = yield* DurableAlarmService;
891
+ const alarms = yield* ThreadMaintenanceAlarm;
892
+ const config = yield* CloudflareDurableRuntimeConfig;
893
+ const { ctx } = yield* DurableObjectContext;
894
+ const execution = DurableObjectState.fromDurableObjectState(ctx);
895
+ const dueQueue = make(ctx.storage);
896
+ const storage = DurableObjectStorage.fromDurableObjectStorage(ctx.storage);
897
+ const runStorage = yield* makeStorageEffect;
898
+ const failpoint = yield* ThreadMaintenanceFailpoint;
899
+ const mutations = yield* ThreadMutationGate;
900
+ const publication = yield* ThreadPublication;
901
+ const publicationContext = yield* Effect.context();
902
+ const projection = yield* ThreadProjectionMaintenance;
903
+ const messages = yield* ThreadMessageDelivery;
904
+ const host = yield* ThreadHostMaintenance;
905
+ const framework = yield* ThreadNativeMaintenance;
906
+ const placement = yield* Effect.serviceOption(ThreadObjectPlacement);
907
+ const nativeThread = Option.isSome(placement) ? placement.value.threadId : void 0;
908
+ const nativeDispatchConcurrency = () => framework.singleThreadRuntime === runtime ? 1 : 2;
909
+ for (const lane of host.lanes) yield* Schema.decodeEffect(HostLaneId)(lane.id).pipe(Effect.mapError(alarmFailure("maintenance lane ID")));
910
+ const recoveryEvents = Option.getOrElse(yield* Effect.serviceOption(ThreadRecoveryEvents), () => ThreadRecoveryEvents.of({ publish: () => Effect.void }));
911
+ let recoveryEventsPending = false;
912
+ const maintenancePassGate = yield* Semaphore.make(1);
913
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
914
+ const runTransaction = yield* makeStorageOperation;
915
+ const { run: runAlarmTransaction } = yield* makeAlarmOperation;
916
+ const queueSnapshot = runTransaction("read maintenance due queue", async () => dueQueue.read());
917
+ const reportParked = Effect.gen(function* () {
918
+ if (!(yield* queueSnapshot).some((row) => row.state === "parked" && row.reported === 0)) return;
919
+ const rows = yield* runTransaction("mark parked maintenance reports", () => dueQueue.transaction(async () => dueQueue.takeParkedReports()));
920
+ for (const row of rows) {
921
+ const lane = [
922
+ "effect-agent:native",
923
+ "effect-agent:publication",
924
+ "effect-agent:projection",
925
+ "effect-agent:messages",
926
+ "effect-agent:recovery-events",
927
+ "effect-agent:lifecycle"
928
+ ].includes(row.id) ? row.id.slice(13) : "host";
929
+ yield* ErrorReporter.report(Cause.fail(MaintenanceRetryParked.make({
930
+ lane,
931
+ retryAfterMillis: ParkedRetryMillis
932
+ })));
933
+ }
934
+ }).pipe(Effect.catchCause((cause) => ErrorReporter.report(cause)));
935
+ yield* runTransaction("register native maintenance lanes", () => dueQueue.transaction(async () => {
936
+ for (const id of [
937
+ Publication,
938
+ Projection,
939
+ Messages,
940
+ ...framework.lanes.map((lane) => lane.id)
941
+ ]) dueQueue.register(id);
942
+ if (framework.lanes.some((lane) => lane.id === "effect-agent:lifecycle")) {
943
+ const start = dueQueue.read().find((row) => row.id === "effect-agent:lifecycle-start");
944
+ if (start !== void 0 && start.dueAt !== null) {
945
+ dueQueue.dirty(Lifecycle, start.dueAt);
946
+ dueQueue.complete(start, null);
947
+ }
948
+ }
949
+ }));
950
+ const runQueued = (selected, work, observed, yielded) => {
951
+ let row = selected;
952
+ let charged = false;
953
+ return Effect.gen(function* () {
954
+ const now = yield* Clock.currentTimeMillis;
955
+ const claimed = yield* runAlarmTransaction("charge maintenance attempt", async (_transaction, checkpoint) => {
956
+ const claimed = dueQueue.claim(selected, now);
957
+ const next$4 = next(dueQueue.read());
958
+ if (Number.isFinite(next$4)) checkpoint.at(Math.max(now + minimumAlarmDelay, next$4));
959
+ else checkpoint.cancel();
960
+ return claimed;
961
+ });
962
+ if (claimed === void 0) return Option.none();
963
+ row = claimed;
964
+ charged = true;
965
+ observed.charged.set(row.id, row.revision);
966
+ observed.queue.set(row.id, row);
967
+ observed.available.set(row.id, row.revision);
968
+ return yield* work;
969
+ }).pipe(Effect.onExit((exit) => {
970
+ if (!charged) return Effect.void;
971
+ if (yielded?.() === true && Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {
972
+ observed.queue.delete(row.id);
973
+ return Effect.void;
974
+ }
975
+ return mutations.withSnapshot(() => Effect.gen(function* () {
976
+ const active = (yield* mutations.activeLanes).has(row.id);
977
+ const now = yield* Clock.currentTimeMillis;
978
+ const next = Exit.isFailure(exit) ? now + backoffDelay(row.stalls, yield* Random.next) : Option.getOrNull(exit.value);
979
+ const checkpointed = yield* runTransaction("checkpoint maintenance lane", () => dueQueue.transaction(async () => {
980
+ if (active) return;
981
+ if (dueQueue.read().find((lane) => lane.id === row.id)?.revision !== row.revision) return;
982
+ return dueQueue.complete(row, next)?.revision;
983
+ }));
984
+ if (checkpointed !== void 0) observed.available.set(row.id, checkpointed);
985
+ })).pipe(Effect.interruptible);
986
+ }));
987
+ };
988
+ const appendRecoveryEvents = async (transaction, events) => {
989
+ if (events.length === 0) return;
990
+ const { state } = await readMaintenanceState(transaction);
991
+ let sequence = state.recoveryEventSequence ?? 0n;
992
+ for (const event of events) {
993
+ sequence++;
994
+ await transaction.put(recoveryEventKey(sequence), encodeRecoveryEvent(ThreadRecoveryFaultEvent.make({
995
+ ...event,
996
+ sequence
997
+ })));
998
+ }
999
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
1000
+ ...state,
1001
+ recoveryEventSequence: sequence
1002
+ })));
1003
+ dueQueue.dirty(RecoveryEvents, 0, true);
1004
+ recoveryEventsPending = true;
1005
+ };
1006
+ const recoveryEventLane = {
1007
+ id: RecoveryEvents,
1008
+ dispatchTimeoutMillis: 3e4,
1009
+ run: Effect.gen(function* () {
1010
+ if (!recoveryEventsPending) return Option.none();
1011
+ const range = yield* runTransaction("select recovery events", () => dueQueue.transaction(async (transaction) => {
1012
+ const { state } = await readMaintenanceState(transaction);
1013
+ return {
1014
+ next: (state.recoveryEventAcknowledged ?? 0n) + 1n,
1015
+ through: state.recoveryEventSequence ?? 0n
1016
+ };
1017
+ }));
1018
+ for (let sequence = range.next; sequence <= range.through; sequence++) {
1019
+ const event = yield* runTransaction("read recovery event", async () => decodeRecoveryEvent(await ctx.storage.get(recoveryEventKey(sequence))));
1020
+ if (event.sequence !== sequence) return yield* DurableAlarmError.make({
1021
+ operation: "read recovery event",
1022
+ message: "Recovery event does not match its sequence key"
1023
+ });
1024
+ yield* recoveryEvents.publish(event);
1025
+ const acknowledgedAt = yield* Clock.currentTimeMillis;
1026
+ yield* runTransaction("acknowledge recovery event", () => dueQueue.transaction(async (transaction) => {
1027
+ const { state } = await readMaintenanceState(transaction);
1028
+ const next = ThreadMaintenanceState.make({
1029
+ ...state,
1030
+ recoveryEventAcknowledged: sequence
1031
+ });
1032
+ await transaction.delete(recoveryEventKey(sequence));
1033
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
1034
+ recoveryEventsPending = hasRecoveryEvents(next);
1035
+ dueQueue.progress(RecoveryEvents, acknowledgedAt, sequence);
1036
+ const lane = dueQueue.read().find((row) => row.id === RecoveryEvents);
1037
+ if (lane !== void 0) dueQueue.complete(lane, recoveryEventsPending ? acknowledgedAt : null);
1038
+ }));
1039
+ }
1040
+ return recoveryEventsPending ? Option.some(0) : Option.none();
1041
+ })
1042
+ };
1043
+ const recordRecoveryFaults = Effect.fnUntraced(function* (result, recovery, current, selectedThread) {
1044
+ const threads = /* @__PURE__ */ new Map();
1045
+ if (selectedThread !== void 0) threads.set(selectedThread, void 0);
1046
+ for (const report of result.reports) threads.set(report.threadId, void 0);
1047
+ for (const report of result.workReports ?? []) threads.set(report.threadId, void 0);
1048
+ for (const blocked of result.blocked) threads.set(blocked.threadId, blocked.failure);
1049
+ if (threads.size === 0 || [...threads].every(([threadId, failure]) => failure === void 0 && recovery.loaded.has(threadId) && !recovery.faults.has(threadId))) return /* @__PURE__ */ new Map();
1050
+ const now = yield* Clock.currentTimeMillis;
1051
+ const submissions = current ?? (result.blocked.length === 0 ? [] : yield* listNonterminal);
1052
+ yield* failpoint.hit("maintenance:recovery-status:before");
1053
+ const retained = yield* runTransaction("record Thread recovery faults", () => dueQueue.transaction(async (transaction) => {
1054
+ const events = [];
1055
+ const newlyBlocked = [];
1056
+ const faults = /* @__PURE__ */ new Map();
1057
+ const recipients = /* @__PURE__ */ new Map();
1058
+ for (const [threadId, failure] of threads) {
1059
+ const key = recoveryFaultKey(threadId);
1060
+ const encoded = await transaction.get(key);
1061
+ const previous = encoded === void 0 ? void 0 : decodeRecoveryFault(threadId, encoded);
1062
+ const previousIds = previous === void 0 ? [] : await readRecoveryRecipients(transaction, previous);
1063
+ const known = new Set(previousIds);
1064
+ recipients.set(threadId, known);
1065
+ if (failure === void 0) {
1066
+ if (previous !== void 0) {
1067
+ await transaction.delete(key);
1068
+ for (let start = 0; start < (previous.recipientCount ?? 0); start += 128) await transaction.delete(recoveryRecipientKeys(previous, start));
1069
+ for (const id of previous.recipientCount === void 0 ? result.reports.filter((report) => report.threadId === threadId).map((report) => report.submissionId) : previousIds) events.push(recoveryEvent(previous, id, "cleared", now));
1070
+ }
1071
+ continue;
1072
+ }
1073
+ const added = submissions.filter((row) => row.threadId === threadId && !known.has(row.submissionId)).map((row) => row.submissionId);
1074
+ await appendRecoveryRecipients(transaction, threadId, previousIds.length, added);
1075
+ const fault = ThreadRecoveryFault.make({
1076
+ schemaVersion: 1,
1077
+ threadId,
1078
+ firstFailedAt: previous?.firstFailedAt ?? now,
1079
+ lastFailedAt: now,
1080
+ attempts: Math.min(0x7fffffff, (previous?.attempts ?? 0) + 1),
1081
+ retryAt: now + Math.min(6e4, 5e3 * 2 ** Math.min(30, previous?.attempts ?? 0)),
1082
+ failure,
1083
+ recipientCount: previousIds.length + added.length
1084
+ });
1085
+ await transaction.put(key, encodeRecoveryFault(fault));
1086
+ if (previous !== void 0 && !sameRecoveryFailure(previous.failure, failure)) for (const id of previousIds) events.push(recoveryEvent(fault, id, "changed", now));
1087
+ for (const id of added) {
1088
+ known.add(id);
1089
+ events.push(recoveryEvent(fault, id, "created", now));
1090
+ }
1091
+ faults.set(threadId, fault);
1092
+ if (previous === void 0) newlyBlocked.push(fault);
1093
+ }
1094
+ await appendRecoveryEvents(transaction, events);
1095
+ return {
1096
+ changed: new Set(events.map((event) => event.threadId)),
1097
+ newlyBlocked,
1098
+ faults,
1099
+ recipients
1100
+ };
1101
+ }));
1102
+ yield* failpoint.hit("maintenance:recovery-status:after");
1103
+ for (const [threadId, ids] of retained.recipients) recovery.recipients.set(threadId, ids);
1104
+ for (const threadId of retained.changed) yield* wakes.notify(threadId);
1105
+ for (const fault of retained.newlyBlocked) yield* Effect.logError("Native Thread recovery blocked; accepted work remains pending", fault.failure.reason === "defect" ? Cause.die(fault.failure) : Cause.fail(fault.failure)).pipe(Effect.annotateLogs({ threadId: fault.threadId }));
1106
+ return retained.faults;
1107
+ });
1108
+ const recoverThread = Effect.fnUntraced(function* (threadId, recovery) {
1109
+ const retained = yield* runTransaction("read work recovery cursor", async () => {
1110
+ const value = await ctx.storage.get(workCursorKey(threadId));
1111
+ return value === void 0 ? void 0 : Schema.decodeUnknownSync(NativeWorkCursor)(value);
1112
+ });
1113
+ if (retained !== void 0 && retained.threadId !== threadId) return yield* DurableAlarmError.make({
1114
+ operation: "read work recovery cursor",
1115
+ message: "Work cursor belongs to another Thread"
1116
+ });
1117
+ let cursor = retained?.cursor;
1118
+ do {
1119
+ const result = yield* runtime.runRecovery({
1120
+ threadId,
1121
+ deferUnclaimedAdmissions: true,
1122
+ ...cursor === void 0 ? {} : { cursor }
1123
+ }).pipe(Effect.provideService(CurrentNativeSource, true));
1124
+ const faults = yield* recordRecoveryFaults(result, recovery, void 0, threadId);
1125
+ if (cursor !== void 0 || result.cursor !== void 0) yield* runTransaction("checkpoint work recovery cursor", async () => {
1126
+ if (result.cursor === void 0) await ctx.storage.delete(workCursorKey(threadId));
1127
+ else await ctx.storage.put(workCursorKey(threadId), Schema.encodeSync(NativeWorkCursor)({
1128
+ threadId,
1129
+ cursor: result.cursor
1130
+ }));
1131
+ });
1132
+ for (const report of result.reports) recovery.reports.set(report.submissionId, report);
1133
+ recovery.faults.delete(threadId);
1134
+ for (const [id, fault] of faults) recovery.faults.set(id, fault);
1135
+ recovery.recovered += (result.workReports?.length ?? result.reports.length) + result.blocked.length;
1136
+ recovery.repaired ||= (result.workReports ?? result.reports).some((report) => report.disposition === "repaired");
1137
+ for (const report of result.workReports ?? []) if (report.retryAtMillis !== void 0) recovery.retryAtMillis = Math.min(recovery.retryAtMillis ?? 1e400, report.retryAtMillis);
1138
+ cursor = result.blocked.length > 0 ? void 0 : result.cursor;
1139
+ } while (cursor !== void 0);
1140
+ });
1141
+ const readCurrentMaintenanceState = async (transaction) => {
1142
+ const current = await readMaintenanceState(transaction);
1143
+ if (current.state.bindingRegistryKey === runtime.bindingRegistryKey) return current;
1144
+ const state = ThreadMaintenanceState.make({
1145
+ ...Struct.omit(current.state, ["retry"]),
1146
+ bindingRegistryKey: runtime.bindingRegistryKey,
1147
+ bindingWaits: [],
1148
+ dirty: current.state.dirty + 1n
1149
+ });
1150
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
1151
+ dueQueue.dirty(Native, 0, true);
1152
+ return {
1153
+ state,
1154
+ initialized: true
1155
+ };
1156
+ };
1157
+ const ensureAlarm = Effect.fnUntraced(function* () {
1158
+ yield* failpoint.hit("maintenance:ensure:before");
1159
+ const now = yield* Clock.currentTimeMillis;
1160
+ yield* runAlarmTransaction("ensure maintenance alarm", async (transaction, checkpoint) => {
1161
+ const { state, initialized } = await readCurrentMaintenanceState(transaction);
1162
+ recoveryEventsPending = hasRecoveryEvents(state);
1163
+ const rows = dueQueue.read();
1164
+ if (recoveryEventsPending && !rows.some((row) => row.id === "effect-agent:recovery-events")) dueQueue.dirty(RecoveryEvents, now);
1165
+ if (!initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
1166
+ const native = state.dirty > state.processed ? state.retry?.generation === state.dirty ? state.retry.notBefore : rows.find((row) => row.id === "effect-agent:native")?.dueAt ?? now + minimumAlarmDelay : null;
1167
+ dueQueue.checkpointNative(native);
1168
+ const next$1 = next(dueQueue.read());
1169
+ if (Number.isFinite(next$1)) checkpoint.earlier(Math.max(now + minimumAlarmDelay, next$1));
1170
+ });
1171
+ yield* failpoint.hit("maintenance:ensure:after");
1172
+ });
1173
+ const beginPass = Effect.fnUntraced(function* (observed) {
1174
+ yield* failpoint.hit("maintenance:begin:before");
1175
+ const now = yield* Clock.currentTimeMillis;
1176
+ const result = yield* runAlarmTransaction("begin maintenance pass", async (transaction, checkpoint) => {
1177
+ const { state, initialized } = await readCurrentMaintenanceState(transaction);
1178
+ recoveryEventsPending = hasRecoveryEvents(state);
1179
+ observed.generation = state.dirty;
1180
+ if (!initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
1181
+ const retryAt = state.retry?.generation === state.dirty ? state.retry.notBefore : 0;
1182
+ const rows = dueQueue.read();
1183
+ const native = rows.find((row) => row.id === Native);
1184
+ const publication = rows.find((row) => row.id === Publication);
1185
+ if (state.processed >= state.dirty || retryAt > now || native === void 0 || native.dueAt === null || native.notBefore > now || publication?.state === "parked") return {
1186
+ _tag: "CaughtUp",
1187
+ nonterminal: state.nonterminal
1188
+ };
1189
+ const charged = observed.charged.get("effect-agent:native") === native.revision ? native : dueQueue.claim(native, now, true);
1190
+ if (charged === void 0) return {
1191
+ _tag: "CaughtUp",
1192
+ nonterminal: state.nonterminal
1193
+ };
1194
+ observed.queue.set(Native, charged);
1195
+ observed.charged.set(Native, charged.revision);
1196
+ const deadline = next(dueQueue.read());
1197
+ if (Number.isFinite(deadline)) checkpoint.at(Math.max(now + minimumAlarmDelay, deadline));
1198
+ else checkpoint.cancel();
1199
+ return {
1200
+ _tag: "Actionable",
1201
+ generation: state.dirty,
1202
+ sourceRevision: charged.revision,
1203
+ nonterminal: state.nonterminal,
1204
+ stalls: charged.stalls
1205
+ };
1206
+ });
1207
+ yield* failpoint.hit("maintenance:begin:after");
1208
+ return result;
1209
+ });
1210
+ const backoffDelay = (priorStalls, jitter) => {
1211
+ const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** Math.min(priorStalls, 30));
1212
+ return Math.ceil(backoff / 2 + backoff / 2 * jitter);
1213
+ };
1214
+ const rearmDelay = Effect.fnUntraced(function* (progressed, priorStalls) {
1215
+ return progressed ? config.alarmBackoffBase : backoffDelay(priorStalls, yield* Random.next);
1216
+ });
1217
+ const rearmFailure = Effect.fnUntraced(function* (observed) {
1218
+ const { generation, nativeOnly } = observed;
1219
+ if (generation === void 0) return;
1220
+ yield* failpoint.hit("maintenance:retry:before");
1221
+ yield* mutations.withSnapshot((active) => Effect.gen(function* () {
1222
+ const now = yield* Clock.currentTimeMillis;
1223
+ const jitter = yield* Random.next;
1224
+ yield* runAlarmTransaction("back off failed maintenance", async (transaction, checkpoint) => {
1225
+ const { state } = await readMaintenanceState(transaction);
1226
+ const previous = state.retry?.generation === generation && state.retry.nativeOnly === nativeOnly ? state.retry : void 0;
1227
+ const retry = state.retry?.generation === generation && state.retry.nativeOnly ? state.retry : MaintenanceRetry.make({
1228
+ generation,
1229
+ notBefore: Math.max(previous?.notBefore ?? 0, now + backoffDelay(previous?.stalls ?? 0, jitter)),
1230
+ nativeOnly,
1231
+ stalls: Math.min(30, (previous?.stalls ?? 0) + 1)
1232
+ });
1233
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
1234
+ ...state,
1235
+ retry
1236
+ })));
1237
+ const nativeDeadline = active > 0 || state.dirty !== generation ? now + minimumAlarmDelay : retry.notBefore;
1238
+ dueQueue.checkpointNative(state.dirty > state.processed || active > 0 ? nativeDeadline : null);
1239
+ for (const row of observed.queue.values()) if (row.id !== "effect-agent:native" && row.dueAt !== null && row.dueAt <= now) {
1240
+ const charged = observed.charged.get(row.id) === row.revision ? row : dueQueue.claim(row, now);
1241
+ if (charged !== void 0) dueQueue.complete(charged, now + backoffDelay(charged.stalls, jitter));
1242
+ }
1243
+ const next$6 = next(dueQueue.read());
1244
+ if (Number.isFinite(next$6)) checkpoint.at(Math.max(now + minimumAlarmDelay, next$6));
1245
+ else checkpoint.cancel();
1246
+ });
1247
+ }));
1248
+ yield* failpoint.hit("maintenance:retry:after");
1249
+ });
1250
+ const beginNative = (observed) => mutations.withSnapshot((activeAtStart) => Effect.gen(function* () {
1251
+ const generation = yield* beginPass(observed);
1252
+ if (activeAtStart === 0) {
1253
+ const native = (yield* queueSnapshot).find((row) => row.id === Native);
1254
+ if (native !== void 0) observed.available.set(native.id, native.revision);
1255
+ }
1256
+ return {
1257
+ ...generation,
1258
+ activeAtStart
1259
+ };
1260
+ }));
1261
+ const attemptSelected = Effect.fnUntraced(function* (selected, previousWaits, yieldAfter, recovery, admitted = false) {
1262
+ if (!admitted) yield* recoverThread(selected.threadId, recovery);
1263
+ let bindingFailure;
1264
+ const settlement = recovery.faults.has(selected.threadId) ? Option.none() : yield* runtime.processThreadHead(selected.threadId, {
1265
+ yieldAfter,
1266
+ ...admitted ? { admittedSubmissionId: selected.submissionId } : {}
1267
+ }).pipe(Effect.provideService(CurrentNativeSource, true), Effect.catchTag("BindingUnavailable", (failure) => {
1268
+ bindingFailure = failure;
1269
+ return Effect.succeedNone;
1270
+ }));
1271
+ const previous = previousWaits.find((wait) => wait.submissionId === selected.submissionId);
1272
+ const wait = bindingFailure === void 0 ? void 0 : BindingWait.make({
1273
+ threadId: selected.threadId,
1274
+ submissionId: selected.submissionId,
1275
+ reportedAt: previous?.reportedAt ?? (yield* Clock.currentTimeMillis)
1276
+ });
1277
+ if (bindingFailure !== void 0 && previous === void 0) yield* Effect.logError("Thread parked until its agent binding registry changes; original work remains pending", Cause.fail(bindingFailure)).pipe(Effect.annotateLogs({
1278
+ threadId: selected.threadId,
1279
+ submissionId: selected.submissionId
1280
+ }));
1281
+ if (wait !== void 0 || previous !== void 0) {
1282
+ yield* failpoint.hit("maintenance:binding-retry:before");
1283
+ yield* runStorage("record submission binding wait", storage.transaction((transaction) => Effect.gen(function* () {
1284
+ const encoded = yield* transaction.get(MAINTENANCE_STATE_KEY);
1285
+ const state = encoded === void 0 ? initialMaintenanceState() : yield* Schema.decodeUnknownEffect(ThreadMaintenanceState)(encoded);
1286
+ const bindingWaits = [...(state.bindingWaits ?? []).filter((entry) => entry.submissionId !== selected.submissionId), ...wait === void 0 ? [] : [wait]];
1287
+ yield* transaction.put(MAINTENANCE_STATE_KEY, yield* Schema.encodeEffect(ThreadMaintenanceState)(ThreadMaintenanceState.make({
1288
+ ...state,
1289
+ bindingWaits
1290
+ })));
1291
+ })).pipe(Effect.mapError(alarmFailure("record submission binding wait"))));
1292
+ yield* failpoint.hit("maintenance:binding-retry:after");
1293
+ }
1294
+ return Option.isSome(settlement) ? 1 : 0;
1295
+ });
1296
+ const advance = Effect.fnUntraced(function* (started, yieldAfter, observed, recovery, native, dispatch = true, reserved = new Set(native.active.keys())) {
1297
+ let publicationRow = (yield* queueSnapshot).find((row) => row.id === Publication);
1298
+ if (publicationRow !== void 0 && publicationRow.dueAt !== null && publicationRow.dueAt <= (yield* Clock.currentTimeMillis)) {
1299
+ yield* runQueued(publicationRow, mutations.withSnapshot((active) => started._tag === "Actionable" && active === 0 ? publication.prepareGeneration(started.generation) : Effect.void).pipe(Effect.andThen(publication.drain)), observed);
1300
+ publicationRow = (yield* queueSnapshot).find((row) => row.id === Publication);
1301
+ }
1302
+ const pending = Option.fromNullishOr(publicationRow?.dueAt);
1303
+ if (started._tag === "CaughtUp" || Option.isSome(pending) || publicationRow?.state === "parked") {
1304
+ const nextAttemptAt = yield* mutations.withSnapshot((active) => Effect.gen(function* () {
1305
+ const now = yield* Clock.currentTimeMillis;
1306
+ const { state } = yield* runTransaction("read native maintenance deadline", () => dueQueue.transaction((transaction) => readMaintenanceState(transaction)));
1307
+ const native = active > 0 || state.dirty > state.processed ? state.retry?.generation === state.dirty && active === 0 ? state.retry.notBefore : now + minimumAlarmDelay : 1e400;
1308
+ const next = Option.isSome(pending) ? pending.value : native;
1309
+ return Number.isFinite(next) ? Math.max(now + minimumAlarmDelay, next) : void 0;
1310
+ }));
1311
+ return {
1312
+ phase: "caught-up",
1313
+ nonterminal: started.nonterminal,
1314
+ nextAttemptAt
1315
+ };
1316
+ }
1317
+ if (native.generation !== started.generation || native.sourceRevision !== started.sourceRevision) {
1318
+ native.deferred.clear();
1319
+ native.generation = started.generation;
1320
+ native.sourceRevision = started.sourceRevision;
1321
+ }
1322
+ if (native.active.size > 0 && native.scanGeneration === started.generation && native.scanRevision === started.sourceRevision) return {
1323
+ phase: "actionable",
1324
+ nonterminal: started.nonterminal,
1325
+ nextAttemptAt: void 0
1326
+ };
1327
+ native.scanGeneration = started.activeAtStart === 0 ? started.generation : void 0;
1328
+ native.scanRevision = started.activeAtStart === 0 ? started.sourceRevision : void 0;
1329
+ observed.nativeOnly = true;
1330
+ const observation = recovery.observation ??= {
1331
+ generation: started.generation,
1332
+ activeAtStart: started.activeAtStart
1333
+ };
1334
+ const { scannedGeneration, afterWorkThread } = yield* runTransaction("read work discovery position", async () => {
1335
+ const { state } = await readMaintenanceState(ctx.storage);
1336
+ return {
1337
+ scannedGeneration: state.dirty,
1338
+ afterWorkThread: framework.singleThreadRuntime === runtime && state.lastRecoveredThreadId === nativeThread ? void 0 : state.lastRecoveredThreadId
1339
+ };
1340
+ });
1341
+ const current = yield* listNonterminal;
1342
+ let workOwners = framework.singleThreadRuntime === runtime && nativeThread !== void 0 && current.some((submission) => submission.threadId === nativeThread) ? {
1343
+ threadIds: [nativeThread],
1344
+ afterThreadId: void 0
1345
+ } : yield* runtime.discoverWorkThreads({
1346
+ limit: 32,
1347
+ ...afterWorkThread === void 0 ? {} : { afterThreadId: afterWorkThread }
1348
+ }).pipe(Effect.provideService(CurrentNativeSource, true));
1349
+ if (workOwners.threadIds.length === 0 && afterWorkThread !== void 0) workOwners = yield* runtime.discoverWorkThreads({ limit: 32 }).pipe(Effect.provideService(CurrentNativeSource, true));
1350
+ recovery.discoveryPending ||= workOwners.afterThreadId !== void 0;
1351
+ const selectionTime = yield* Clock.currentTimeMillis;
1352
+ const submissionsByThread = /* @__PURE__ */ new Map();
1353
+ for (const row of current) {
1354
+ const ids = submissionsByThread.get(row.threadId) ?? [];
1355
+ ids.push(row.submissionId);
1356
+ submissionsByThread.set(row.threadId, ids);
1357
+ }
1358
+ for (const threadId of workOwners.threadIds) if (!submissionsByThread.has(threadId)) submissionsByThread.set(threadId, []);
1359
+ yield* runTransaction("read Thread recovery deadlines", async () => {
1360
+ for (const [threadId, ids] of submissionsByThread) {
1361
+ if (!recovery.loaded.has(threadId)) {
1362
+ const encoded = await ctx.storage.get(recoveryFaultKey(threadId));
1363
+ if (encoded !== void 0) {
1364
+ const fault = decodeRecoveryFault(threadId, encoded);
1365
+ recovery.faults.set(threadId, fault);
1366
+ recovery.recipients.set(threadId, new Set(await readRecoveryRecipients(ctx.storage, fault)));
1367
+ }
1368
+ recovery.loaded.add(threadId);
1369
+ }
1370
+ if (recovery.faults.get(threadId) === void 0 || ids.every((id) => recovery.recipients.get(threadId)?.has(id))) continue;
1371
+ await dueQueue.transaction(async (transaction) => {
1372
+ const encoded = await transaction.get(recoveryFaultKey(threadId));
1373
+ if (encoded === void 0) return;
1374
+ const previous = decodeRecoveryFault(threadId, encoded);
1375
+ const previousIds = await readRecoveryRecipients(transaction, previous);
1376
+ const known = new Set(previousIds);
1377
+ const added = ids.filter((id) => !known.has(id));
1378
+ if (added.length === 0) return;
1379
+ const updated = ThreadRecoveryFault.make({
1380
+ ...previous,
1381
+ recipientCount: previousIds.length + added.length
1382
+ });
1383
+ await appendRecoveryRecipients(transaction, threadId, previousIds.length, added);
1384
+ await transaction.put(recoveryFaultKey(threadId), encodeRecoveryFault(updated));
1385
+ await appendRecoveryEvents(transaction, added.map((id) => recoveryEvent(updated, id, "created", selectionTime)));
1386
+ recovery.faults.set(threadId, updated);
1387
+ recovery.recipients.set(threadId, /* @__PURE__ */ new Set([...previousIds, ...added]));
1388
+ });
1389
+ }
1390
+ });
1391
+ const reports = recovery.reports;
1392
+ const recoveryFaults = recovery.faults;
1393
+ const bindingWaits = yield* runTransaction("read binding waits", async () => (await readMaintenanceState(ctx.storage)).state.bindingWaits ?? []);
1394
+ const parked = new Set(bindingWaits.map((wait) => wait.submissionId));
1395
+ const waiting = (row) => !recovery.pending.has(row.threadId) && !recoveryFaults.has(row.threadId) && (parked.has(row.submissionId) || stableExternalWait(row, reports));
1396
+ const heads = /* @__PURE__ */ new Map();
1397
+ for (const row of current) {
1398
+ if (row.state === "unknown" && waiting(row)) continue;
1399
+ if (!heads.has(row.threadId)) heads.set(row.threadId, row);
1400
+ }
1401
+ const stopping = /* @__PURE__ */ new Set();
1402
+ for (const head of heads.values()) {
1403
+ if (head.state !== "ready" || native.active.has(head.threadId) || recovery.pending.has(head.threadId) || recoveryFaults.has(head.threadId)) continue;
1404
+ const intent = yield* isolateRecovery(ledger.readAbortIntent(AbortIntentRequest.make({ submissionId: head.submissionId })), {
1405
+ timeout: recoveryConfig.recoveryTimeout,
1406
+ phase: () => "recovery",
1407
+ operation: "read abort intent"
1408
+ });
1409
+ if (Result.isSuccess(intent)) {
1410
+ if (intent.success !== void 0) stopping.add(head.threadId);
1411
+ } else {
1412
+ const faults = yield* recordRecoveryFaults(RecoverySweepResult.make({
1413
+ reports: [],
1414
+ blocked: [RecoveryBlocked.make({
1415
+ threadId: head.threadId,
1416
+ failure: intent.failure
1417
+ })]
1418
+ }), recovery, current);
1419
+ for (const [threadId, fault] of faults) recoveryFaults.set(threadId, fault);
1420
+ recovery.recovered++;
1421
+ }
1422
+ }
1423
+ const eligible = [...heads.values()].filter((head) => !recovery.pending.has(head.threadId) && !stopping.has(head.threadId) && !recoveryFaults.has(head.threadId) && !waiting(head) && (head.state === "ready" || reports.has(head.submissionId))).map((head) => head.threadId).sort();
1424
+ yield* failpoint.hit("maintenance:select:before");
1425
+ const selection = yield* runTransaction("select maintenance lane", () => dueQueue.transaction(async (transaction) => {
1426
+ const { state } = await readMaintenanceState(transaction);
1427
+ const waits = (state.bindingWaits ?? []).filter((retry) => heads.get(retry.threadId)?.submissionId === retry.submissionId);
1428
+ const runnable = eligible.filter((threadId) => !reserved.has(threadId) && !native.active.has(threadId) && !native.deferred.has(threadId) && !waits.some((wait) => wait.threadId === threadId));
1429
+ const pivot = Math.max(0, runnable.findIndex((threadId) => state.lastServedThreadId === void 0 || threadId > state.lastServedThreadId));
1430
+ const selected = dispatch ? [...runnable.slice(pivot), ...runnable.slice(0, pivot)].slice(0, nativeDispatchConcurrency() - reserved.size) : [];
1431
+ const next = selected.at(-1);
1432
+ if (next !== void 0 && next !== state.lastServedThreadId) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
1433
+ ...state,
1434
+ lastServedThreadId: next
1435
+ })));
1436
+ const backlog = recovery.started ? [] : [.../* @__PURE__ */ new Set([...heads.keys(), ...workOwners.threadIds])].filter((threadId) => {
1437
+ const fault = recoveryFaults.get(threadId);
1438
+ return !eligible.includes(threadId) && (fault === void 0 || fault.retryAt <= selectionTime);
1439
+ });
1440
+ const after = backlog.filter((threadId) => state.lastRecoveredThreadId === void 0 || threadId > state.lastRecoveredThreadId);
1441
+ const before = backlog.filter((threadId) => state.lastRecoveredThreadId !== void 0 && threadId <= state.lastRecoveredThreadId);
1442
+ return {
1443
+ selected,
1444
+ waits,
1445
+ backlog: [...after, ...before].slice(0, 32),
1446
+ discoveryPending: backlog.length > 32
1447
+ };
1448
+ }));
1449
+ yield* failpoint.hit("maintenance:select:after");
1450
+ if (!recovery.started) {
1451
+ recovery.started = true;
1452
+ recovery.needsCheckpoint = selection.backlog.length > 0;
1453
+ recovery.discoveryPending ||= selection.discoveryPending;
1454
+ for (const threadId of selection.backlog) recovery.pending.add(threadId);
1455
+ yield* Deferred.succeed(recovery.queue, selection.backlog);
1456
+ }
1457
+ for (const threadId of selection.selected) {
1458
+ const selected = heads.get(threadId);
1459
+ if (selected === void 0) continue;
1460
+ native.dispatched++;
1461
+ native.active.set(threadId, yield* Effect.forkIn(attemptSelected(selected, selection.waits, yieldAfter, recovery), native.scope));
1462
+ }
1463
+ if (native.active.size > 0) return {
1464
+ phase: "actionable",
1465
+ nonterminal: current.length,
1466
+ nextAttemptAt: void 0,
1467
+ dispatched: selection.selected.length > 0
1468
+ };
1469
+ const remaining = yield* listNonterminal;
1470
+ const waitingHeads = /* @__PURE__ */ new Map();
1471
+ const autonomous = recovery.pending.size > 0 || recovery.discoveryPending || recoveryFaults.size > 0 || recovery.retryAtMillis !== void 0 || remaining.some((snapshot) => {
1472
+ if (snapshot.state === "unknown" && waiting(snapshot)) return false;
1473
+ const headWaiting = waitingHeads.get(snapshot.threadId);
1474
+ if (headWaiting === void 0) waitingHeads.set(snapshot.threadId, waiting(snapshot));
1475
+ if (headWaiting === true && snapshot.state === "ready" && reports.get(snapshot.submissionId)?.decision._tag === "ApplyInput") return false;
1476
+ return !waiting(snapshot);
1477
+ });
1478
+ const progressed = native.progressed || recovery.repaired;
1479
+ const now = yield* Clock.currentTimeMillis;
1480
+ const ordinaryDelay = autonomous ? yield* rearmDelay(progressed, started.stalls) : 0;
1481
+ const nextEligible = [...recoveryFaults.values()].map((fault) => fault.retryAt).concat(eligible.filter((threadId) => !selection.waits.some((wait) => wait.threadId === threadId)).map(() => now));
1482
+ if (recovery.retryAtMillis !== void 0) nextEligible.push(recovery.retryAtMillis);
1483
+ const retryDelay = nextEligible.length === 0 ? 0 : Math.max(0, Math.min(...nextEligible) - now);
1484
+ const delay = Math.max(ordinaryDelay, retryDelay);
1485
+ yield* failpoint.hit("maintenance:checkpoint:before");
1486
+ const nextAttemptAt = yield* mutations.withSnapshot((active) => runTransaction("checkpoint native maintenance", () => dueQueue.transaction(async (transaction) => {
1487
+ const { state } = await readMaintenanceState(transaction);
1488
+ const mutationOverlap = observation.activeAtStart > 0 || started.activeAtStart > 0 || active > 0;
1489
+ const generation = remaining.length === 0 && workOwners.threadIds.length === 0 && !mutationOverlap && state.dirty === scannedGeneration ? scannedGeneration : observation.generation;
1490
+ const processed = autonomous || mutationOverlap ? state.processed : state.processed > generation ? state.processed : generation;
1491
+ const canBackoff = !mutationOverlap && state.dirty === started.generation;
1492
+ const next = ThreadMaintenanceState.make({
1493
+ ...Struct.omit(state, ["retry"]),
1494
+ processed,
1495
+ nonterminal: remaining.length,
1496
+ bindingWaits: (state.bindingWaits ?? []).filter((retry) => remaining.some((row) => row.submissionId === retry.submissionId)),
1497
+ ...autonomous && !progressed && canBackoff ? { retry: MaintenanceRetry.make({
1498
+ generation: started.generation,
1499
+ notBefore: now + delay,
1500
+ nativeOnly: true,
1501
+ stalls: Math.min(30, started.stalls + 1)
1502
+ }) } : {}
1503
+ });
1504
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
1505
+ const dueAt = autonomous ? now + (canBackoff ? delay : minimumAlarmDelay) : mutationOverlap || next.dirty > next.processed ? now + minimumAlarmDelay : null;
1506
+ dueQueue.checkpointNative(dueAt);
1507
+ return dueAt ?? void 0;
1508
+ })));
1509
+ yield* failpoint.hit("maintenance:checkpoint:after");
1510
+ if (remaining.length === 0 && recovery.pending.size === 0) recovery.observation = {
1511
+ generation: observation.generation,
1512
+ activeAtStart: 0
1513
+ };
1514
+ native.deferred.clear();
1515
+ native.progressed = false;
1516
+ native.needsCheckpoint = false;
1517
+ return {
1518
+ phase: "actionable",
1519
+ nonterminal: remaining.length,
1520
+ nextAttemptAt
1521
+ };
1522
+ });
1523
+ const validateLanes = Effect.fnUntraced(function* (lanes, queued) {
1524
+ const ids = /* @__PURE__ */ new Set([
1525
+ Native,
1526
+ Publication,
1527
+ Projection,
1528
+ Messages
1529
+ ]);
1530
+ for (const lane of lanes) {
1531
+ yield* Schema.decodeEffect(LaneId)(lane.id).pipe(Effect.mapError(alarmFailure("maintenance lane ID")));
1532
+ if (ids.has(lane.id)) return yield* DurableAlarmError.make({
1533
+ operation: "maintenance lane ID",
1534
+ message: `Duplicate maintenance lane: ${lane.id}`
1535
+ });
1536
+ ids.add(lane.id);
1537
+ }
1538
+ for (const row of queued) if (row.dueAt !== null && !ids.has(row.id)) return yield* DurableAlarmError.make({
1539
+ operation: "maintenance lane ID",
1540
+ message: `No handler registered for scheduled lane: ${row.id}`
1541
+ });
1542
+ });
1543
+ const dispatch = Effect.fnUntraced(function* (yieldAfter, dispatchUntil, observed, admission) {
1544
+ const leanSelection = framework.singleThreadRuntime === runtime && publication === emptyPublication && host.lanes.length === 0 && framework.lanes.length === 0;
1545
+ const notified = leanSelection ? Effect.never : (yield* Stream.toPull(wakes.wakes)).pipe(Effect.asVoid, Effect.catch(() => Effect.never));
1546
+ const started = yield* beginNative(observed);
1547
+ yield* mutations.withSnapshot(() => Effect.gen(function* () {
1548
+ const queued = yield* queueSnapshot;
1549
+ const producing = yield* mutations.activeLanes;
1550
+ for (const row of queued) {
1551
+ observed.queue.set(row.id, row);
1552
+ if (!producing.has(row.id)) observed.available.set(row.id, row.revision);
1553
+ }
1554
+ }));
1555
+ const auxiliaryScope = yield* Effect.acquireRelease(Scope.make("parallel"), (scope, exit) => Scope.close(scope, exit));
1556
+ const fork = (work) => Effect.forkIn(work, auxiliaryScope);
1557
+ const lanes = [
1558
+ recoveryEventLane,
1559
+ ...framework.lanes,
1560
+ ...host.lanes
1561
+ ].map((lane) => ({
1562
+ ...lane,
1563
+ exhausted: false,
1564
+ fiber: void 0
1565
+ }));
1566
+ let messageExhausted = false;
1567
+ let delivery;
1568
+ let failure;
1569
+ const recovery = {
1570
+ queue: yield* Deferred.make(),
1571
+ pending: /* @__PURE__ */ new Set(),
1572
+ loaded: /* @__PURE__ */ new Set(),
1573
+ reports: /* @__PURE__ */ new Map(),
1574
+ faults: /* @__PURE__ */ new Map(),
1575
+ recipients: /* @__PURE__ */ new Map(),
1576
+ started: false,
1577
+ needsCheckpoint: false,
1578
+ recovered: 0,
1579
+ repaired: false,
1580
+ discoveryPending: false
1581
+ };
1582
+ let recoveryFiber;
1583
+ let backfill;
1584
+ const dispatch = {
1585
+ scope: auxiliaryScope,
1586
+ active: /* @__PURE__ */ new Map(),
1587
+ deferred: /* @__PURE__ */ new Set(),
1588
+ dispatched: 0,
1589
+ settled: 0,
1590
+ progressed: false,
1591
+ needsCheckpoint: false
1592
+ };
1593
+ let native;
1594
+ let result;
1595
+ let backlog;
1596
+ if (leanSelection && admission !== void 0 && started._tag === "Actionable") {
1597
+ dispatch.dispatched++;
1598
+ dispatch.active.set(admission.threadId, yield* fork(attemptSelected(admission, [], yieldAfter, recovery, true)));
1599
+ result = {
1600
+ phase: "actionable",
1601
+ nonterminal: started.nonterminal,
1602
+ nextAttemptAt: void 0,
1603
+ dispatched: true
1604
+ };
1605
+ } else if (leanSelection) {
1606
+ result = yield* advance(started, yieldAfter, observed, recovery, dispatch);
1607
+ recovery.started = true;
1608
+ yield* Deferred.succeed(recovery.queue, []);
1609
+ backlog = yield* Deferred.await(recovery.queue);
1610
+ } else {
1611
+ native = yield* fork(advance(started, yieldAfter, observed, recovery, dispatch));
1612
+ result = {
1613
+ phase: "caught-up",
1614
+ nonterminal: started.nonterminal,
1615
+ nextAttemptAt: void 0
1616
+ };
1617
+ }
1618
+ if (backlog === void 0 || backlog.length > 0) recoveryFiber = yield* fork(Effect.gen(function* () {
1619
+ for (const threadId of backlog ?? (yield* Deferred.await(recovery.queue))) {
1620
+ yield* failpoint.hit("maintenance:select:before");
1621
+ yield* runTransaction("select old recovery lane", () => dueQueue.transaction(async (transaction) => {
1622
+ const { state } = await readMaintenanceState(transaction);
1623
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
1624
+ ...state,
1625
+ lastRecoveredThreadId: threadId
1626
+ })));
1627
+ }));
1628
+ yield* failpoint.hit("maintenance:select:after");
1629
+ yield* recoverThread(threadId, recovery);
1630
+ recovery.pending.delete(threadId);
1631
+ if (!recovery.faults.has(threadId)) yield* wakes.notify(threadId);
1632
+ }
1633
+ }));
1634
+ const projectionRow = (yield* queueSnapshot).find((row) => row.id === Projection);
1635
+ if (projectionRow !== void 0 && projectionRow.dueAt !== null && projectionRow.dueAt <= (yield* Clock.currentTimeMillis) && !(yield* mutations.activeLanes).has("effect-agent:projection")) backfill = yield* fork(runQueued(projectionRow, projection.drain.pipe(Effect.andThen(projection.pendingDeadline)), observed).pipe(Effect.timeoutOption(config.projectionDispatchTimeoutMillis), Effect.asVoid));
1636
+ let phase = result.phase;
1637
+ let nativeCheck = result.dispatched === true && dispatch.active.size < nativeDispatchConcurrency();
1638
+ observed.nativeOnly = dispatch.active.size > 0;
1639
+ const until = DateTime.toEpochMillis(yieldAfter);
1640
+ const dispatchEnd = DateTime.toEpochMillis(dispatchUntil);
1641
+ while (true) {
1642
+ if (native?.pollUnsafe() !== void 0) {
1643
+ result = yield* Fiber.join(native);
1644
+ native = void 0;
1645
+ if (result.phase === "actionable") phase = "actionable";
1646
+ observed.nativeOnly = dispatch.active.size > 0;
1647
+ if (result.dispatched === true && dispatch.active.size < nativeDispatchConcurrency()) {
1648
+ dispatch.scanGeneration = void 0;
1649
+ nativeCheck = true;
1650
+ }
1651
+ recovery.started = true;
1652
+ yield* Deferred.succeed(recovery.queue, []);
1653
+ }
1654
+ for (const [threadId, attempt] of dispatch.active) {
1655
+ const exit = attempt.pollUnsafe();
1656
+ if (exit === void 0) continue;
1657
+ dispatch.active.delete(threadId);
1658
+ dispatch.scanGeneration = void 0;
1659
+ if (Exit.isFailure(exit)) return yield* Effect.failCause(exit.cause);
1660
+ dispatch.settled += exit.value;
1661
+ dispatch.progressed ||= exit.value > 0;
1662
+ dispatch.needsCheckpoint = true;
1663
+ if (exit.value === 0) dispatch.deferred.add(threadId);
1664
+ nativeCheck = true;
1665
+ }
1666
+ if (recoveryFiber?.pollUnsafe() !== void 0) {
1667
+ yield* Fiber.join(recoveryFiber);
1668
+ recoveryFiber = void 0;
1669
+ dispatch.scanGeneration = void 0;
1670
+ nativeCheck ||= recovery.needsCheckpoint;
1671
+ }
1672
+ const backfillExit = backfill?.pollUnsafe();
1673
+ if (backfillExit !== void 0) {
1674
+ backfill = void 0;
1675
+ if (Exit.isFailure(backfillExit)) failure ??= backfillExit.cause;
1676
+ }
1677
+ for (const lane of lanes) {
1678
+ const exit = lane.fiber?.pollUnsafe();
1679
+ if (exit === void 0) continue;
1680
+ lane.fiber = void 0;
1681
+ if (Exit.isFailure(exit)) {
1682
+ failure ??= exit.cause;
1683
+ lane.exhausted = true;
1684
+ }
1685
+ }
1686
+ const deliveryExit = delivery?.pollUnsafe();
1687
+ if (deliveryExit !== void 0) {
1688
+ delivery = void 0;
1689
+ if (Exit.isFailure(deliveryExit)) {
1690
+ failure ??= deliveryExit.cause;
1691
+ messageExhausted = true;
1692
+ }
1693
+ }
1694
+ const now = yield* Clock.currentTimeMillis;
1695
+ if (now >= until) break;
1696
+ const queueRevision = yield* mutations.revision;
1697
+ const queued = yield* queueSnapshot;
1698
+ const producing = yield* mutations.activeLanes;
1699
+ yield* validateLanes(lanes, queued);
1700
+ for (const lane of lanes) {
1701
+ if (lane.phase === "after-native" || lane.fiber !== void 0 || lane.exhausted || producing.has(lane.id)) continue;
1702
+ const row = queued.find((row) => row.id === lane.id);
1703
+ if (row === void 0 || row.dueAt === null || row.dueAt > now) continue;
1704
+ const dueAt = row.dueAt;
1705
+ lane.fiber = yield* fork(Effect.gen(function* () {
1706
+ yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(lane.dispatchTimeoutMillis).pipe(Effect.mapError(alarmFailure("host dispatch allowance")));
1707
+ const selectedAt = yield* Clock.currentTimeMillis;
1708
+ if (selectedAt >= until || selectedAt + lane.dispatchTimeoutMillis > dispatchEnd) {
1709
+ lane.exhausted = true;
1710
+ return Option.some(dueAt);
1711
+ }
1712
+ return yield* runQueued(row, lane.run.pipe(Effect.scoped), observed).pipe(Effect.timeoutOrElse({
1713
+ duration: lane.dispatchTimeoutMillis,
1714
+ orElse: () => DurableAlarmError.make({
1715
+ operation: "host dispatch allowance",
1716
+ message: "The admitted host wave exceeded its allowance; durable work remains pending"
1717
+ })
1718
+ }));
1719
+ }));
1720
+ }
1721
+ if (delivery === void 0 && !messageExhausted && !producing.has("effect-agent:messages")) {
1722
+ const row = queued.find((row) => row.id === Messages);
1723
+ if (row !== void 0 && row.dueAt !== null && row.dueAt <= now) delivery = yield* fork(runQueued(row, Effect.gen(function* () {
1724
+ const wave = yield* messages.prepare;
1725
+ const selectedAt = yield* Clock.currentTimeMillis;
1726
+ if (selectedAt >= until || selectedAt + wave.timeoutMillis > dispatchEnd) {
1727
+ messageExhausted = true;
1728
+ return Option.fromNullishOr(row.dueAt);
1729
+ }
1730
+ return yield* wave.run;
1731
+ }), observed).pipe(Effect.asVoid));
1732
+ }
1733
+ if (native === void 0 && dispatch.active.size === 0 && recoveryFiber === void 0 && !recovery.needsCheckpoint && backfill === void 0 && delivery === void 0 && lanes.every((lane) => lane.fiber === void 0)) break;
1734
+ if (native === void 0 && nativeCheck && dispatch.active.size < nativeDispatchConcurrency()) {
1735
+ nativeCheck = false;
1736
+ const nativeCheckpoint = dispatch.needsCheckpoint && dispatch.active.size === 0;
1737
+ const checkpoint = recoveryFiber === void 0 && recovery.needsCheckpoint || nativeCheckpoint;
1738
+ if (checkpoint) recovery.needsCheckpoint = false;
1739
+ const reserved = new Set(dispatch.active.keys());
1740
+ native = yield* fork(Effect.gen(function* () {
1741
+ const awakened = checkpoint ? started : yield* beginNative(observed);
1742
+ return yield* advance(awakened, yieldAfter, observed, recovery, dispatch, !nativeCheckpoint && (!checkpoint || dispatch.settled === 0), reserved);
1743
+ }));
1744
+ }
1745
+ const next = Math.min(native === void 0 ? result.nextAttemptAt ?? 1e400 : 1e400, ...queued.flatMap((row) => row.id !== "effect-agent:native" && row.dueAt !== null && row.dueAt > now ? [row.dueAt] : []), until);
1746
+ const completing = [
1747
+ native,
1748
+ ...dispatch.active.values(),
1749
+ recoveryFiber,
1750
+ backfill,
1751
+ delivery,
1752
+ ...lanes.map((lane) => lane.fiber)
1753
+ ].filter((fiber) => fiber !== void 0);
1754
+ const changed = awaitAnyCompletion(completing, queueRevision);
1755
+ if ((yield* leanSelection && native === void 0 && dispatch.active.size === 1 && completing.length === 1 && !queued.some((row) => row.id !== "effect-agent:native" && row.dueAt !== null && row.dueAt > now && row.dueAt < until) ? changed : Effect.raceAllFirst([
1756
+ changed,
1757
+ ...leanSelection ? [] : [notified.pipe(Effect.as("scan"))],
1758
+ Effect.sleep(Math.max(0, next - now)).pipe(Effect.as("scan"))
1759
+ ])) === "scan") nativeCheck = true;
1760
+ }
1761
+ if (native !== void 0) {
1762
+ result = yield* Fiber.join(native);
1763
+ if (result.phase === "actionable") phase = "actionable";
1764
+ observed.nativeOnly = dispatch.active.size > 0;
1765
+ recovery.started = true;
1766
+ yield* Deferred.succeed(recovery.queue, []);
1767
+ }
1768
+ for (const attempt of dispatch.active.values()) {
1769
+ const settled = yield* Fiber.join(attempt);
1770
+ dispatch.settled += settled;
1771
+ dispatch.progressed ||= settled > 0;
1772
+ }
1773
+ dispatch.active.clear();
1774
+ observed.nativeOnly = false;
1775
+ for (const fiber of [
1776
+ recoveryFiber,
1777
+ backfill,
1778
+ delivery,
1779
+ ...lanes.map((lane) => lane.fiber)
1780
+ ]) {
1781
+ if (fiber === void 0) continue;
1782
+ const exit = yield* Fiber.await(fiber);
1783
+ if (Exit.isFailure(exit)) failure ??= exit.cause;
1784
+ }
1785
+ if (failure !== void 0) return yield* Effect.failCause(failure);
1786
+ if (recovery.needsCheckpoint || dispatch.dispatched > 0) {
1787
+ result = yield* advance(started, yieldAfter, observed, recovery, dispatch, false);
1788
+ if (result.phase === "actionable") phase = "actionable";
1789
+ }
1790
+ yield* Scope.close(auxiliaryScope, Exit.void);
1791
+ return {
1792
+ result,
1793
+ phase,
1794
+ recovered: recovery.recovered,
1795
+ settled: dispatch.settled
1796
+ };
1797
+ });
1798
+ const pass = Effect.fnUntraced(function* (yieldAfter, dispatchUntil, observed, admission) {
1799
+ const concurrent = yield* Effect.exit(Effect.scoped(dispatch(yieldAfter, dispatchUntil, observed, admission)).pipe(Effect.provideService(ThreadMutationGate, mutations)));
1800
+ const afterNative = yield* Effect.gen(function* () {
1801
+ const lanes = [
1802
+ recoveryEventLane,
1803
+ ...framework.lanes,
1804
+ ...host.lanes
1805
+ ];
1806
+ const selected = lanes.filter((lane) => lane.phase === "after-native");
1807
+ if (selected.length === 0) return [];
1808
+ const queued = yield* queueSnapshot;
1809
+ const producing = yield* mutations.activeLanes;
1810
+ for (const row of queued) if (!producing.has(row.id)) observed.available.set(row.id, row.revision);
1811
+ const dispatchEnd = DateTime.toEpochMillis(dispatchUntil);
1812
+ const afterNativeIds = new Set(selected.map((lane) => lane.id));
1813
+ const completed = [];
1814
+ let yielded = false;
1815
+ const yieldToConcurrent = Effect.gen(function* () {
1816
+ while (true) {
1817
+ const revision = yield* mutations.revision;
1818
+ const now = yield* Clock.currentTimeMillis;
1819
+ const current = yield* queueSnapshot;
1820
+ const active = yield* mutations.activeLanes;
1821
+ if (current.some((row) => !afterNativeIds.has(row.id) && !active.has(row.id) && row.dueAt !== null && row.dueAt <= now && row.revision !== observed.available.get(row.id))) {
1822
+ yielded = true;
1823
+ return completed;
1824
+ }
1825
+ yield* mutations.awaitChange(revision);
1826
+ }
1827
+ });
1828
+ yield* validateLanes(lanes, queued);
1829
+ const cursor = yield* mutations.withSnapshot(() => runTransaction("read post-native dispatch cursor", () => dueQueue.transaction(async (transaction) => (await readMaintenanceState(transaction)).state.lastAfterNativeLaneId)));
1830
+ const ordered = selected.toSorted((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
1831
+ const after = cursor === void 0 ? 0 : ordered.findIndex((lane) => lane.id > cursor);
1832
+ const rotated = after <= 0 ? ordered : [...ordered.slice(after), ...ordered.slice(0, after)];
1833
+ const waves = Effect.forEach(rotated, (lane) => Effect.gen(function* () {
1834
+ const row = queued.find((row) => row.id === lane.id);
1835
+ const now = yield* Clock.currentTimeMillis;
1836
+ if (row === void 0 || row.dueAt === null || row.dueAt > now || producing.has(lane.id)) return;
1837
+ yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(lane.dispatchTimeoutMillis).pipe(Effect.mapError(alarmFailure("host dispatch allowance")));
1838
+ if (now + lane.dispatchTimeoutMillis > dispatchEnd) return;
1839
+ const admit = mutations.withSnapshot(() => runTransaction("advance post-native dispatch cursor", () => dueQueue.transaction(async (transaction) => {
1840
+ const { state } = await readMaintenanceState(transaction);
1841
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(ThreadMaintenanceState.make({
1842
+ ...state,
1843
+ lastAfterNativeLaneId: lane.id
1844
+ })));
1845
+ })));
1846
+ yield* runQueued(row, admit.pipe(Effect.andThen(lane.run.pipe(Effect.scoped))), observed, () => yielded).pipe(Effect.timeoutOrElse({
1847
+ duration: lane.dispatchTimeoutMillis,
1848
+ orElse: () => DurableAlarmError.make({
1849
+ operation: "host dispatch allowance",
1850
+ message: "The admitted host wave exceeded its allowance; durable work remains pending"
1851
+ })
1852
+ }));
1853
+ }).pipe(Effect.exit, Effect.tap((exit) => Effect.sync(() => {
1854
+ if (!yielded || Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) completed.push(exit);
1855
+ }))), { concurrency: afterNativeDispatchConcurrency }).pipe(Effect.as(completed));
1856
+ return yield* Effect.raceFirst(waves, yieldToConcurrent);
1857
+ }).pipe(Effect.exit);
1858
+ let failure = Exit.isFailure(concurrent) ? concurrent.cause : Cause.empty;
1859
+ if (Exit.isFailure(afterNative)) failure = Cause.combine(failure, afterNative.cause);
1860
+ else for (const exit of afterNative.value) if (Exit.isFailure(exit)) failure = Cause.combine(failure, exit.cause);
1861
+ if (Exit.isFailure(concurrent) || failure.reasons.length > 0) return yield* Effect.failCause(failure);
1862
+ const { result, phase, recovered, settled } = concurrent.value;
1863
+ yield* failpoint.hit("maintenance:finish:before");
1864
+ const disposition = yield* mutations.withSnapshot((active) => Effect.gen(function* () {
1865
+ const now = yield* Clock.currentTimeMillis;
1866
+ return yield* runAlarmTransaction("finish maintenance event", async (transaction, checkpoint) => {
1867
+ const { state } = await readMaintenanceState(transaction);
1868
+ const native = active > 0 || state.dirty > state.processed ? state.retry?.generation === state.dirty && active === 0 ? Math.max(now + minimumAlarmDelay, state.retry.notBefore) : state.dirty === observed.generation && active === 0 ? result.nextAttemptAt ?? now + minimumAlarmDelay : now + minimumAlarmDelay : 1e400;
1869
+ dueQueue.checkpointNative(Number.isFinite(native) ? native : null);
1870
+ const next$3 = next(dueQueue.read());
1871
+ if (Number.isFinite(next$3)) {
1872
+ checkpoint.at(Math.max(now + minimumAlarmDelay, next$3));
1873
+ return "rearmed";
1874
+ }
1875
+ if (config.recoveryWindowMillis > 0 && observed.charged.size > 0) {
1876
+ checkpoint.at(now + config.recoveryWindowMillis);
1877
+ return "rearmed";
1878
+ }
1879
+ checkpoint.cancel();
1880
+ return "cleared";
1881
+ });
1882
+ }));
1883
+ yield* failpoint.hit("maintenance:finish:after");
1884
+ const report = MaintenancePassReport.make({
1885
+ phase,
1886
+ recovered,
1887
+ settled,
1888
+ nonterminal: result.nonterminal,
1889
+ alarm: disposition
1890
+ });
1891
+ yield* Effect.annotateCurrentSpan({
1892
+ phase: report.phase,
1893
+ recovered: report.recovered,
1894
+ settled: report.settled,
1895
+ nonterminal: report.nonterminal,
1896
+ alarm: report.alarm
1897
+ });
1898
+ return report;
1899
+ });
1900
+ const runPass = Effect.fnUntraced(function* (admission) {
1901
+ const now = yield* Clock.currentTimeMillis;
1902
+ const yieldAfter = DateTime.makeUnsafe(now + 6e5);
1903
+ const dispatchUntil = DateTime.makeUnsafe(now + 84e4);
1904
+ const observed = {
1905
+ nativeOnly: false,
1906
+ queue: /* @__PURE__ */ new Map(),
1907
+ charged: /* @__PURE__ */ new Map(),
1908
+ available: /* @__PURE__ */ new Map()
1909
+ };
1910
+ return yield* alarms.deferWakes(maintenancePassGate.withPermit(dueQueue.withView(Effect.scoped(pass(yieldAfter, dispatchUntil, observed, admission))).pipe(Effect.onErrorIf(() => true, () => rearmFailure(observed))))).pipe(hints.withHintsDeferred, Effect.catchTags({
1911
+ StorageOperationError: (error) => alarmFailure("defer maintenance wakes")(error),
1912
+ InvalidScheduleConfigurationError: (error) => alarmFailure("defer maintenance wakes")(error)
1913
+ }));
1914
+ }, Effect.timeoutOrElse({
1915
+ duration: "14 minutes",
1916
+ orElse: () => DurableAlarmError.make({
1917
+ operation: "maintenance pass deadline",
1918
+ message: "The maintenance event exceeded its 14 minute deadline; durable recovery remains pending"
1919
+ })
1920
+ }), Effect.ensuring(reportParked));
1921
+ return ThreadMaintenance.of({
1922
+ pass: runPass(void 0),
1923
+ start: (admission) => execution.waitUntil(runPass(admission)),
1924
+ ensureAlarm: mutations.withSnapshot(() => ensureAlarm()).pipe(Effect.tap(() => reportParked)),
1925
+ withMutation: (body) => mutations.withMutation(body.pipe(Effect.tap(() => publishCommitted.pipe(Effect.provide(publicationContext)))))
1926
+ });
1927
+ }));
1928
+ };
1929
+ export { Messages as _, ThreadMaintenance as a, Publication as b, ThreadMessageDelivery as c, ThreadPublication as d, ThreadRecoveryEvents as f, Lifecycle as g, HostLaneId as h, ThreadHostMaintenance as i, ThreadMutationGate as l, publishCommitted as m, DurableAlarmService as n, ThreadMaintenanceAlarm as o, ThreadRecoveryFaultEvent as p, MaintenancePassReport as r, ThreadMaintenanceFailpoint as s, Alarm_exports as t, ThreadNativeMaintenance as u, Native as v, Projection as y };
1930
+
1931
+ //# sourceMappingURL=Alarm-CbhflIzz.mjs.map