3737 * for — a deferred row coming due, a row another process wrote, a crashed
3838 * node's claim passing its timeout: it is noticed within one backed-off
3939 * interval, never more than `maxIdleIntervalMs` after it became claimable.
40+ *
41+ * ## Waking at the next due time (#29919)
42+ *
43+ * Two of those three are not unknowable: a deferred row and a claim carry the
44+ * instant they become claimable. A loop given {@link DispatchLoopOptions.nextDueAt}
45+ * asks for the earliest such instant once, after the first empty tick of an
46+ * idle streak (after `start()`, after a tick that claimed work, after a wake,
47+ * and after the due time it was sleeping towards arrives), and never sleeps
48+ * past it: a deferred row goes out within one tick of coming due, whatever the
49+ * ceiling. The answer is remembered, not re-read on every ceiling tick, so an
50+ * idle loop's steady-state cost is unchanged; a deferred row written in this
51+ * process later in the streak reaches the loop through
52+ * {@link DispatchLoop.wakeAt} instead, at no read at all.
53+ *
54+ * Only the third case — a row another process wrote — is left to the backoff.
55+ * A host on which no other process writes the store (a hosted tenant kernel:
56+ * one kernel per tenant database) says so with
57+ * {@link DispatchLoopOptions.soleWriter}, and an empty tick then sleeps
58+ * straight to the next due time or the ceiling instead of re-running the
59+ * `intervalMs` ramp. Before #29919 every boot re-ran that ramp against empty
60+ * stores: five ticks in the first minute per loop, every one of them idle.
4061 */
4162
4263/** Default ceiling of the idle backoff, in ms — see {@link DispatchLoopOptions.maxIdleIntervalMs}. */
@@ -50,6 +71,30 @@ export interface DispatchLoopOptions {
5071 * A value at or below `intervalMs` disables the backoff.
5172 */
5273 maxIdleIntervalMs ?: number ;
74+ /**
75+ * [#29919] The earliest instant (epoch ms, on `Date.now()`'s clock) at
76+ * which work this loop's tick would claim becomes claimable — a deferred
77+ * row's due time, a claim's expiry — or `null` when nothing is deferred.
78+ * Read once per idle streak, after its first empty tick; the loop then never
79+ * sleeps past the answer. An answer at or before the start of the tick that
80+ * just found nothing is not chased (that work was visible and not claimable
81+ * by this loop — another node's partition, say), so it cannot make the loop
82+ * spin. A rejection is reported through `onTickError` and the loop sleeps as
83+ * if it had no answer.
84+ *
85+ * Absent, the loop sleeps by the backoff alone, as it always has.
86+ */
87+ nextDueAt ?: ( ) => Promise < number | null | undefined > ;
88+ /**
89+ * [#29919] No other process writes the store this loop drains: every row it
90+ * can claim is written here, by a producer that calls
91+ * {@link DispatchLoop.wake} (or {@link DispatchLoop.wakeAt} for a deferred
92+ * row). The idle backoff's ramp only ever bought latency on rows another
93+ * process wrote, so with this set an empty tick sleeps straight to the
94+ * ceiling, or to the next due time when {@link nextDueAt} is given. Default
95+ * `false`: the ramp from `intervalMs` is kept.
96+ */
97+ soleWriter ?: boolean ;
5398 /** One full pass over the outbox. Resolves to the number of rows it claimed. */
5499 runTick : ( ) => Promise < number > ;
55100 /** A tick rejected. The loop has already counted it as idle; report it. */
@@ -61,7 +106,17 @@ export class DispatchLoop {
61106 private readonly maxIdleIntervalMs : number ;
62107 private readonly runTick : ( ) => Promise < number > ;
63108 private readonly onTickError : ( err : unknown ) => void ;
109+ private readonly nextDueAt : ( ( ) => Promise < number | null | undefined > ) | undefined ;
110+ private readonly soleWriter : boolean ;
64111 private timer : ReturnType < typeof setTimeout > | undefined ;
112+ /** When the pending timer fires (epoch ms); meaningful only while `timer` is set. */
113+ private timerFiresAt = 0 ;
114+ /** [#29919] Earliest known instant work becomes claimable, from the last read and every hint since. */
115+ private knownDueAt : number | null = null ;
116+ /** [#29919] The next empty tick reads {@link DispatchLoopOptions.nextDueAt}. */
117+ private dueReadOwed = false ;
118+ /** [#29919] Hints ({@link DispatchLoop.wakeAt}) since the running tick began — a read in flight cannot see them. */
119+ private hintedDueAt : number | null = null ;
65120 private running = false ;
66121 private inflightTick : Promise < void > | undefined ;
67122 /** Consecutive loop ticks that claimed nothing — the idle backoff's exponent. */
@@ -78,13 +133,17 @@ export class DispatchLoop {
78133 ) ;
79134 this . runTick = options . runTick ;
80135 this . onTickError = options . onTickError ;
136+ this . nextDueAt = options . nextDueAt ;
137+ this . soleWriter = options . soleWriter ?? false ;
81138 }
82139
83140 /** Begin the loop; the first tick runs immediately. Idempotent. */
84141 start ( ) : void {
85142 if ( this . running ) return ;
86143 this . running = true ;
87144 this . idleTicks = 0 ;
145+ this . knownDueAt = null ;
146+ this . dueReadOwed = true ;
88147 this . loopTick ( ) ;
89148 }
90149
@@ -106,9 +165,33 @@ export class DispatchLoop {
106165 wake ( ) : void {
107166 if ( ! this . running ) return ;
108167 this . idleTicks = 0 ;
168+ this . dueReadOwed = true ;
109169 this . loopTick ( ) ;
110170 }
111171
172+ /**
173+ * [#29919] Work becomes claimable at `dueAtMs` (epoch ms, on `Date.now()`'s
174+ * clock) — a deferred row this process just wrote: make sure a tick runs
175+ * then. Costs no read and no tick now, and leaves the idle backoff where it
176+ * is; a timer already due sooner is kept. An instant already past ticks at
177+ * once. No-op while stopped, or for a non-finite instant.
178+ */
179+ wakeAt ( dueAtMs : number ) : void {
180+ if ( ! this . running || ! Number . isFinite ( dueAtMs ) ) return ;
181+ this . knownDueAt = earliest ( this . knownDueAt , dueAtMs ) ;
182+ this . hintedDueAt = earliest ( this . hintedDueAt , dueAtMs ) ;
183+ // The running tick schedules its successor from `knownDueAt` when it settles.
184+ if ( this . inflightTick ) return ;
185+ if ( this . timer !== undefined && this . timerFiresAt <= dueAtMs ) return ;
186+ const delayMs = dueAtMs - Date . now ( ) ;
187+ if ( delayMs <= 0 ) {
188+ this . dueReadOwed = true ;
189+ this . loopTick ( ) ;
190+ return ;
191+ }
192+ this . schedule ( delayMs , true ) ;
193+ }
194+
112195 /**
113196 * One tick of the loop, then the timer for the next. Never two at once: a
114197 * call that finds a tick in flight becomes a follow-up request instead.
@@ -121,13 +204,22 @@ export class DispatchLoop {
121204 return ;
122205 }
123206 const startedAt = Date . now ( ) ;
207+ this . hintedDueAt = null ;
124208 this . inflightTick = this . runTick ( )
125- . then ( ( claimed ) => {
126- this . idleTicks = claimed > 0 ? 0 : this . idleTicks + 1 ;
209+ . then ( async ( claimed ) => {
210+ if ( claimed > 0 ) {
211+ this . idleTicks = 0 ;
212+ // The work just done may have deferred more (a retry, a backoff).
213+ this . dueReadOwed = true ;
214+ return ;
215+ }
216+ this . idleTicks += 1 ;
217+ if ( this . nextDueAt && this . dueReadOwed ) await this . readNextDueAt ( ) ;
127218 } )
128219 . catch ( ( err ) => {
129220 // A failing store is not work: back off rather than hammer it.
130221 this . idleTicks += 1 ;
222+ this . dueReadOwed = true ;
131223 this . onTickError ( err ) ;
132224 } )
133225 . finally ( ( ) => {
@@ -139,25 +231,67 @@ export class DispatchLoop {
139231 this . loopTick ( ) ;
140232 return ;
141233 }
142- this . schedule ( Math . max ( 0 , this . nextIntervalMs ( ) - ( Date . now ( ) - startedAt ) ) ) ;
234+ const { delayMs, forDue } = this . nextDelay ( startedAt ) ;
235+ this . schedule ( Math . max ( 0 , delayMs - ( Date . now ( ) - startedAt ) ) , forDue ) ;
143236 } ) ;
144237 }
145238
239+ /** [#29919] One read of the next due time, folded with the hints that arrived while it ran. */
240+ private async readNextDueAt ( ) : Promise < void > {
241+ this . dueReadOwed = false ;
242+ try {
243+ const due = await this . nextDueAt ! ( ) ;
244+ this . knownDueAt = earliest (
245+ typeof due === 'number' && Number . isFinite ( due ) ? due : null ,
246+ this . hintedDueAt ,
247+ ) ;
248+ } catch ( err ) {
249+ // No answer: sleep by the backoff alone, and ask again next idle tick.
250+ this . dueReadOwed = true ;
251+ this . onTickError ( err ) ;
252+ }
253+ }
254+
146255 /**
147- * Delay before the next loop tick, measured from the START of the last one:
148- * `intervalMs` while ticks claim work, doubled for every consecutive empty
149- * tick after that, capped at `maxIdleIntervalMs`.
256+ * Delay before the next loop tick, measured from the START of the last one
257+ * (`startedAt`), and whether it is a due time's: the backoff's delay
258+ * ({@link nextIntervalMs}), cut short by the earliest known due time.
259+ */
260+ private nextDelay ( startedAt : number ) : { delayMs : number ; forDue : boolean } {
261+ const backoffMs = this . nextIntervalMs ( ) ;
262+ if ( this . idleTicks === 0 || this . knownDueAt === null ) return { delayMs : backoffMs , forDue : false } ;
263+ if ( this . knownDueAt <= startedAt ) {
264+ // Claimable before this tick began, and the tick claimed nothing: the
265+ // work is not this loop's to take right now (another node holds its
266+ // partition, say). Chasing it would spin; the backoff covers it.
267+ this . knownDueAt = null ;
268+ return { delayMs : backoffMs , forDue : false } ;
269+ }
270+ const untilDueMs = this . knownDueAt - startedAt ;
271+ return untilDueMs < backoffMs ? { delayMs : untilDueMs , forDue : true } : { delayMs : backoffMs , forDue : false } ;
272+ }
273+
274+ /**
275+ * The backoff's delay before the next loop tick, measured from the START of
276+ * the last one: `intervalMs` while ticks claim work, doubled for every
277+ * consecutive empty tick after that, capped at `maxIdleIntervalMs` — or the
278+ * cap at once after an empty tick when the loop is the store's sole writer.
150279 */
151280 private nextIntervalMs ( ) : number {
152281 if ( this . idleTicks === 0 ) return this . intervalMs ;
282+ if ( this . soleWriter ) return this . maxIdleIntervalMs ;
153283 // Exponent clamped so the product stays finite long after the cap wins.
154284 return Math . min ( this . maxIdleIntervalMs , this . intervalMs * 2 ** Math . min ( this . idleTicks , 30 ) ) ;
155285 }
156286
157- private schedule ( delayMs : number ) : void {
287+ private schedule ( delayMs : number , forDue : boolean ) : void {
158288 this . clearTimer ( ) ;
289+ this . timerFiresAt = Date . now ( ) + delayMs ;
159290 this . timer = setTimeout ( ( ) => {
160291 this . timer = undefined ;
292+ // The due time arrived: the tick takes that work, and the next idle
293+ // tick asks for the one after it.
294+ if ( forDue ) this . dueReadOwed = true ;
161295 this . loopTick ( ) ;
162296 } , delayMs ) ;
163297 // Don't keep the event loop alive solely for the dispatcher.
@@ -170,3 +304,10 @@ export class DispatchLoop {
170304 this . timer = undefined ;
171305 }
172306}
307+
308+ /** The earlier of two optional instants. */
309+ function earliest ( a : number | null , b : number | null ) : number | null {
310+ if ( a === null ) return b ;
311+ if ( b === null ) return a ;
312+ return Math . min ( a , b ) ;
313+ }
0 commit comments