@lunora/scheduler 1.0.0-alpha.17 → 1.0.0-alpha.170

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 (33) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +8 -8
  3. package/dist/index.d.mts +911 -146
  4. package/dist/index.d.ts +911 -146
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/CRON_SCHEDULE_KINDS-AS5GtmnL.mjs +1 -0
  7. package/dist/packem_shared/MAX_RETRY_ATTEMPTS-Ds3leY0P.mjs +2 -0
  8. package/dist/packem_shared/assertScheduleDelay-D9Na2wPU.mjs +1 -0
  9. package/dist/packem_shared/assertScheduleInstant-KIOgxgOT.mjs +1 -0
  10. package/dist/packem_shared/assertValidCronExpression-fiNfNiWf.mjs +1 -0
  11. package/dist/packem_shared/createCronTrigger-cg32QNgj.mjs +1 -0
  12. package/dist/packem_shared/createQueueConsumer-CYwmsmvq.mjs +4 -0
  13. package/dist/packem_shared/createScheduler-BUMMD_lz.mjs +1 -0
  14. package/dist/packem_shared/createSchedulerHost-e5kSr3H-.mjs +1 -0
  15. package/dist/packem_shared/createWorkpool-BEdQoG83.mjs +1 -0
  16. package/dist/packem_shared/do-client-DnJqrsmj.mjs +1 -0
  17. package/dist/packem_shared/resolve-schedule-id-B2ghxgFm.mjs +1 -0
  18. package/dist/packem_shared/resolveScheduleId-BEV7mby4.mjs +1 -0
  19. package/dist/packem_shared/validate-cron-full.d-Bemx45E8.d.mts +28 -0
  20. package/dist/packem_shared/validate-cron-full.d-Bemx45E8.d.ts +28 -0
  21. package/dist/validate-cron-full.d.mts +1 -0
  22. package/dist/validate-cron-full.d.ts +1 -0
  23. package/dist/validate-cron-full.mjs +1 -0
  24. package/package.json +10 -5
  25. package/dist/packem_shared/CRON_SCHEDULE_KINDS-DMu4DfhG.mjs +0 -1
  26. package/dist/packem_shared/SchedulerDO-BAq6x7mo.mjs +0 -1
  27. package/dist/packem_shared/assertValidCronExpression-B2lN8n3O.mjs +0 -1
  28. package/dist/packem_shared/createCronTrigger-C4iUW_zz.mjs +0 -1
  29. package/dist/packem_shared/createQueueConsumer-B0qNXRUJ.mjs +0 -1
  30. package/dist/packem_shared/createScheduler-CsRAEtdb.mjs +0 -1
  31. package/dist/packem_shared/createSchedulerHost-C5XacwXv.mjs +0 -1
  32. package/dist/packem_shared/createWorkpool-DyVdhB6o.mjs +0 -1
  33. package/dist/packem_shared/do-client-BFps7NIj.mjs +0 -1
package/dist/index.d.ts CHANGED
@@ -1,25 +1,51 @@
1
1
  import { SchedulerHost } from '@lunora/platform';
2
+ export { a as assertValidCronExpression, i as isValidCronExpression, w as warnIfSecondsLeading } from "./packem_shared/validate-cron-full.d-Bemx45E8.js";
2
3
  /**
3
- * Opaque reference to a Lunora function. Mirrors the `FunctionReference` shape
4
- * emitted by `@lunora/codegen` (and consumed by `@lunora/client`). We avoid a
5
- * direct dependency to keep this package usable from the codegen pipeline
6
- * itself.
4
+ * The generated function-reference type, shared by every package that needs to
5
+ * infer a call's args or return from `api.<file>.<fn>`.
7
6
  *
8
- * The runtime identifier lives in `__lunoraRef` — this MUST stay in lockstep
9
- * with the codegen emit + `@lunora/client`'s `FunctionReference`.
7
+ * This lives in `shared/` rather than in one package because the consumers span
8
+ * a dependency boundary they must not cross: `@lunora/scheduler` and
9
+ * `@lunora/workflow` accept a reference in `runAfter`/`runAt`/`step.run*` but
10
+ * cannot depend on `@lunora/client`, which is a browser package. Each of them
11
+ * previously hand-copied this declaration, and both copies silently rotted when
12
+ * the phantom carrier was renamed — the conditional matched an OPTIONAL property
13
+ * that no longer existed, so `ArgsOf<F>` quietly resolved to `unknown` and every
14
+ * `step.run(ref, args)` in the repo lost its arg checking without a single error.
15
+ *
16
+ * `shared/` is the repo's answer to exactly that shape: bundler-inlined,
17
+ * zero-dependency source imported by relative path, so it creates no runtime
18
+ * edge between the packages that inline it. Being ONE declaration, there is
19
+ * nothing to keep in lockstep and no drift test to write.
20
+ */
21
+ /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
22
+ type FunctionKind = "action" | "mutation" | "query" | "stream";
23
+ /**
24
+ * Opaque reference to a registered function emitted by `@lunora/codegen`.
25
+ *
26
+ * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
27
+ * Generated declarations decorate this with phantom type parameters so callers
28
+ * can infer args / return values per call site.
10
29
  */
11
- interface FunctionReference {
30
+ interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
31
+ /**
32
+ * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
33
+ * inference. Never present at runtime; declared as a covariant (output)
34
+ * position so a concrete reference stays assignable to a widened one.
35
+ */
36
+ readonly __lunoraPhantom?: {
37
+ args: Args;
38
+ kind: Kind;
39
+ returns: Return;
40
+ };
12
41
  readonly __lunoraRef: string;
13
- /** Marker phantom type — discriminates queries / mutations / actions. */
14
- readonly _kind?: "query" | "mutation" | "action";
15
42
  }
16
- type ArgsOf<F extends FunctionReference> = F extends {
17
- _args?: infer A;
18
- } ? A : Record<string, unknown>;
43
+ /** Extract the args type from a {@link FunctionReference}. */
44
+ type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
19
45
  /**
20
46
  * Typed reference to a Lunora durable workflow — either the generated
21
- * `workflows.&lt;name>` reference object (`_generated/api.ts`, which carries the
22
- * `WORKFLOW_*` binding + export name) or, structurally, a `defineWorkflow()`
47
+ * `workflows.<name>` reference object (`_generated/api.ts`, which carries the
48
+ * workflow's class name + export name) or, structurally, a `defineWorkflow()`
23
49
  * result imported directly. Both are matched by the `isLunoraWorkflow` brand and
24
50
  * carry the workflow's `params` in the phantom `__params`, so a `cronJobs()`
25
51
  * registration infers them.
@@ -36,25 +62,36 @@ type ArgsOf<F extends FunctionReference> = F extends {
36
62
  interface WorkflowReference<Params = Record<string, unknown>> {
37
63
  /** Phantom carrier for the workflow's `params` type — drives `cronJobs()` arg inference. Never read at runtime. */
38
64
  readonly __params?: Params;
39
- /** The `WORKFLOW_*` binding name (present on a generated `workflows.&lt;name>` ref). */
40
- readonly binding?: string;
65
+ /** The workflow's export key — its generated class name, reached as `ctx.exports.<className>` (present on a generated ref). */
66
+ readonly className?: string;
41
67
  readonly isLunoraWorkflow: true;
42
68
  /** The workflow's export/stable name (present on a generated ref; a `defineWorkflow({ name })` override otherwise). */
43
69
  readonly name?: string;
44
70
  }
71
+ /**
72
+ * A function reference a scheduler or workpool may target.
73
+ *
74
+ * `stream` is excluded deliberately, and the exclusion is load-bearing rather
75
+ * than tidiness: a scheduled job is dispatched as an ordinary `/rpc` call, and
76
+ * the function runner cannot execute a stream function (see
77
+ * `create-worker.ts`'s registry note). Accepting one compiles a job that is
78
+ * guaranteed to fail when its alarm fires, long after the call site that
79
+ * scheduled it.
80
+ */
81
+ type SchedulableReference<Args = unknown, Return = unknown> = FunctionReference<Exclude<FunctionKind, "stream">, Args, Return>;
45
82
  /** A cron job's target: either a one-shot function dispatch or a durable workflow start. */
46
- type CronTarget = FunctionReference | WorkflowReference;
83
+ type CronTarget = SchedulableReference | WorkflowReference;
47
84
  /** The arguments a cron's target accepts: a workflow's inferred `params`, else an open record (function args aren't inferred). */
48
85
  type CronTargetArgs<T extends CronTarget> = T extends WorkflowReference<infer Params> ? Params : Record<string, unknown>;
49
86
  /**
50
87
  * The arguments a one-shot schedule target ({@link Scheduler.runAfter} /
51
- * {@link Scheduler.runAt}) accepts. Unlike {@link CronTargetArgs} it preserves a
52
- * {@link FunctionReference}'s inferred `args` (via {@link ArgsOf}) as well as a
53
- * {@link WorkflowReference}'s inferred `params`, so scheduling a plain function
54
- * keeps its today's arg checking while scheduling a workflow/agent infers its
55
- * `params`.
88
+ * {@link Scheduler.runAt}) accepts. Unlike {@link CronTargetArgs} it resolves a
89
+ * {@link FunctionReference}'s `args` through {@link ArgsOf} as well as a
90
+ * {@link WorkflowReference}'s `params`, so scheduling a generated function
91
+ * reference is arg-checked against that function's validator while scheduling a
92
+ * workflow/agent is checked against its `params`.
56
93
  */
57
- type ScheduleTargetArgs<T extends CronTarget> = T extends WorkflowReference<infer Params> ? Params : T extends FunctionReference ? ArgsOf<T> : Record<string, unknown>;
94
+ type ScheduleTargetArgs<T extends CronTarget> = T extends WorkflowReference<infer Params> ? Params : T extends SchedulableReference ? ArgsOf<T> : Record<string, unknown>;
58
95
  /** Narrow a {@link CronTarget} to a {@link WorkflowReference} by its runtime brand. */
59
96
  declare const isWorkflowReference: (target: unknown) => target is WorkflowReference;
60
97
  /**
@@ -75,12 +112,62 @@ interface RetryPolicy {
75
112
  backoff?: "exponential" | "linear";
76
113
  /** Base delay in milliseconds for the first retry. Default `30_000`. */
77
114
  baseMs?: number;
78
- /** Maximum number of dispatch attempts before dead-lettering. Default `5`. */
115
+ /**
116
+ * Keep retrying failed deliveries instead of dead-lettering. Overrides
117
+ * `maxAttempts`, and logs once at `warn` at the attempt that would have
118
+ * dead-lettered. The delay between attempts is clamped to between 1 second
119
+ * and 30 minutes: the default backoff climbs to the 30-minute ceiling, but a
120
+ * caller-supplied `maxMs` below it keeps a job that never succeeds retrying
121
+ * that often.
122
+ *
123
+ * `cancel` applies once SchedulerDO has accepted the job. A job still in a
124
+ * shard's outbox custody (its mutation committed, the hand-off has not
125
+ * landed) is dropped from the shard's `dropOutboxEntry` admin RPC instead. A
126
+ * stored call the scheduler refuses as invalid is parked and logged rather
127
+ * than retried. Honoured by SchedulerDO; a `SchedulerHost` without unbounded
128
+ * retry, such as the Node one, refuses it.
129
+ */
130
+ forever?: boolean;
131
+ /**
132
+ * Maximum number of **retries** after the initial dispatch. Default `5`, so
133
+ * a job that keeps failing is dispatched 6 times in total before it is
134
+ * dead-lettered (the park happens once `attempts > maxAttempts`).
135
+ */
79
136
  maxAttempts?: number;
80
137
  /** Optional ceiling clamping the computed backoff delay. */
81
138
  maxMs?: number;
82
139
  }
83
140
  interface RunOptions {
141
+ /**
142
+ * Job id to store the record under, instead of one the SchedulerDO mints.
143
+ *
144
+ * Exists for `@lunora/server`'s deferred-schedule facade: inside a mutation a
145
+ * `runAfter`/`runAt` is buffered until the transaction commits, but the
146
+ * handler is handed the id synchronously, so the id has to be decided before
147
+ * the call is made. Callers that are not deferring should leave it unset and
148
+ * take the minted id from the return value. Anything that is not a plain
149
+ * `[A-Za-z0-9_-]` id of at most 64 characters, or that LEADS with `-`, is
150
+ * REFUSED (`400 INVALID_SCHEDULE_ID`) rather than replaced: the id is handed
151
+ * to `WorkflowBinding.create({ id })` verbatim for a workflow target, and the
152
+ * engine's instance-id grammar (`^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`) refuses that
153
+ * first character. Minting over it would mean two calls naming the same bad
154
+ * id ran the job twice instead of the second answering `409`.
155
+ *
156
+ * **Not an idempotency key.** An id that is already scheduled is REFUSED
157
+ * (`409 DUPLICATE_SCHEDULE_ID`), not replaced or de-duplicated: the time
158
+ * index is keyed by time as well as id, so an overwrite would fire the new
159
+ * job at the old job's instant and drop the slot it was actually scheduled
160
+ * for. Cancel the existing job first if you mean to reschedule it. The id
161
+ * is free again once the job has fired or been cancelled.
162
+ */
163
+ id?: string;
164
+ /**
165
+ * Cap for the {@link RunOptions.pool} this job joins, applied when the pool
166
+ * is first created and refreshed on every enqueue that carries one. Ignored
167
+ * without `pool`. A pool created by a `runAfter`/`runAt` that omits it caps
168
+ * at 1 — {@link Workpool} is the usual way to set it.
169
+ */
170
+ maxConcurrency?: number;
84
171
  /**
85
172
  * Logical workpool this job belongs to. When set, the SchedulerDO gates the
86
173
  * job behind the pool's `maxConcurrency` (see {@link WorkpoolOptions}).
@@ -103,6 +190,16 @@ interface ScheduleRecord {
103
190
  */
104
191
  attempts?: number;
105
192
  enqueuedAt: number;
193
+ /** Why the job was dead-lettered. Set only on a parked (`/dead`) record. */
194
+ error?: string;
195
+ /**
196
+ * The due time a pooled job had when its full pool first turned it away.
197
+ * Each backpressure re-arm moves {@link ScheduleRecord.scheduledFor}, so the
198
+ * dispatch reports this one as the job's due time and the lag metric counts
199
+ * the wait for a slot. Absent until the first re-arm; cleared by a retry,
200
+ * which measures its own attempt's lateness.
201
+ */
202
+ firstDueAt?: number;
106
203
  /**
107
204
  * The `ns:fn` path of the function to dispatch on fire. Absent when the job
108
205
  * targets a durable workflow/agent instead — see {@link ScheduleRecord.workflow}.
@@ -129,7 +226,7 @@ interface ScheduleRecord {
129
226
  scheduledFor: number;
130
227
  shardKey?: string;
131
228
  /**
132
- * The `WORKFLOW_*`/`AGENT_*` binding name to start a fresh durable instance
229
+ * The workflow/agent export key (its generated class name) to start a fresh durable instance
133
230
  * of on fire (the {@link ScheduleRecord.args} become its `params`). Set
134
231
  * instead of {@link ScheduleRecord.functionPath} when the job targets a
135
232
  * workflow/agent {@link WorkflowReference}. The runtime — not the DO — owns
@@ -137,6 +234,65 @@ interface ScheduleRecord {
137
234
  */
138
235
  workflow?: string;
139
236
  }
237
+ /**
238
+ * Where a job is in its life, as {@link Scheduler.get} reports it.
239
+ *
240
+ * - `pending` — waiting for its fire time, a pool slot, or a retry backoff.
241
+ * - `running` — its dispatch is in flight right now.
242
+ * - `succeeded` — the dispatch answered 2xx. For a function target the receiver
243
+ * answers only after the function returned, so this is the function's success;
244
+ * for a workflow/agent target it means the instance was STARTED, not finished —
245
+ * follow the instance (same id) for its outcome.
246
+ * - `failed` — the retry budget ran out and the job was dead-lettered
247
+ * ({@link Scheduler.dead}); `deadRetry` returns it to `pending`.
248
+ * - `canceled` — removed by {@link Scheduler.cancel}.
249
+ */
250
+ type ScheduledJobState = "canceled" | "failed" | "pending" | "running" | "succeeded";
251
+ /**
252
+ * A job as {@link Scheduler.get} sees it: the record plus its lifecycle state.
253
+ * Terminal states (`succeeded`, `canceled`, and a purged `failed`) are kept for
254
+ * a bounded retention window after `completedAt`, then answer `null`.
255
+ */
256
+ interface ScheduledJobView extends ScheduleRecord {
257
+ /** When the job reached its terminal state (epoch ms). Absent while `pending`/`running`. */
258
+ completedAt?: number;
259
+ state: ScheduledJobState;
260
+ }
261
+ /**
262
+ * How one cron fire ended. `skipped` is a tick that did not run: the previous
263
+ * run of the same cron was still in flight (`reason: "in-flight"`), or the
264
+ * deployment was paused (`reason: "paused"`).
265
+ */
266
+ type CronRunStatus = "failed" | "skipped" | "succeeded";
267
+ /** One recorded fire of a code-defined cron job (`cronJobs()`), as the SchedulerDO's `/cron/runs` reports it. */
268
+ interface CronRunRecord {
269
+ /** Run time in ms; `0` for a skipped tick. */
270
+ durationMs: number;
271
+ /** When the run finished, or when the tick was skipped (epoch ms). */
272
+ endedAt: number;
273
+ /** The thrown message of a `failed` run. */
274
+ error?: string;
275
+ /** The `cronJobs()` name. */
276
+ name: string;
277
+ /** Why a tick was `skipped`: the previous run still held the lease, or the deployment was paused. */
278
+ reason?: "in-flight" | "paused";
279
+ runId: string;
280
+ /** Ticks of the same cron skipped while this run held the lease; on a `skipped` row, the consecutive ticks it stands for. */
281
+ skipped: number;
282
+ /** When the run began, or the first tick of a `skipped` row's streak (epoch ms). */
283
+ startedAt: number;
284
+ status: CronRunStatus;
285
+ }
286
+ /** A cron run that holds its lease right now. */
287
+ interface CronRunInFlight {
288
+ name: string;
289
+ /** When the run last said it was still alive; the lease lapses fifteen minutes after this, or after `startedAt` when it never did. */
290
+ renewedAt?: number;
291
+ runId: string;
292
+ /** Ticks skipped so far because this run was still going. */
293
+ skipped: number;
294
+ startedAt: number;
295
+ }
140
296
  interface Scheduler {
141
297
  cancel: (id: string) => Promise<{
142
298
  cancelled: boolean;
@@ -154,27 +310,39 @@ interface Scheduler {
154
310
  * recover is a no-op rather than an error.
155
311
  */
156
312
  deadRetry: (id: string) => Promise<boolean>;
157
- /** Resolve a single pending job by id, or `null` when absent (derived from {@link Scheduler.list}). */
158
- get: (id: string) => Promise<ScheduleRecord | null>;
313
+ /**
314
+ * Resolve a job by id with its lifecycle {@link ScheduledJobView.state} —
315
+ * pending, running, or (for a bounded retention window) its terminal outcome.
316
+ * `null` when the id was never scheduled or its terminal record has expired.
317
+ */
318
+ get: (id: string) => Promise<ScheduledJobView | null>;
159
319
  /** All pending scheduled jobs (the DO's `/list` view). */
160
320
  list: () => Promise<ScheduleRecord[]>;
161
321
  /**
162
322
  * Schedule `target` to run once, `delayMs` from now. `target` is a function
163
323
  * {@link FunctionReference} (dispatched as a one-shot) or a durable
164
- * {@link WorkflowReference} — the generated `workflows.&lt;name>` /
165
- * `agents.&lt;name>` ref — which starts a fresh instance on fire (args become
324
+ * {@link WorkflowReference} — the generated `workflows.<name>` /
325
+ * `agents.<name>` ref — which starts a fresh instance on fire (args become
166
326
  * its `params`). {@link ScheduleTargetArgs} infers the accepted args from
167
327
  * whichever target was passed.
328
+ *
329
+ * **Resolves the job id, a bare string** — the same value `cancel`/`get`
330
+ * take, and the same value the `ctx.scheduler` surface promises. This object
331
+ * IS `ctx.scheduler` on the shard side (codegen installs it behind
332
+ * `SchedulerLike`, whose `runAfter`/`runAt` are declared `Promise<string>`),
333
+ * so resolving a `{ id, scheduledFor }` record here handed mutations an
334
+ * object where every other gate — `@lunora/server`'s `Scheduler`,
335
+ * `@lunora/shard-engine`'s `SchedulerLike`, `@lunora/runtime`'s httpAction
336
+ * ctx, and the docs — said string. Nothing caught it, because the install is
337
+ * a cast: apps wrote the object into a string column and `cancel(id)`
338
+ * answered `{ cancelled: false }` with no error anywhere.
339
+ *
340
+ * The fire instant is not lost: `runAt` was handed it, and a caller that
341
+ * needs it back reads `scheduledFor` off {@link Scheduler.get}.
168
342
  */
169
- runAfter: <T extends CronTarget>(delayMs: number, target: T, args: ScheduleTargetArgs<T>, options?: RunOptions) => Promise<{
170
- id: string;
171
- scheduledFor: number;
172
- }>;
173
- /** Like {@link Scheduler.runAfter} but fires at an absolute `date`/timestamp. */
174
- runAt: <T extends CronTarget>(date: Date | number, target: T, args: ScheduleTargetArgs<T>, options?: RunOptions) => Promise<{
175
- id: string;
176
- scheduledFor: number;
177
- }>;
343
+ runAfter: <T extends CronTarget>(delayMs: number, target: T, args: ScheduleTargetArgs<T>, options?: RunOptions) => Promise<string>;
344
+ /** Like {@link Scheduler.runAfter} but fires at an absolute `date`/timestamp. Resolves the job id. */
345
+ runAt: <T extends CronTarget>(date: Date | number, target: T, args: ScheduleTargetArgs<T>, options?: RunOptions) => Promise<string>;
178
346
  }
179
347
  /**
180
348
  * Cloudflare Durable Object data-residency jurisdiction. Widening union —
@@ -208,13 +376,21 @@ interface LunoraSchedulerOptions {
208
376
  * un-pinned global namespace.
209
377
  */
210
378
  jurisdiction?: DurableObjectJurisdiction;
211
- /** Binding to the `SchedulerDO` durable object namespace. */
379
+ /**
380
+ * Binding to the `SchedulerDO` durable object namespace.
381
+ *
382
+ * The origin the DO dispatches back to is NOT passed here: it reads
383
+ * `env.LUNORA_ORIGIN_URL` off its own binding at fire time, because a
384
+ * caller-supplied dispatch target would be an SSRF vector.
385
+ */
212
386
  namespace: DurableObjectNamespaceLike;
213
387
  /**
214
- * Origin where the Worker is mounted. SchedulerDO uses this base URL when
215
- * dispatching scheduled functions back to the Worker on alarm fire.
388
+ * The instance that holds the deployment's pause flag and the registry of
389
+ * named instances: the worker's `schedulerInstanceName`. Default `default`.
390
+ * A named instance registers there the first time it is addressed, so a
391
+ * pause reaches it and an instance created during a pause starts paused.
216
392
  */
217
- originUrl: string;
393
+ primaryInstanceName?: string;
218
394
  }
219
395
  /** Per-enqueue options for a {@link Workpool}. Extends {@link RunOptions} minus the implicit `pool` (the pool sets that). */
220
396
  interface EnqueueOptions {
@@ -227,7 +403,7 @@ interface EnqueueOptions {
227
403
  }
228
404
  /**
229
405
  * Options for `createWorkpool`. Mirrors {@link LunoraSchedulerOptions}
230
- * (same `namespace` / `originUrl` / `instanceName`) plus the bounded-concurrency
406
+ * (same `namespace` / `instanceName`) plus the bounded-concurrency
231
407
  * controls. A workpool is a NAMED logical pool inside the existing SchedulerDO —
232
408
  * it needs no extra Durable Object or wrangler binding beyond the SchedulerDO
233
409
  * the scheduler already uses.
@@ -241,7 +417,7 @@ interface WorkpoolOptions extends LunoraSchedulerOptions {
241
417
  maxConcurrency: number;
242
418
  /**
243
419
  * Pool name — the concurrency counter is keyed by this inside the
244
- * SchedulerDO storage (`pool:&lt;name>`). Default `default`.
420
+ * SchedulerDO storage (`pool:<name>`). Default `default`.
245
421
  */
246
422
  name?: string;
247
423
  }
@@ -261,11 +437,11 @@ interface Workpool {
261
437
  * and the time it was scheduled for (it may not run immediately if the pool
262
438
  * is at capacity).
263
439
  */
264
- enqueue: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: EnqueueOptions) => Promise<{
440
+ enqueue: <F extends SchedulableReference>(function_: F, args: ArgsOf<F>, options?: EnqueueOptions) => Promise<{
265
441
  id: string;
266
442
  scheduledFor: number;
267
443
  }>;
268
- /** The pool's name (the `pool:&lt;name>` storage key suffix). */
444
+ /** The pool's name (the `pool:<name>` storage key suffix). */
269
445
  readonly name: string;
270
446
  /** Inspect the pool's current state — `inFlight` slots used and the configured `maxConcurrency`. */
271
447
  status: () => Promise<{
@@ -316,6 +492,13 @@ interface MessageBatchLike<Body = unknown> {
316
492
  }
317
493
  /** The wire payload Lunora puts on the queue: a function dispatch. */
318
494
  interface QueueJob {
495
+ /**
496
+ * The call's arguments in WIRE form (`packages/wire/src/wire-codec`), so a `bigint`,
497
+ * `Date` or bytes survives the queue's own JSON serialisation. The producers
498
+ * encode; the shard's dispatch loop is the single decoder. A custom
499
+ * {@link QueueDispatch} must forward this untouched — decoding it here and
500
+ * letting the shard decode again flattens a `Date` to `{}`.
501
+ */
319
502
  args?: Record<string, unknown>;
320
503
  functionPath: string;
321
504
  /** Routing hint forwarded to the Worker so the call lands on the right shard. */
@@ -341,7 +524,7 @@ interface QueueWorkpoolOptions {
341
524
  */
342
525
  interface QueueWorkpool {
343
526
  /** Enqueue a single `fn(args)` dispatch. */
344
- enqueue: <F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: QueueEnqueueOptions) => Promise<void>;
527
+ enqueue: <F extends SchedulableReference>(function_: F, args: ArgsOf<F>, options?: QueueEnqueueOptions) => Promise<void>;
345
528
  /** Enqueue many dispatches in one `sendBatch`. Each job names its function `ref`. */
346
529
  enqueueBatch: (jobs: ReadonlyArray<{
347
530
  args?: Record<string, unknown>;
@@ -349,12 +532,40 @@ interface QueueWorkpool {
349
532
  shardKey?: string;
350
533
  }>, options?: QueueSendOptionsLike) => Promise<void>;
351
534
  }
352
- /** Dispatches a single {@link QueueJob} — the consumer's per-message worker. */
353
- type QueueDispatch = (job: QueueJob) => Promise<void>;
535
+ /**
536
+ * Dispatches a single {@link QueueJob} — the consumer's per-message worker.
537
+ * `messageId` is the queue message's native id, threaded through so the
538
+ * dispatcher can attribute a failure to the exact message that caused it.
539
+ */
540
+ type QueueDispatch = (job: QueueJob, messageId?: string) => Promise<void>;
354
541
  /** Options for `createQueueConsumer`. */
355
542
  interface QueueConsumerOptions {
356
543
  /** How each job is executed; e.g. the `httpDispatcher`. */
357
544
  dispatch: QueueDispatch;
545
+ /**
546
+ * The consumer's `max_retries` as deployed in `wrangler.jsonc`, which a
547
+ * consumer cannot read at runtime. Used only to recognise a message's last
548
+ * delivery, where a declined dispatch is re-enqueued through `requeue` (or
549
+ * logged as the drop or dead-letter it becomes without one). Defaults to
550
+ * Cloudflare's default of 3.
551
+ */
552
+ maxRetries?: number;
553
+ /**
554
+ * Re-enqueue a job whose dispatch is declined on its last delivery as a
555
+ * copy delayed past the in-flight claim, with a fresh retry budget, instead
556
+ * of letting it be dead-lettered or dropped while its call is still
557
+ * running. Without it that loss is only logged.
558
+ *
559
+ * `queue` is the producer binding of the queue this consumer reads (the
560
+ * one handed to `createQueueWorkpool`). `secret` keys the MAC the copy
561
+ * carries — pass the admin token (`LUNORA_ADMIN_TOKEN`). The copy
562
+ * dispatches under the replaced message's id so the shard serves the
563
+ * declined call's result, and without a valid MAC no body can claim an id.
564
+ */
565
+ requeue?: {
566
+ queue: QueueLike<QueueJob>;
567
+ secret: string;
568
+ };
358
569
  }
359
570
  /** Options for the `httpDispatcher` — the default HTTP dispatcher. */
360
571
  interface HttpDispatcherOptions {
@@ -364,6 +575,13 @@ interface HttpDispatcherOptions {
364
575
  fetchImpl?: typeof fetch;
365
576
  /** Origin where the Worker is mounted (the `/_lunora/scheduler/dispatch` endpoint). */
366
577
  originUrl: string;
578
+ /**
579
+ * Abort a job's dispatch after this many ms; the abort is retryable, so the
580
+ * consumer retries the message. Defaults to 5 minutes — raise it for a
581
+ * workpool running jobs that legitimately run longer, lower it to fail a
582
+ * stuck origin faster.
583
+ */
584
+ timeoutMs?: number;
367
585
  }
368
586
  /**
369
587
  * Client-side scheduler — forwards `runAfter` / `runAt` / `cancel` calls to a
@@ -374,9 +592,9 @@ declare const createScheduler: (options: LunoraSchedulerOptions) => Scheduler;
374
592
  /**
375
593
  * Bounded-concurrency action queue — the Lunora equivalent of
376
594
  * `@convex-dev/workpool`. Mirrors `createScheduler`'s `namespace` /
377
- * `originUrl` / `instanceName` options and is built on the SAME `SchedulerDO`:
595
+ * `instanceName` options and is built on the SAME `SchedulerDO`:
378
596
  * a workpool is just a NAMED logical pool inside that DO (concurrency counter
379
- * keyed by {@link WorkpoolOptions.name} under the `pool:&lt;name>` storage key).
597
+ * keyed by {@link WorkpoolOptions.name} under the `pool:<name>` storage key).
380
598
  * It needs no extra Durable Object or wrangler binding beyond the SchedulerDO
381
599
  * the scheduler already uses.
382
600
  *
@@ -384,8 +602,24 @@ declare const createScheduler: (options: LunoraSchedulerOptions) => Scheduler;
384
602
  * `maxConcurrency` of the pool's jobs at once and queues the rest durably,
385
603
  * draining them as the runtime reports completions (`POST /complete`).
386
604
  *
605
+ * The ceiling the platform adds: one alarm drain keeps at most SIX dispatches in
606
+ * flight, because a Durable Object may have only six connections simultaneously
607
+ * waiting for response headers. A `maxConcurrency` above six is therefore not
608
+ * wrong, just not reachable within a single drain — the surplus drains on the
609
+ * following alarms. The same invocation is bounded by the 15-minute alarm wall
610
+ * clock, which covers the WHOLE drain rather than one job; work that does not
611
+ * fit is deferred to the next alarm, never dropped.
612
+ *
613
+ * For jobs that are individually long — an LLM call, an export, a payment
614
+ * round-trip — prefer `createQueueWorkpool`: the dispatch this DO awaits
615
+ * only returns once the function has finished running, so a long job occupies
616
+ * one of those six slots and one slice of that 15-minute budget for its whole
617
+ * duration. A Queues consumer gets a fresh Worker invocation per batch, with its
618
+ * own connection budget and its own clock, and its `max_concurrency` is not
619
+ * capped at six. You give up the hard cap, per-job cancel, and per-job status.
620
+ *
387
621
  * ```ts
388
- * const pool = createWorkpool({ namespace: env.SCHEDULER, originUrl, maxConcurrency: 5 });
622
+ * const pool = createWorkpool({ namespace: env.SCHEDULER, maxConcurrency: 5 });
389
623
  * await pool.enqueue(internal.stripe.sync, { invoiceId }, { retry: { maxAttempts: 3 } });
390
624
  * ```
391
625
  *
@@ -429,8 +663,18 @@ interface CronTriggerSnippet {
429
663
  declare const createCronTrigger: (options: CronTriggerOptions) => CronTriggerSnippet;
430
664
  /** Sub-day recurrence. Exactly one unit must be provided. */
431
665
  interface IntervalSchedule {
666
+ /** 1–23, and must divide 24 (an interval repeats *within* a day). */
432
667
  hours?: number;
668
+ /** 1–59, and must divide 60. */
433
669
  minutes?: number;
670
+ /**
671
+ * Accepted by the type, **rejected at definition time**: Cloudflare Cron
672
+ * Triggers have a one-minute floor, so the 6-field expression this compiles
673
+ * to would survive codegen and land in the committed `wrangler.jsonc`, then
674
+ * fail at `wrangler deploy` naming neither the job nor the file. Declared so
675
+ * the rejection can name the job instead. Use `ctx.scheduler.runAfter`/
676
+ * `runAt` for sub-minute recurrence, or `{ minutes: 1 }`.
677
+ */
434
678
  seconds?: number;
435
679
  }
436
680
  /** Daily recurrence at a fixed UTC wall-clock time. */
@@ -484,7 +728,7 @@ interface CronJob {
484
728
  * Set when the job targets a durable workflow rather than a function: the
485
729
  * workflow's stable name (`defineWorkflow({ name })`) when one was declared,
486
730
  * otherwise `""`. `@lunora/codegen` statically resolves the concrete
487
- * `lunora/workflows.ts` export + its `WORKFLOW_*` binding for the emitted
731
+ * `lunora/workflows.ts` export + its class name for the emitted
488
732
  * dispatch map, so this authoring-time value is informational only.
489
733
  */
490
734
  workflow?: string;
@@ -509,22 +753,22 @@ declare const compileCronSchedule: (kind: CronScheduleKind, schedule: DailySched
509
753
  */
510
754
  interface CronJobsBuilder {
511
755
  /**
512
- * Raw cron expression escape hatch (5- or 6-field, full cron-parser grammar).
756
+ * Raw cron expression escape hatch (5- or 6-field, full `@visulima/cron-parser` Cloudflare grammar).
513
757
  * The target may be a function (`internal.file.fn`) or a durable workflow
514
- * (`workflows.&lt;name>`); a workflow's `args` are inferred from its `params`.
758
+ * (`workflows.<name>`); a workflow's `args` are inferred from its `params`.
515
759
  */
516
760
  cron: <T extends CronTarget>(name: string, cronExpr: string, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
517
- /** Daily at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.&lt;name>`). */
761
+ /** Daily at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.<name>`). */
518
762
  daily: <T extends CronTarget>(name: string, schedule: DailySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
519
- /** Hourly at `minuteUTC` past the hour. The target may be a function or a durable workflow (`workflows.&lt;name>`). */
763
+ /** Hourly at `minuteUTC` past the hour. The target may be a function or a durable workflow (`workflows.<name>`). */
520
764
  hourly: <T extends CronTarget>(name: string, schedule: HourlySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
521
- /** Every `{ seconds | minutes | hours }`. The target may be a function or a durable workflow (`workflows.&lt;name>`). */
765
+ /** Every `{ minutes | hours }` — `{ seconds }` throws (Cron Triggers have a one-minute floor). The target may be a function or a durable workflow (`workflows.<name>`). */
522
766
  interval: <T extends CronTarget>(name: string, schedule: IntervalSchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
523
767
  /** Snapshot of the registered jobs, in declaration order. */
524
768
  jobs: () => ReadonlyArray<CronJob>;
525
- /** Monthly on `day` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.&lt;name>`). */
769
+ /** Monthly on `day` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.<name>`). */
526
770
  monthly: <T extends CronTarget>(name: string, schedule: MonthlySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
527
- /** Weekly on `dayOfWeek` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.&lt;name>`). */
771
+ /** Weekly on `dayOfWeek` at `hourUTC:minuteUTC` (UTC). The target may be a function or a durable workflow (`workflows.<name>`). */
528
772
  weekly: <T extends CronTarget>(name: string, schedule: WeeklySchedule, target: T, args?: CronTargetArgs<T>) => CronJobsBuilder;
529
773
  }
530
774
  /**
@@ -550,12 +794,49 @@ declare const createQueueWorkpool: (options: QueueWorkpoolOptions) => QueueWorkp
550
794
  */
551
795
  declare const createQueueConsumer: (options: QueueConsumerOptions) => ((batch: MessageBatchLike) => Promise<void>);
552
796
  /**
553
- * Default {@link QueueDispatch}: POST each job to the Worker's
797
+ * Default {@link QueueDispatch}: dispatch each job to the Worker's
554
798
  * `/_lunora/scheduler/dispatch` endpoint (the same path SchedulerDO dispatches
555
- * through), authenticated with the admin bearer. A non-2xx response throws so
556
- * the consumer retries the message.
799
+ * through) via `@lunora/dispatch`'s `createDispatchRunner` — which bounds each
800
+ * job with {@link HttpDispatcherOptions.timeoutMs} (default
801
+ * {@link DEFAULT_JOB_TIMEOUT_MS}), so a hung origin no longer holds the whole
802
+ * `queue()` invocation open, and threads the queue message id through for
803
+ * failure attribution. Any dispatch failure throws so the consumer retries the
804
+ * message — including a 2xx carrying a non-empty non-JSON body, which is an
805
+ * intermediary's page rather than a function's return value and therefore no
806
+ * evidence the job ran. An empty 2xx is a normal success (a `void` function).
807
+ *
808
+ * `job.args` is forwarded VERBATIM: {@link encodeJobArgs} already put it in wire
809
+ * form at the producer, and the shard's dispatch loop is the single decoder.
810
+ * Encoding again here would leave the handler a tagged array.
557
811
  */
558
812
  declare const httpDispatcher: (options: HttpDispatcherOptions) => QueueDispatch;
813
+ /**
814
+ * The id a new record is stored under: the caller's, or a freshly minted one when
815
+ * they did not name it.
816
+ *
817
+ * A caller id that is not a safe key segment is REFUSED, not replaced.
818
+ * `RunOptions.id` is not an idempotency key — an id already scheduled answers
819
+ * `409 DUPLICATE_SCHEDULE_ID` — so quietly swapping an invalid one for a random
820
+ * id made `runAt(ts, ref, args, { id: "-daily-2026-09-06" })` mint a fresh id on
821
+ * every call and run the job once per call, where naming it was the caller's way
822
+ * of saying "at most once".
823
+ *
824
+ * Minting swaps a leading `-` for `_` rather than re-rolling: 1 in 64 minted ids
825
+ * led with one and was refused by the workflow engine on dispatch. `_` is in the
826
+ * engine's leading class, the swap is a single pass, and 96 random bits stay 96
827
+ * random bits everywhere but that first character.
828
+ *
829
+ * Exported because two surfaces have to agree on it. The SchedulerDO applies it
830
+ * when the record is written (turning the refusal into a `400`);
831
+ * `@lunora/server`'s deferred-schedule facade applies it when the call is
832
+ * BUFFERED, because it answers the handler with the id synchronously — long
833
+ * before the DO sees the request. Restating the rule in the facade is how the two
834
+ * drift: an id the facade accepted and the DO replaced leaves the handler holding
835
+ * an id no job was ever stored under, so its later `cancel` silently misses.
836
+ * @param requested the caller's `RunOptions.id`, if any
837
+ * @throws LunoraError `INVALID_SCHEDULE_ID` when `requested` is supplied and is not a safe key segment
838
+ */
839
+ declare const resolveScheduleId: (requested: unknown) => string;
559
840
  /**
560
841
  * Minimal projection of `DurableObjectState` for the SchedulerDO. Declared
561
842
  * structurally so unit tests can pass a fake state without booting the
@@ -586,6 +867,7 @@ interface SchedulerDOState {
586
867
  end?: string;
587
868
  limit?: number;
588
869
  prefix?: string;
870
+ startAfter?: string;
589
871
  }) => Promise<Map<string, T>>;
590
872
  put: <T = unknown>(entries: Record<string, T> | string, value?: T) => Promise<void>;
591
873
  setAlarm: (scheduledTime: number | Date) => Promise<void> | void;
@@ -596,23 +878,47 @@ interface SchedulerEnv {
596
878
  /**
597
879
  * Fallback bearer token attached to the dispatch when
598
880
  * {@link SchedulerEnv.LUNORA_SCHEDULER_SECRET} is not configured. Sent as
599
- * `authorization: Bearer &lt;token>`.
881
+ * `authorization: Bearer <token>`.
600
882
  */
601
883
  LUNORA_ADMIN_TOKEN?: string;
602
884
  /**
603
885
  * Base URL where the Worker is mounted. SchedulerDO uses this at dispatch
604
886
  * time to call back into the Worker. Read at fire time (NOT taken from the
605
- * request body) to prevent SSRF via a forged `originUrl` field.
887
+ * request body, which carries no dispatch target at all) to prevent SSRF.
606
888
  */
607
889
  LUNORA_ORIGIN_URL?: string;
608
890
  /**
609
- * Shared secret used to HMAC-sign the dispatch body so the runtime receiver
610
- * can authenticate the call (header `x-lunora-scheduler-signature`). Without
891
+ * Shared secret used to HMAC-sign each dispatch so the runtime receiver can
892
+ * authenticate the call (header `x-lunora-scheduler-signature`). The signature
893
+ * covers the body, the send time (`x-lunora-scheduler-timestamp`) and the
894
+ * forwarded identity headers, via the shared `schedulerDispatchCanonical`. Without
611
895
  * it the dispatch is sent unsigned (optionally bearer-authenticated via
612
896
  * {@link SchedulerEnv.LUNORA_ADMIN_TOKEN}).
613
897
  */
614
898
  LUNORA_SCHEDULER_SECRET?: string;
615
899
  }
900
+ /**
901
+ * Retries allowed after the original attempt before {@link SchedulerDO.recordRetry}
902
+ * parks a record in the dead-letter (`dead:`) prefix. Overridable per job via
903
+ * {@link RetryPolicy.maxAttempts}. Exported so test doubles of the scheduler
904
+ * (`@lunora/testing`'s fake scheduler) model the same budget instead of
905
+ * duplicating the number.
906
+ */
907
+ declare const MAX_RETRY_ATTEMPTS = 5;
908
+ /**
909
+ * Backoff before the first retry, in milliseconds; doubles on each subsequent
910
+ * retry under the default `"exponential"` backoff (`baseMs * 2 ** (attempts - 1)`).
911
+ * Overridable per job via {@link RetryPolicy.baseMs}. Exported alongside
912
+ * {@link MAX_RETRY_ATTEMPTS} for the same reason.
913
+ */
914
+ declare const RETRY_BASE_DELAY_MS = 3e4;
915
+ /**
916
+ * How long a terminal (`succeeded` / `canceled` / purged `failed`) record keeps
917
+ * answering `/get` and `/history` after it settled. Expiry is enforced on read,
918
+ * so the window holds even when no alarm runs to sweep; the sweep only reclaims
919
+ * the storage.
920
+ */
921
+ declare const TERMINAL_RETENTION_MS = 6048e5;
616
922
  /**
617
923
  * One pool's live backlog, as surfaced by `GET /status`. `inFlight`/
618
924
  * `maxConcurrency` mirror the durable {@link PoolState} semaphore; `queued`
@@ -623,7 +929,7 @@ interface SchedulerPoolStatus {
623
929
  inFlight: number;
624
930
  /** The pool's concurrency cap. */
625
931
  maxConcurrency: number;
626
- /** The logical workpool name (the `pool:&lt;name>` suffix). */
932
+ /** The logical workpool name (the `pool:<name>` suffix). */
627
933
  name: string;
628
934
  /** Pending jobs routed to this pool but not yet dispatched. */
629
935
  queued: number;
@@ -638,13 +944,21 @@ interface SchedulerStatus {
638
944
  backlog: number;
639
945
  /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
640
946
  inFlight: number;
641
- /** Per-pool backlog breakdown, one entry per `pool:&lt;name>` record. */
947
+ /** Per-pool backlog breakdown, one entry per `pool:<name>` record. */
642
948
  pools: SchedulerPoolStatus[];
643
949
  }
950
+ /** Whether the deployment is paused, as `GET /pause` answers it. */
951
+ interface DeploymentPauseState {
952
+ paused: boolean;
953
+ /** When the pause began (epoch ms). */
954
+ pausedAt?: number;
955
+ /** The operator's note, shown wherever the pause is. */
956
+ reason?: string;
957
+ }
644
958
  /**
645
959
  * Durable Object that stores pending scheduled invocations sorted by their
646
960
  * `scheduledFor` time and fires them via HTTP on alarm. Storage layout:
647
- * `id:&lt;id>` maps to {@link ScheduleRecord}; `t:&lt;paddedTime>:&lt;id>` maps to the
961
+ * `id:<id>` maps to {@link ScheduleRecord}; `t:<paddedTime>:<id>` maps to the
648
962
  * id (used as a sorted index).
649
963
  *
650
964
  * On every mutation the DO recomputes the earliest pending task and updates
@@ -652,13 +966,32 @@ interface SchedulerStatus {
652
966
  */
653
967
  declare class SchedulerDO {
654
968
  private static indexKey;
969
+ private static terminalIndexKey;
970
+ /** A cron run row's key: newest end first under its job's prefix. */
971
+ private static cronRunKey;
972
+ /** Whether `lease` still holds: its newest sign of life is within {@link DISPATCH_LEASE_MS}. */
973
+ private static leaseIsLive;
974
+ /** A cron job name off an untrusted body, or `undefined` when absent or implausible. */
975
+ private static cronName;
976
+ /** The record's `pq:` row key, or `undefined` for a job outside any pool. */
977
+ private static poolQueueKey;
978
+ /**
979
+ * The rows that make `record` a pending job — its header, plus its `pq:` row
980
+ * when pooled — ready to spread into one multi-key `put`, so the two can
981
+ * never disagree.
982
+ */
983
+ private static pendingRows;
984
+ /** The header key plus the `pq:` row key, to spread into the same multi-key `delete`. */
985
+ private static pendingKeys;
655
986
  private static json;
656
987
  private static error;
657
988
  /**
658
989
  * Resolve the effective retry parameters for a record: its per-job
659
990
  * {@link RetryPolicy} merged over the DO's built-in defaults. Callers that
660
991
  * never set `record.retry` get today's behaviour verbatim
661
- * (`maxAttempts: 5`, exponential, `baseMs: 30_000`, no ceiling).
992
+ * (`maxAttempts: 5`, exponential, `baseMs: 30_000`, no ceiling). A
993
+ * `forever` policy has its delay clamped into
994
+ * [{@link FOREVER_RETRY_MIN_DELAY_MS}, {@link FOREVER_RETRY_MAX_DELAY_MS}].
662
995
  */
663
996
  private static resolveRetry;
664
997
  /** Clamp an untrusted `maxConcurrency` to a positive integer, else fall back. */
@@ -691,15 +1024,66 @@ declare class SchedulerDO {
691
1024
  /**
692
1025
  * Normalize the mutually-exclusive dispatch target off an untrusted body: a
693
1026
  * one-shot function path (`functionPath`) or a durable workflow/agent
694
- * instance (`workflow`, a `WORKFLOW_*`/`AGENT_*` binding). Returns `undefined`
1027
+ * instance (`workflow`, a workflow/agent export key). Returns `undefined`
695
1028
  * when neither is present so the caller can reject the schedule.
696
1029
  */
697
1030
  private static resolveScheduleTarget;
698
1031
  protected readonly state: SchedulerDOState;
699
1032
  protected readonly env: SchedulerEnv;
1033
+ /**
1034
+ * This instance's one run of {@link SchedulerDO.reindexOrphanedRecords},
1035
+ * shared by every caller so none proceeds before it settles. Once is enough:
1036
+ * an orphan can only be minted by an eviction, and an eviction ends the
1037
+ * instance that minted it. A rejection is surfaced to the first caller only.
1038
+ */
1039
+ private recovery;
1040
+ /** Whether {@link SchedulerDO.recovery} completed, so this instance may vouch for the store via {@link CLEAN_KEY}. */
1041
+ private recovered;
1042
+ /**
1043
+ * Set when a swallowed storage failure may have left a header with no `t:`
1044
+ * entry in THIS instance (see `drainRecordGuarded`). Sticky: the instance
1045
+ * then never writes {@link CLEAN_KEY} back, so its successor runs the walk.
1046
+ */
1047
+ private dirty;
1048
+ /**
1049
+ * Tail of the serialized `pool:<name>` critical section — see
1050
+ * the pool lock (`withPoolLock`). Per-instance, which is the right scope: the pool rows
1051
+ * live in this Durable Object's own storage and only this instance writes
1052
+ * them.
1053
+ */
1054
+ private poolLock;
1055
+ /**
1056
+ * Record id → the `t:` index key its in-flight claim currently holds, for
1057
+ * every dispatch this instance has open. See `drainRecordGuarded()`.
1058
+ *
1059
+ * A lease moves a record's index entry without rewriting its `scheduledFor`,
1060
+ * so while a claim is held the live key is NOT the one derivable from the
1061
+ * record. Anything that has to remove such a record — `removeRecord()`, on
1062
+ * the `/cancel` path — would otherwise delete a key that no longer exists
1063
+ * and strand the real one.
1064
+ *
1065
+ * In-memory and per-instance on purpose: it answers "is THIS instance
1066
+ * dispatching that record right now", which is exactly when the divergence
1067
+ * can be observed by another request. A lease left behind by an instance that
1068
+ * died has no live dispatch to protect and is reconciled from storage
1069
+ * instead — `alarm()` drops it as a dangling entry once the header is gone.
1070
+ */
1071
+ private readonly activeLeases;
1072
+ /**
1073
+ * Ids `/cancel` removed while this instance held their dispatch lease.
1074
+ *
1075
+ * The attempt is already in flight when such a cancel lands, and whatever it
1076
+ * settles to must not write the job back: `recordRetry()` and
1077
+ * `requeuePooled()` re-create the `id:` header and a `t:` entry, so a
1078
+ * failed attempt would resurrect a job `/cancel` answered `{ cancelled: true }`
1079
+ * for, and it would fire again. Both check this set synchronously right
1080
+ * before their single write, so no `/cancel` can land between the check and
1081
+ * the write. Cleared with the lease in `drainRecordGuarded()`.
1082
+ */
1083
+ private readonly cancelledLeases;
700
1084
  constructor(state: SchedulerDOState, env: SchedulerEnv);
701
1085
  fetch(request: Request): Promise<Response>;
702
- /** Called by the Workers runtime when the alarm previously set by `_rescheduleAlarm()` fires. */
1086
+ /** Called by the Workers runtime when the alarm previously set by `rescheduleAlarm()` fires. */
703
1087
  alarm(): Promise<void>;
704
1088
  /**
705
1089
  * Internal dispatch hook; overridden in unit tests to capture the outgoing
@@ -712,13 +1096,18 @@ declare class SchedulerDO {
712
1096
  * drop. After {@link MAX_RETRY_ATTEMPTS} the record is parked under a
713
1097
  * `dead:` key for inspection — never silently deleted.
714
1098
  *
1099
+ * One non-2xx is told apart: a `409` carrying `DISPATCH_IN_PROGRESS` returns
1100
+ * `"in-progress"`. The shard is saying the first attempt of this very record
1101
+ * is still running, so {@link recordRetry} re-arms it without charging an
1102
+ * attempt — see there.
1103
+ *
715
1104
  * The dispatch target is taken from `env.LUNORA_ORIGIN_URL` (NOT from the
716
- * stored record) to prevent SSRF via a forged `originUrl` on the schedule
717
- * request. If that env var is missing at fire time (a deploy/binding
1105
+ * stored record) so a schedule request can never name where the DO calls
1106
+ * back — that would be SSRF. If that env var is missing at fire time (a deploy/binding
718
1107
  * regression — schedule time already enforced its presence) we return
719
1108
  * `false` so the record is retried rather than silently dropped.
720
1109
  */
721
- protected dispatch(record: ScheduleRecord): Promise<boolean>;
1110
+ protected dispatch(record: ScheduleRecord): Promise<boolean | "in-progress">;
722
1111
  /**
723
1112
  * Register the hibernation-safe ping/pong keepalive. The runtime answers a
724
1113
  * {@link WS_KEEPALIVE_PING} text frame with {@link WS_KEEPALIVE_PONG}
@@ -733,24 +1122,93 @@ declare class SchedulerDO {
733
1122
  * in the unit harness and on older runtimes, where it degrades to a no-op.
734
1123
  */
735
1124
  private armWebSocketKeepalive;
1125
+ /**
1126
+ * Drain the due slice with up to {@link MAX_CONCURRENT_DISPATCHES} records in
1127
+ * flight at once, so a slow job delays only its own lane instead of every
1128
+ * other due job in the app (see the constant for why the drain used to
1129
+ * serialise whole jobs, not just their kicks).
1130
+ *
1131
+ * Lanes pull from the head of the slice, so records still ENTER dispatch in
1132
+ * the slice's order — the same `t:<paddedTime>:<id>` order the sequential
1133
+ * drain used. What is no longer implied is that they FINISH in that order,
1134
+ * which was never a guarantee worth relying on anyway: two jobs due at the
1135
+ * same instant already ran in storage-key (id) order rather than arrival
1136
+ * order, a saturated pooled job is pushed {@link POOL_BACKPRESSURE_DELAY_MS}
1137
+ * into the future ahead of its queue-mates, and a failed job re-enters at the
1138
+ * end of a backoff. Nothing in the public surface documents an ordering
1139
+ * guarantee; jobs that must be ordered must chain themselves.
1140
+ *
1141
+ * {@link drainRecordGuarded} swallows every throw, so no lane can reject and
1142
+ * abandon its siblings.
1143
+ */
1144
+ private drainDue;
1145
+ /**
1146
+ * Run `critical` with exclusive access to the `pool:<name>` rows.
1147
+ *
1148
+ * Every pool mutation is a read-modify-write (`loadPool` → mutate →
1149
+ * `savePool`), and the two halves are separated by an `await`. That was safe
1150
+ * while the drain ran one record at a time — the Durable Object input gate
1151
+ * keeps a foreign event (a concurrent `/complete`) out while a storage
1152
+ * operation is in flight, and nothing else in this instance could interleave.
1153
+ * Concurrent lanes break exactly that assumption: lane A and lane B can both
1154
+ * issue their `get` before either `put` lands, both observe `inFlight: 0`,
1155
+ * and the second `put` then erases the first lane's reservation — the pool
1156
+ * oversubscribes and one holder's id is lost, so its slot is never released.
1157
+ *
1158
+ * The lock is a promise chain rather than anything cleverer because the
1159
+ * critical section is two local storage ops with no I/O in it. It is held
1160
+ * across NO outbound fetch: `dispatch()` runs outside it, which is the whole
1161
+ * point of draining concurrently.
1162
+ *
1163
+ * The chain is rebuilt from a swallowed copy so one rejecting section can
1164
+ * never wedge every later one.
1165
+ */
1166
+ private withPoolLock;
736
1167
  /**
737
1168
  * Claim + drain one due record with per-record fault isolation, so a storage
738
1169
  * throw can never abort the whole alarm pass (which would skip the remaining
739
1170
  * due records and the `rescheduleAlarm()` that re-arms the clock).
740
1171
  *
741
- * Claims the job by deleting its time-index entry BEFORE dispatch (an alarm
742
- * re-fire then won't pick it up again), runs {@link drainRecord}, and on a
743
- * thrown storage op re-asserts the claim so the job stays re-fireable.
1172
+ * The claim is a LEASE, not a deletion. The record's `t:` entry is moved
1173
+ * from its due time to `now + DISPATCH_LEASE_MS` before
1174
+ * {@link SchedulerDO.dispatch} is called, so this alarm pass (and the next)
1175
+ * will not pick it up again, while the record is never left WITHOUT an index
1176
+ * entry. That distinction is the whole point: deleting the entry outright
1177
+ * made an instance evicted mid-dispatch leave an `id:` header with no index,
1178
+ * which {@link SchedulerDO.reindexOrphanedRecords} re-armed and the
1179
+ * successor fired AGAIN on sight — concurrently with an attempt that could
1180
+ * still be running at the origin. A leased record is not an orphan, so the
1181
+ * successor leaves it alone until the lease lapses; see
1182
+ * {@link DISPATCH_LEASE_MS} for why that horizon is fifteen minutes and what
1183
+ * it does and does not bound.
1184
+ *
1185
+ * The lease is released as soon as this instance knows the attempt settled —
1186
+ * dispatched, re-armed for retry, backpressured, or dead-lettered — so the
1187
+ * horizon only ever governs the one case nobody is left to report: a lost
1188
+ * instance.
744
1189
  *
745
1190
  * A throw reaching here always means the job was NOT dispatched:
746
1191
  * {@link drainRecord} swallows its own post-dispatch cleanup errors and
747
1192
  * returns instead of throwing once a kick succeeds, so every escaping throw
748
- * comes from the pre-dispatch or failed-dispatch paths. We therefore always
749
- * re-assert the time-index claim so a later alarm re-attempts it
750
- * (at-least-once): the claim delete may have removed it and
751
- * recordRetry()/requeuePooled() may not have re-armed it before throwing, and
752
- * re-inserting the same key is idempotent, so a surviving claim is simply
753
- * rewritten to its prior value.
1193
+ * comes from the pre-dispatch or failed-dispatch paths. Nothing is in flight,
1194
+ * so the lease is dropped and the due-time claim re-asserted — keeping the
1195
+ * job re-fireable on the very next alarm (at-least-once) rather than letting
1196
+ * a transient storage blip cost it a whole lease.
1197
+ *
1198
+ * With one exception, checked first: a record that already has a durable
1199
+ * `dead:` row is TERMINAL, and re-claiming it would re-dispatch a job the
1200
+ * dead-letter says is finished. See the comment on that branch.
1201
+ *
1202
+ * `claimKey` is the index key `alarm()` SELECTED this record under, passed
1203
+ * down rather than recomputed. That is load-bearing, not tidiness: a lease
1204
+ * moves the record's index entry and deliberately does NOT rewrite its
1205
+ * `scheduledFor` (that field is the job's real due time, which `/list`,
1206
+ * `/get`, `/dead` and the studio all show, and which `parkDead` preserves).
1207
+ * So from the moment a lease is taken the live key and the key derivable
1208
+ * from the record disagree — and a claim that recomputed it would delete a
1209
+ * key that no longer exists while adding a second one, leaving the record
1210
+ * indexed twice and dispatched twice. That is the same double-run the lease
1211
+ * exists to close, re-entering through the expiry path.
754
1212
  */
755
1213
  private drainRecordGuarded;
756
1214
  /**
@@ -781,12 +1239,15 @@ declare class SchedulerDO {
781
1239
  * always return `true` without touching any pool state.
782
1240
  *
783
1241
  * The pool row is read FRESH from storage on every call — never cached
784
- * across the drain. Each reservation durably `savePool()`s before the next
785
- * record runs, so a same-pass reservation is still visible to the next
786
- * record's fresh read (the budget carries forward); and because dispatch()
787
- * awaits an outbound fetch between records, a concurrent /complete that
788
- * decrements the row mid-drain IS reflected here instead of being clobbered
789
- * by a stale in-memory copy (which would leak a slot permanently).
1242
+ * across the drain — and the read-modify-write runs under
1243
+ * the pool lock (`withPoolLock`). Both halves are load-bearing. Freshness is what
1244
+ * keeps a concurrent `/complete` landing during a dispatch from being
1245
+ * clobbered by a stale in-memory copy (which would leak a slot permanently: a
1246
+ * POOL SLOT has no expiry, unlike the dispatch claim's). The lock is what
1247
+ * keeps two drain lanes from both reading the same pre-reservation row and
1248
+ * both believing a slot was free — without it the pool oversubscribes past
1249
+ * `maxConcurrency` and one holder's id is dropped from `inFlightIds`, so its
1250
+ * slot is never released.
790
1251
  */
791
1252
  private reservePoolSlot;
792
1253
  /**
@@ -798,18 +1259,38 @@ declare class SchedulerDO {
798
1259
  */
799
1260
  private handleWebSocketUpgrade;
800
1261
  /**
801
- * Re-list the jobs and push them to every connected subscriber. Called after
802
- * any change (schedule / cancel / alarm-fire) so live studios reflect it
803
- * immediately. A no-op when the runtime doesn't support hibernated sockets.
1262
+ * Re-list the jobs (bounded — see {@link listPage}) and push them to
1263
+ * every connected subscriber. Called after any change (schedule / cancel /
1264
+ * alarm-fire) so live studios reflect it immediately. A no-op when the
1265
+ * runtime doesn't support hibernated sockets.
804
1266
  */
805
1267
  private broadcastChange;
806
- /** The current pending job records (shared by `/list` and the live channel). */
807
- private listRecords;
808
1268
  /**
809
- * HMAC-SHA-256 sign the dispatch body with `env.LUNORA_SCHEDULER_SECRET`,
810
- * returning a base64url signature, or `undefined` when no secret is
811
- * configured. Mirrors `@lunora/storage`'s signed-URL HMAC pattern (WebCrypto
812
- * `crypto.subtle`, available in workerd).
1269
+ * One bounded page of the rows under `prefix`, in key order, plus the
1270
+ * `cursor` a caller resumes from (the last key of the page) when `truncated`.
1271
+ * Lists `limit + 1` and slices back down so both facts are known without a
1272
+ * second round-trip.
1273
+ *
1274
+ * Shared by `/list` (pending headers) and `/dead` (dead-letter records) so
1275
+ * NEITHER can materialize an unbounded set into one JSON response: nothing
1276
+ * prunes `dead:`, so a workpool with a broken origin parks thousands of rows
1277
+ * and the studio's only view of them — and only way to requeue them — would
1278
+ * fail exactly when it is needed.
1279
+ */
1280
+ private listPage;
1281
+ /**
1282
+ * Page through every row under `prefix` exactly once with bounded per-page
1283
+ * memory (a `limit`+`startAfter` cursor loop), invoking `visit` for each.
1284
+ * Unlike {@link listPage}, which intentionally truncates for the studio's
1285
+ * live view, `/status` and `/pool` need EXACT counts — this walks the full
1286
+ * set, but never materializes more than one page at a time.
1287
+ */
1288
+ private forEachPage;
1289
+ /**
1290
+ * HMAC-SHA-256 sign a dispatch with `env.LUNORA_SCHEDULER_SECRET`, returning a
1291
+ * base64url signature, or `undefined` when no secret is configured. The signed
1292
+ * string is the shared `schedulerDispatchCanonical`, which the receiver rebuilds
1293
+ * from the body, the timestamp and the forwarded identity headers.
813
1294
  */
814
1295
  private signDispatch;
815
1296
  /**
@@ -817,9 +1298,36 @@ declare class SchedulerDO {
817
1298
  * The retry budget/backoff comes from the record's {@link RetryPolicy}
818
1299
  * (falling back to the DO defaults); on exhaustion the record is parked
819
1300
  * under a `dead:` key for manual inspection.
1301
+ *
1302
+ * **A `DISPATCH_IN_PROGRESS` decline (`inProgress`) is not charged.** It
1303
+ * means the record's first attempt is still running on the shard, not that
1304
+ * anything failed; charging it would spend the budget while that attempt is
1305
+ * doing the work, and if it then failed the job would dead-letter having
1306
+ * run once. It still re-arms at the backoff of the NEXT charged attempt, at
1307
+ * least {@link RETRY_BASE_DELAY_MS} apart — nothing else rate-limits an
1308
+ * uncharged retry, and polling a running attempt faster gains nothing.
1309
+ *
1310
+ * It is bounded, not forever, only because the shard's claim is: a claim
1311
+ * older than the shard's fifteen-minute ceiling is treated as stale and the
1312
+ * next delivery runs (and is charged as usual if it fails). A handler that
1313
+ * hangs therefore costs at most that long in declines before the ordinary
1314
+ * budget applies again. Without that ceiling, not charging would let one hung
1315
+ * handler keep its record retrying and never dead-letter.
1316
+ *
1317
+ * A {@link RetryPolicy.forever} record never parks on its budget. Its
1318
+ * attempt count saturates at `Number.MAX_SAFE_INTEGER` so the stored count
1319
+ * and the backoff exponent stay finite; the delay ceiling in
1320
+ * {@link SchedulerDO.resolveRetry} is what keeps the backoff indexable.
820
1321
  */
821
1322
  private recordRetry;
822
- /** Read the durable `pool:&lt;name>` row, defaulting to a fresh `inFlight: 0` pool. */
1323
+ /**
1324
+ * Terminal park into the dead-letter (`dead:`) prefix, with `reason` naming
1325
+ * why in the emitted warning. Shared by the two ways a retry ends for good:
1326
+ * an exhausted attempt budget, and a backoff that ran past the largest
1327
+ * schedulable time (see {@link isIndexableTime}).
1328
+ */
1329
+ private parkDead;
1330
+ /** Read the durable `pool:<name>` row, defaulting to a fresh `inFlight: 0` pool. */
823
1331
  private loadPool;
824
1332
  private savePool;
825
1333
  /**
@@ -841,28 +1349,72 @@ declare class SchedulerDO {
841
1349
  private handlePoolStatus;
842
1350
  /**
843
1351
  * `GET /status` — the app-level backlog signal that powers the studio's
844
- * SLO view. Enumerates every durable `pool:&lt;name>` row for its `inFlight`/
1352
+ * SLO view. Enumerates every durable `pool:<name>` row for its `inFlight`/
845
1353
  * `maxConcurrency` semaphore, counts the pending (not-yet-dispatched) jobs
846
- * routed to each pool with the same single-pass scan {@link handlePoolStatus}
847
- * uses, and rolls those up into app-wide `backlog` (sum of `queued`) and
848
- * `inFlight` (sum of held slots) totals.
1354
+ * routed to each pool from its `pq:` rows, and rolls those up into app-wide
1355
+ * `backlog` (sum of `queued`) and `inFlight` (sum of held slots) totals.
849
1356
  *
850
1357
  * Pools that have rows but no queued jobs still appear (with `queued: 0`) so
851
1358
  * a saturated-but-idle pool stays visible; a pool that only ever existed as
852
1359
  * queued jobs without a persisted row is unreachable here (the schedule path
853
- * always writes a `pool:&lt;name>` row before the job's header), so a single
854
- * scan over `pool:`/`id:` is sufficient.
1360
+ * always writes a `pool:<name>` row before the job's header), so a single
1361
+ * scan over `pool:` plus a cursor loop over `pq:` is sufficient.
855
1362
  */
856
1363
  private handleStatus;
1364
+ /**
1365
+ * Persist (or refresh) a pool's concurrency cap, so the alarm-time gate has
1366
+ * a durable `maxConcurrency` even after the enqueuing client is gone.
1367
+ */
1368
+ private persistPoolCap;
1369
+ /**
1370
+ * The `409` a caller-supplied id earns when something durable already holds
1371
+ * it, or `undefined` when the id is free.
1372
+ *
1373
+ * A pending header is the obvious half: `put` on `id:<id>` overwrites, but
1374
+ * the `t:` index is keyed by TIME as well as id, so the OLD entry survives.
1375
+ * The drain then dispatches the NEW record at the OLD time and deletes the
1376
+ * entry it should have fired at — the job runs early and never runs again.
1377
+ * Refused rather than made a replace: `RunOptions.id` exists so a deferred
1378
+ * schedule can name its own job, and silently retiming someone else's is the
1379
+ * worse failure.
1380
+ *
1381
+ * The `dead:` row holds the id too, and for a worse reason. A dead record
1382
+ * keeps NO `id:` header, so a pending-only check leaves the id apparently
1383
+ * free — and a later `/dead/retry` writes the revived corpse straight over
1384
+ * the new job's header and adds a SECOND time index under the same id. The
1385
+ * new job is gone and the dead one fires in its place. Recovering a dead job
1386
+ * is an operator action taken minutes or days after the schedule, so nothing
1387
+ * at schedule time would ever have surfaced the collision.
1388
+ */
1389
+ private idConflict;
1390
+ /**
1391
+ * The id the record is stored under, or the `Response` refusing it.
1392
+ *
1393
+ * A caller id that is not a safe key segment is refused with a `400` rather
1394
+ * than minted over: `RunOptions.id` is not an idempotency key, so swapping an
1395
+ * invalid one for a random id made two calls naming it schedule two jobs
1396
+ * where the second should have answered `409`.
1397
+ *
1398
+ * Only an id the CALLER chose can collide — a minted one is 96 random bits —
1399
+ * so {@link idConflict} costs two `get`s on the deferred path and nothing on
1400
+ * the ordinary one.
1401
+ */
1402
+ private resolveId;
857
1403
  private handleSchedule;
858
1404
  private handleCancel;
1405
+ /**
1406
+ * `GET /list[?cursor=]` — one bounded page of pending jobs. `truncated` says
1407
+ * whether more rows follow and `cursor` is what a caller passes back to get
1408
+ * them (`createScheduler.list()` walks every page; the studio shows one).
1409
+ */
859
1410
  private handleList;
860
1411
  /**
861
1412
  * `GET /dead` — list the dead-letter records: jobs that exhausted their
862
- * retry budget ({@link recordRetry}) and were parked under `dead:&lt;id>`
1413
+ * retry budget ({@link recordRetry}) and were parked under `dead:<id>`
863
1414
  * instead of being silently dropped. These never appear in `/list` (their
864
1415
  * `id:` header is deleted on park), so this is the ONLY way the studio can
865
- * surface — and recover — a permanently-failed job.
1416
+ * surface — and recover — a permanently-failed job. Bounded and cursored
1417
+ * like `/list`: nothing prunes `dead:`, so this set grows without limit.
866
1418
  */
867
1419
  private handleDeadList;
868
1420
  /**
@@ -880,12 +1432,133 @@ declare class SchedulerDO {
880
1432
  */
881
1433
  private handleDeadCancel;
882
1434
  /**
883
- * Resolve a single pending job by id via a direct `id:&lt;id>` storage read —
884
- * O(1), versus scanning the whole `/list` view. Responds `{ record }` on a
885
- * hit and `{}` on a miss (an absent `record` field — JSON has no `undefined`
886
- * — which the client reads back as `null`).
1435
+ * `GET /get?id=` — one job with its lifecycle state, in O(1) reads. Responds
1436
+ * `{ record }` on a hit and `{}` on a miss (JSON has no `undefined`; the
1437
+ * client reads it back as `null`).
1438
+ *
1439
+ * The terminal row is read FIRST: a successful dispatch writes it before
1440
+ * clearing the header, so a header that outlived a swallowed cleanup still
1441
+ * reads as `succeeded`. A reused id cannot hit a stale terminal row, because
1442
+ * `/schedule` deletes it. `running` is this instance's own lease set — the
1443
+ * only instance that can be dispatching — so a lease orphaned by an eviction
1444
+ * reads as `pending`, which is what it is until the lease lapses.
887
1445
  */
888
1446
  private handleGet;
1447
+ /**
1448
+ * `GET /history[?cursor=]` — one bounded page of finished jobs, newest first,
1449
+ * within the retention window. Paged off the `dt:` index, then each page's
1450
+ * rows are read; an index entry whose row was replaced (id reuse) or has
1451
+ * expired is skipped rather than shown.
1452
+ */
1453
+ private handleHistory;
1454
+ /**
1455
+ * The unexpired terminal row for `id`, or `undefined`. With `indexKey`, only
1456
+ * the row that index entry was written for — a newer outcome under the same
1457
+ * id has its own entry.
1458
+ */
1459
+ private readTerminal;
1460
+ /** A parked job as an outcome row, when it was parked with its failure time. */
1461
+ private readParked;
1462
+ /**
1463
+ * Rewrite the `canceled` outcome `/cancel` wrote for `record` to `succeeded`,
1464
+ * because the dispatch it raced went through. Only while that row is still
1465
+ * this record's and no new job has reused the id; the reads and the write
1466
+ * await no I/O in between, so the input gate keeps `/schedule` out.
1467
+ */
1468
+ private correctCanceledToSucceeded;
1469
+ /** Record how `record` ended: its `done:` row and `dt:` index entry, in one put. */
1470
+ private writeTerminal;
1471
+ /**
1472
+ * Reclaim terminal rows past {@link TERMINAL_RETENTION_MS}, in up to
1473
+ * {@link TERMINAL_SWEEP_PASSES} batches — enough to outpace one full drain's
1474
+ * worth of new outcomes, so a steady load cannot outgrow the sweep. Runs on
1475
+ * every alarm and after a cancel or purge, the paths that write outcomes.
1476
+ */
1477
+ private sweepTerminal;
1478
+ /**
1479
+ * Reclaim one batch and answer how many index entries it held. The index is
1480
+ * newest-first, so every expired entry sorts after the horizon key. A `done:`
1481
+ * row is deleted only when THIS entry is its index — an id reused since owns
1482
+ * a newer row with its own entry.
1483
+ */
1484
+ private sweepTerminalBatch;
1485
+ private pauseState;
1486
+ private isPaused;
1487
+ /**
1488
+ * `POST /instances/register { name }` — record a named scheduler instance, on
1489
+ * the instance that holds the pause flag, and answer the pause state it was
1490
+ * recorded under. The write and the read sit in one handler, so a pause
1491
+ * either lands first (and the new instance is told) or after (and its
1492
+ * fan-out lists the new instance). Idempotent.
1493
+ */
1494
+ private handleRegisterInstance;
1495
+ /** `GET /instances` — every registered instance name, for the pause fan-out. */
1496
+ private handleListInstances;
1497
+ /**
1498
+ * `POST /pause { paused, reason? }` — pause or resume the deployment.
1499
+ * Pausing stops the alarm (see `alarm()`); resuming re-derives it from the
1500
+ * time index, so every job held while paused fires on the next alarm, late
1501
+ * but with its attempt budget intact. Idempotent both ways; re-pausing keeps
1502
+ * the original `pausedAt`.
1503
+ */
1504
+ private handleSetPause;
1505
+ /**
1506
+ * `POST /cron/begin { name }` — take the in-flight lease for one cron job, or
1507
+ * answer `{ acquired: false }` and record the tick as skipped when a run of
1508
+ * the same job still holds it.
1509
+ *
1510
+ * The lease lives here rather than in the worker because Cloudflare delivers
1511
+ * cron triggers to whichever isolate it likes: module state cannot see a run
1512
+ * in another isolate, and this Durable Object is the one place every fire of
1513
+ * an app passes through. The check and the write are atomic for the same
1514
+ * reason every read-modify-write in this class is: the input gate keeps any
1515
+ * other request out while a storage operation is pending, and nothing between
1516
+ * them awaits I/O.
1517
+ *
1518
+ * A lease with no sign of life (its start, or its last `/cron/renew`) within
1519
+ * {@link DISPATCH_LEASE_MS} is treated as lost: the run was torn down or its
1520
+ * worker died. The lost run is recorded as failed rather than vanishing.
1521
+ */
1522
+ private handleCronBegin;
1523
+ /**
1524
+ * `POST /cron/renew { name, runId }` — a running cron job says it is still
1525
+ * alive, which restarts the {@link DISPATCH_LEASE_MS} window. The ceiling
1526
+ * assumes a `scheduled()` invocation is torn down at fifteen minutes; a run
1527
+ * with no such bound (a manual run from Studio, a host that does not enforce
1528
+ * it) renews instead of being declared lost while it works.
1529
+ *
1530
+ * Only the run that holds the lease, and only while it is still live, can
1531
+ * extend it. A lapsed lease may already have been recorded as lost or taken
1532
+ * over, and reviving it would give two runs the lease.
1533
+ */
1534
+ private handleCronRenew;
1535
+ /**
1536
+ * `POST /cron/end { name, runId, status, error? }` — release the lease and
1537
+ * record the run. A `runId` that no longer holds the lease (its lease expired
1538
+ * and was already recorded as lost) is ignored, so a late report cannot
1539
+ * record the same run twice or free a successor's lease.
1540
+ */
1541
+ private handleCronEnd;
1542
+ /**
1543
+ * `GET /cron/runs` — every cron job's in-flight lease and recorded runs,
1544
+ * newest end first per job. Bounded by {@link CRON_HISTORY_LIMIT} rows per job
1545
+ * and by the app's own `cronJobs()` declarations.
1546
+ */
1547
+ private handleCronRuns;
1548
+ /** Record a run whose lease lapsed without a `/cron/end`. */
1549
+ private recordLostCronRun;
1550
+ /**
1551
+ * Record a skipped tick, folded into the newest row when that row is a skip
1552
+ * for the same reason. Otherwise a long run or a long pause would write one
1553
+ * row per tick and push every real run out of the {@link CRON_HISTORY_LIMIT}.
1554
+ */
1555
+ private recordCronSkip;
1556
+ /**
1557
+ * Write one run row and drop that job's rows past {@link CRON_HISTORY_LIMIT}.
1558
+ * Keyed newest END first, so a run is the newest row the moment it is
1559
+ * recorded, however many ticks were skipped while it held the lease.
1560
+ */
1561
+ private recordCronRun;
889
1562
  private removeRecord;
890
1563
  /**
891
1564
  * Arm the alarm for `scheduledFor` only if it is sooner than the currently
@@ -894,6 +1567,80 @@ declare class SchedulerDO {
894
1567
  * full `t:` rescan is unnecessary unless the new job is the new earliest.
895
1568
  */
896
1569
  private armAlarmIfEarlier;
1570
+ /**
1571
+ * Re-index every pending job whose time-index entry is gone, and fire it now.
1572
+ *
1573
+ * A record with an `id:` header but no `t:` entry is invisible to every
1574
+ * clock in this class: {@link SchedulerDO.rescheduleAlarm} derives the alarm
1575
+ * from `t:` alone, and `alarm()`'s inline reconciliation only handles the
1576
+ * INVERSE orphan (a `t:` entry whose header is gone). Left alone such a job
1577
+ * sits in `/list` and `/status.backlog` forever — never fires, never reaches
1578
+ * `/dead`.
1579
+ *
1580
+ * **This is no longer how a lost dispatch looks.**
1581
+ * {@link SchedulerDO.drainRecordGuarded} used to claim a record by deleting
1582
+ * its `t:` entry outright, so an instance evicted mid-dispatch minted an
1583
+ * orphan on every claimed record and this method re-fired each of them ON
1584
+ * SIGHT — concurrently with attempts that could still have been running at
1585
+ * the origin. The claim is a lease now (see {@link DISPATCH_LEASE_MS}): a
1586
+ * claimed record keeps a `t:` entry at the lease horizon, so it is not an
1587
+ * orphan, is not recovered here, and is re-fired by the ordinary alarm drain
1588
+ * only once the lease lapses.
1589
+ *
1590
+ * What still reaches this method is the residue of a storage failure — a
1591
+ * claim released with no lease written, or a pre-lease record written by an
1592
+ * older build — where nothing was dispatched and firing immediately is
1593
+ * exactly right.
1594
+ *
1595
+ * The dispatch is deduplicated by the record id, which the receiver spends
1596
+ * as `x-lunora-mutation-id` for a function target and as the workflow
1597
+ * INSTANCE id for a `workflow` target. A mutation's dedup read runs inside
1598
+ * the shard's single-writer gate, so a mutation is exactly-once even under a
1599
+ * genuinely concurrent re-fire; a workflow re-attaches to the running
1600
+ * instance rather than starting a second one. An ACTION takes no gate —
1601
+ * gating one would let any caller freeze a whole shard for the length of an
1602
+ * action's outbound I/O — and its dedup row is written only after the
1603
+ * handler returns, so the cache alone could not tell "already ran" from
1604
+ * "still running". The shard closes that itself (#803): it claims the dedup
1605
+ * key before entering the handler and answers a second delivery of a live
1606
+ * key `409 DISPATCH_IN_PROGRESS`, which is a non-2xx, so the record is
1607
+ * re-armed rather than cleared.
1608
+ *
1609
+ * Bounded walks (all `t:` values, `pq:` rows, then all `id:` headers) rather
1610
+ * than a per-header `get`, so the cost is one pass over each prefix.
1611
+ *
1612
+ * **The walk runs only when {@link CLEAN_KEY} is absent.** It is O(every
1613
+ * pending job), and an instance is evicted between alarms spaced wider than the
1614
+ * idle timeout, so it must not run on every new instance. The key is sufficient because
1615
+ * every remaining way to mint an orphan sits inside an alarm drain: the
1616
+ * schedule, dead-retry, retry and requeue writes each put header and index in
1617
+ * ONE call, and cancel deletes them in one. `alarm()` deletes the key before
1618
+ * a non-empty drain and writes it back only after the drain settled with no
1619
+ * swallowed failure ({@link dirty}) in an instance whose own recovery
1620
+ * finished — so an instance that dies mid-drain, or swallowed a failed
1621
+ * index write, leaves the key absent and its successor walks. A store from
1622
+ * an older build has no key and is walked once. The no-clock check at the
1623
+ * end is cheap and runs on every new instance regardless.
1624
+ */
1625
+ private reindexOrphanedRecords;
1626
+ /** One run of {@link reindexOrphanedRecords}. */
1627
+ private recoverStore;
1628
+ /**
1629
+ * Write back the outcome a failed write lost, then drop the marker and any
1630
+ * header the job left behind. Skipped when a newer outcome already exists
1631
+ * (the id was reused and finished again); the marker goes either way.
1632
+ */
1633
+ private restoreOutcome;
1634
+ /** The full orphan walk — see {@link reindexOrphanedRecords}. */
1635
+ private reindexWalk;
1636
+ /**
1637
+ * The time component of the earliest pending `t:` entry, or `undefined` when
1638
+ * there is no pending entry at all. Reads exactly one row — the index's
1639
+ * lexical order is its numeric order. A present-but-unreadable key yields
1640
+ * `NaN`, which callers must distinguish from "nothing pending": the two
1641
+ * answers mean opposite things for the alarm.
1642
+ */
1643
+ private earliestPendingTime;
897
1644
  private rescheduleAlarm;
898
1645
  }
899
1646
  /** What the Cloudflare scheduler host needs from the Worker's environment. */
@@ -908,14 +1655,14 @@ interface SchedulerHostOptions {
908
1655
  * the worker's own jurisdiction so scheduled state co-resides with app data.
909
1656
  */
910
1657
  jurisdiction?: "eu" | "fedramp" | "us";
911
- /** The `SchedulerDO` namespace binding. */
912
- namespace: Parameters<typeof createScheduler>[0]["namespace"];
913
1658
  /**
914
- * Public origin the Worker is mounted at. `SchedulerDO` dispatches back to
915
- * this base URL when an alarm fires, so a wrong value means jobs fire into
916
- * nothing.
1659
+ * The `SchedulerDO` namespace binding.
1660
+ *
1661
+ * The origin the DO dispatches back to is not configured here — it reads
1662
+ * `env.LUNORA_ORIGIN_URL` off its own binding at fire time, so a wrong value
1663
+ * there (or none) is what makes jobs fire into nothing.
917
1664
  */
918
- originUrl: string;
1665
+ namespace: Parameters<typeof createScheduler>[0]["namespace"];
919
1666
  }
920
1667
  /**
921
1668
  * Build the Cloudflare {@link SchedulerHost}.
@@ -923,31 +1670,49 @@ interface SchedulerHostOptions {
923
1670
  * The returned host has no `cron` member — see the module docstring.
924
1671
  */
925
1672
  declare const createSchedulerHost: (options: SchedulerHostOptions) => SchedulerHost;
926
- /** Standard cron expression (5- or 6-field) or a supported `@macro`, per `cron-parser`. */
927
- declare const isValidCronExpression: (schedule: string) => boolean;
928
- /**
929
- * A 6-field (seconds-leading) cron expression is legal generic cron grammar
930
- * but not a Cloudflare Cron Trigger — the platform only understands the
931
- * 5-field, minute-granularity form and rejects the rest at `wrangler deploy`
932
- * with a message naming neither the job nor the file. Warn here instead of
933
- * staying silent, without throwing: unlike the ergonomic `.interval()` form,
934
- * the raw `.cron()` escape hatch is meant to accept cron grammar this module
935
- * doesn't otherwise second-guess.
1673
+ /**
1674
+ * Reject a `delayMs` a scheduler cannot act on, before it reaches the
1675
+ * SchedulerDO.
1676
+ *
1677
+ * A `NaN`/`Infinity` delay serializes to `null` through JSON and lands as a
1678
+ * malformed `scheduledFor`; a negative one schedules into the past. Both are the
1679
+ * caller's argument, so the answer has to name the argument — which is why the
1680
+ * code is `INVALID_INPUT` (400) and not `INTERNAL`: `toErrorBody` replaces an
1681
+ * internal-coded message with "Internal error", redacting the one sentence that
1682
+ * says what to fix.
936
1683
  *
937
- * Exported (not module-private) because it is the ONE place this advisory is
938
- * written: the runtime `cronJobs()` builder reaches it via
939
- * {@link assertValidCronExpression}, and `@lunora/codegen`'s static
940
- * `discover-crons.ts` calls it directly after its own `isValidCronExpression`
941
- * check — so a hand-authored 6-field `.cron()` warns whether it's discovered
942
- * from source at build time or registered at runtime, with one shared message.
943
- */
944
- declare const warnIfSecondsLeading: (schedule: string, context: string) => void;
945
- /**
946
- * Assert a raw cron expression is well-formed, throwing the same shaped error
947
- * both cron surfaces use. The `context` prefix lets callers name the offending
948
- * job (`cron job "send digest"`) vs. the bare trigger. Well-formed but
949
- * Cloudflare-incompatible (6-field) expressions pass but log a warning — see
950
- * {@link warnIfSecondsLeading}.
951
- */
952
- declare const assertValidCronExpression: (schedule: string, context?: string) => void;
953
- export { type ArgsOf, CRON_SCHEDULE_KINDS, type CronJob, type CronJobsBuilder, type CronScheduleKind, type CronTarget, type CronTriggerOptions, type CronTriggerSnippet, type DailySchedule, type DurableObjectIdLike, type DurableObjectJurisdiction, type DurableObjectNamespaceLike, type DurableObjectStubLike, type EnqueueOptions, type FunctionReference, type HourlySchedule, type HttpDispatcherOptions, type IntervalSchedule, type LunoraSchedulerOptions, type MessageBatchLike, type MonthlySchedule, type QueueConsumerOptions, type QueueDispatch, type QueueEnqueueOptions, type QueueJob, type QueueLike, type QueueMessageLike, type QueueSendOptionsLike, type QueueSendRequestLike, type QueueWorkpool, type QueueWorkpoolOptions, type RetryPolicy, type RunOptions, type ScheduleRecord, type Scheduler, SchedulerDO, type SchedulerDOState, type SchedulerEnv, type SchedulerHostOptions, type SchedulerPoolStatus, type SchedulerStatus, type WeeklySchedule, type WorkflowReference, type Workpool, type WorkpoolOptions, assertValidCronExpression, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isValidCronExpression, isWorkflowReference, warnIfSecondsLeading };
1684
+ * Exported because four surfaces enforce it — `createScheduler().runAfter`,
1685
+ * `createWorkpool().enqueue`, `@lunora/server`'s deferred-schedule facade (which
1686
+ * must reject BEFORE the transaction commits, not at flush time) and
1687
+ * `@lunora/testing`'s fake scheduler. They used to restate it and threw three
1688
+ * different codes between them, so a test written against the harness caught one
1689
+ * code while production threw another.
1690
+ * @param delayMs the delay to validate
1691
+ * @param surface what to name in the message — the call the delay was passed to (e.g. `"ctx.scheduler.runAfter"`)
1692
+ * @param argument the caller's argument to name in the message; `runAt` converts its absolute `date` to a delay and passes that name through so the answer points at what was actually written
1693
+ */
1694
+ declare const assertScheduleDelay: (delayMs: number, surface: string, argument?: string) => void;
1695
+ /**
1696
+ * Reject a `runAt` instant a scheduler cannot act on — {@link assertScheduleDelay}'s
1697
+ * bound, restated for the absolute form by converting the instant to the delay it
1698
+ * implies.
1699
+ *
1700
+ * `runAfter` has refused a `NaN`/`Infinity` argument since the guard was written;
1701
+ * `runAt` took the same value through a different door and let it reach the DO,
1702
+ * where it serializes to `null` through JSON and lands as a `scheduledFor` no
1703
+ * alarm can ever fire. `new Date("2026-13-01")`, `runAt(row.dueAt + delay)` on a
1704
+ * row whose `dueAt` is absent — both arrive here as a number that is not one.
1705
+ *
1706
+ * An instant already in the PAST is not refused. It is an overdue job
1707
+ * (`runAt(row.dueAt)` on a row that came due while the request was in flight),
1708
+ * and `runAfter` itself reaches `runAt` a fraction of a millisecond after
1709
+ * capturing its own clock reading — so a strict sign check would fail the
1710
+ * documented `runAfter(0, …)` call at random. The delay is therefore clamped at
1711
+ * zero while it is still a finite number, which leaves the half that matters:
1712
+ * a value that is not a number at all.
1713
+ * @param timestampMs the absolute instant (epoch ms) the caller passed
1714
+ * @param nowMs the clock to measure it against — the wall clock in production, the harness's virtual clock in a test
1715
+ * @param surface what to name in the message — the call the instant was passed to (e.g. `"ctx.scheduler.runAt"`)
1716
+ */
1717
+ declare const assertScheduleInstant: (timestampMs: number, nowMs: number, surface: string) => void;
1718
+ export { type ArgsOf, CRON_SCHEDULE_KINDS, type CronJob, type CronJobsBuilder, type CronRunInFlight, type CronRunRecord, type CronRunStatus, type CronScheduleKind, type CronTarget, type CronTriggerOptions, type CronTriggerSnippet, type DailySchedule, type DeploymentPauseState, type DurableObjectIdLike, type DurableObjectJurisdiction, type DurableObjectNamespaceLike, type DurableObjectStubLike, type EnqueueOptions, type FunctionKind, type FunctionReference, type HourlySchedule, type HttpDispatcherOptions, type IntervalSchedule, type LunoraSchedulerOptions, MAX_RETRY_ATTEMPTS, type MessageBatchLike, type MonthlySchedule, type QueueConsumerOptions, type QueueDispatch, type QueueEnqueueOptions, type QueueJob, type QueueLike, type QueueMessageLike, type QueueSendOptionsLike, type QueueSendRequestLike, type QueueWorkpool, type QueueWorkpoolOptions, RETRY_BASE_DELAY_MS, type RetryPolicy, type RunOptions, type ScheduleRecord, type ScheduledJobState, type ScheduledJobView, type Scheduler, SchedulerDO, type SchedulerDOState, type SchedulerEnv, type SchedulerHostOptions, type SchedulerPoolStatus, type SchedulerStatus, TERMINAL_RETENTION_MS, type WeeklySchedule, type WorkflowReference, type Workpool, type WorkpoolOptions, assertScheduleDelay, assertScheduleInstant, compileCronSchedule, createCronTrigger, createQueueConsumer, createQueueWorkpool, createScheduler, createSchedulerHost, createWorkpool, cronJobs, httpDispatcher, isWorkflowReference, resolveScheduleId };