Skip to content

Commit 141fc49

Browse files
committed
test: pin the next-due wake and the sole-writer cold start (#29919)
1 parent edc37a0 commit 141fc49

6 files changed

Lines changed: 535 additions & 6 deletions

File tree

Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #29919 — `DispatchLoop` wakes at the next due time, and a sole writer's loop
5+
* does not re-run the idle ramp after a cold start.
6+
*
7+
* Before #29919 every `start()` re-ran the backoff's ramp from `intervalMs`
8+
* against stores that were empty: with the dispatchers' 500 ms base, six ticks
9+
* in a fresh loop's first minute (0, 1, 3, 7, 15, 31 s), every one idle, while the only thing the ramp ever bought — early
10+
* notice of a row another process wrote — cannot happen on a sole writer. And
11+
* a deferred row was noticed only at the next backed-off tick, up to the
12+
* ceiling late.
13+
*
14+
* Every leg runs on vitest's fake timers, so "when did a tick start" is an
15+
* exact reading rather than a sleep-and-hope.
16+
*/
17+
18+
import { describe, it, expect, afterEach, vi } from 'vitest';
19+
import { DispatchLoop, type DispatchLoopOptions } from './dispatch-loop.js';
20+
21+
const BASE = 500;
22+
const MINUTE = 60_000;
23+
const FIVE_MINUTES = 5 * MINUTE;
24+
25+
afterEach(() => { vi.useRealTimers(); });
26+
27+
/** Fake timers with the clock at 0, so a tick's start reads as ms since `start()`. */
28+
function useClockAtZero(): void {
29+
vi.useFakeTimers();
30+
vi.setSystemTime(0);
31+
}
32+
33+
/**
34+
* A store of deferred rows: `runTick` claims every row due by the fake clock,
35+
* `nextDueAt` answers the earliest row still in the future. Both are recorded.
36+
*/
37+
function harness(options: Partial<DispatchLoopOptions> & { dueRows?: number[] } = {}) {
38+
const dueRows = [...(options.dueRows ?? [])];
39+
const tickStarts: number[] = [];
40+
const claimedAt: number[] = [];
41+
let dueReads = 0;
42+
const errors: unknown[] = [];
43+
const loop = new DispatchLoop({
44+
intervalMs: BASE,
45+
runTick: async () => {
46+
const now = Date.now();
47+
tickStarts.push(now);
48+
let claimed = 0;
49+
for (let i = dueRows.length - 1; i >= 0; i--) {
50+
if (dueRows[i]! <= now) {
51+
dueRows.splice(i, 1);
52+
claimedAt.push(now);
53+
claimed++;
54+
}
55+
}
56+
return claimed;
57+
},
58+
nextDueAt: async () => {
59+
dueReads++;
60+
const future = dueRows.filter((t) => t > Date.now());
61+
return future.length > 0 ? Math.min(...future) : null;
62+
},
63+
onTickError: (err) => { errors.push(err); },
64+
...options,
65+
});
66+
return {
67+
loop,
68+
tickStarts,
69+
claimedAt,
70+
errors,
71+
dueRows,
72+
get dueReads() { return dueReads; },
73+
};
74+
}
75+
76+
describe('#29919 DispatchLoop — a sole writer does not ramp from a cold start', () => {
77+
it('a fresh loop on an empty store ticks ONCE in its first minute', async () => {
78+
useClockAtZero();
79+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
80+
h.loop.start();
81+
await vi.advanceTimersByTimeAsync(MINUTE);
82+
await h.loop.stop();
83+
84+
expect(h.tickStarts).toEqual([0]);
85+
// The one tick's one due read — nothing deferred, so the ceiling.
86+
expect(h.dueReads).toBe(1);
87+
});
88+
89+
it('CONTROL: the same loop without soleWriter still runs the ramp it always had', async () => {
90+
useClockAtZero();
91+
const h = harness({ maxIdleIntervalMs: FIVE_MINUTES });
92+
h.loop.start();
93+
await vi.advanceTimersByTimeAsync(MINUTE);
94+
await h.loop.stop();
95+
96+
// 1, 2, 4, 8, 16 s apart — six ticks. The harness can see a ramp, so the
97+
// single tick above is a reading about soleWriter, not a dead clock.
98+
expect(h.tickStarts).toEqual([0, 1_000, 3_000, 7_000, 15_000, 31_000]);
99+
});
100+
101+
it('without a nextDueAt reader, soleWriter alone sleeps straight to the ceiling', async () => {
102+
useClockAtZero();
103+
const h = harness({ soleWriter: true, maxIdleIntervalMs: 30_000, nextDueAt: undefined });
104+
h.loop.start();
105+
await vi.advanceTimersByTimeAsync(2 * MINUTE);
106+
await h.loop.stop();
107+
108+
expect(h.tickStarts).toEqual([0, 30_000, 60_000, 90_000, 120_000]);
109+
});
110+
111+
it('steady state costs no extra read: an idle hour at the ceiling reads the due time once', async () => {
112+
useClockAtZero();
113+
const h = harness({ soleWriter: true, maxIdleIntervalMs: 30_000 });
114+
h.loop.start();
115+
await vi.advanceTimersByTimeAsync(60 * MINUTE);
116+
await h.loop.stop();
117+
118+
// 3600 s / 30 s, plus the tick start() runs.
119+
expect(h.tickStarts).toHaveLength(121);
120+
expect(h.dueReads).toBe(1);
121+
});
122+
});
123+
124+
describe('#29919 DispatchLoop — wakes at the next due time', () => {
125+
it('a row due at T+20 s is claimed at T+20 s, under a five-minute ceiling', async () => {
126+
useClockAtZero();
127+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES, dueRows: [20_000] });
128+
h.loop.start();
129+
await vi.advanceTimersByTimeAsync(MINUTE);
130+
await h.loop.stop();
131+
132+
expect(h.claimedAt).toEqual([20_000]);
133+
// The cold-start tick, the due tick, and the tick after a claim
134+
// (`intervalMs` later) — then nothing is deferred and the ceiling wins.
135+
expect(h.tickStarts).toEqual([0, 20_000, 20_500]);
136+
});
137+
138+
it('the ramp keeps its shape, cut short only by the due time (no soleWriter)', async () => {
139+
useClockAtZero();
140+
const h = harness({ maxIdleIntervalMs: FIVE_MINUTES, dueRows: [2_000] });
141+
h.loop.start();
142+
await vi.advanceTimersByTimeAsync(4_000);
143+
await h.loop.stop();
144+
145+
expect(h.claimedAt).toEqual([2_000]);
146+
expect(h.tickStarts).toEqual([0, 1_000, 2_000, 2_500, 3_500]);
147+
});
148+
149+
it('consecutive deferred rows are each claimed on time — the read is re-asked after each due time', async () => {
150+
useClockAtZero();
151+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES, dueRows: [10_000, 40_000] });
152+
h.loop.start();
153+
await vi.advanceTimersByTimeAsync(MINUTE);
154+
await h.loop.stop();
155+
156+
expect(h.claimedAt).toEqual([10_000, 40_000]);
157+
});
158+
159+
it('wakeAt(): a deferred row written later in the streak is claimed on time with no read', async () => {
160+
useClockAtZero();
161+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
162+
h.loop.start();
163+
await vi.advanceTimersByTimeAsync(10_000);
164+
const readsBefore = h.dueReads;
165+
const ticksBefore = h.tickStarts.length;
166+
167+
h.dueRows.push(35_000);
168+
h.loop.wakeAt(35_000);
169+
// No tick now: the hint only moves the timer.
170+
await vi.advanceTimersByTimeAsync(1);
171+
expect(h.tickStarts).toHaveLength(ticksBefore);
172+
173+
await vi.advanceTimersByTimeAsync(MINUTE);
174+
await h.loop.stop();
175+
expect(h.claimedAt).toEqual([35_000]);
176+
// The hint cost no read; the read after the claim is the next streak's.
177+
expect(h.dueReads).toBe(readsBefore + 1);
178+
});
179+
180+
it('wakeAt() keeps a timer that is already due sooner', async () => {
181+
useClockAtZero();
182+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES, dueRows: [20_000] });
183+
h.loop.start();
184+
await vi.advanceTimersByTimeAsync(1);
185+
h.dueRows.push(50_000);
186+
h.loop.wakeAt(50_000);
187+
await vi.advanceTimersByTimeAsync(MINUTE);
188+
await h.loop.stop();
189+
190+
expect(h.claimedAt).toEqual([20_000, 50_000]);
191+
});
192+
});
193+
194+
describe('#29919 DispatchLoop — wake() still delivers at once', () => {
195+
it('a wake on a sole writer sleeping towards its ceiling ticks immediately', async () => {
196+
useClockAtZero();
197+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
198+
h.loop.start();
199+
await vi.advanceTimersByTimeAsync(MINUTE);
200+
201+
h.dueRows.push(MINUTE);
202+
h.loop.wake();
203+
await vi.advanceTimersByTimeAsync(0);
204+
await h.loop.stop();
205+
206+
expect(h.claimedAt).toEqual([MINUTE]);
207+
});
208+
});
209+
210+
describe('#29919 DispatchLoop — nothing it reads can make it spin', () => {
211+
it('a rejected tick counts as idle: a failing store is ticked once per ceiling, not hammered', async () => {
212+
useClockAtZero();
213+
const h = harness({
214+
soleWriter: true,
215+
maxIdleIntervalMs: 30_000,
216+
runTick: async () => { h.tickStarts.push(Date.now()); throw new Error('store down'); },
217+
});
218+
h.loop.start();
219+
await vi.advanceTimersByTimeAsync(MINUTE);
220+
await h.loop.stop();
221+
222+
expect(h.tickStarts).toEqual([0, 30_000, 60_000]);
223+
expect(h.errors).toHaveLength(3);
224+
// A rejected tick asks for no due time.
225+
expect(h.dueReads).toBe(0);
226+
});
227+
228+
it('a rejected tick after a due time was learned still sleeps until that due time, not 0 ms', async () => {
229+
useClockAtZero();
230+
const tickStarts: number[] = [];
231+
const loop = new DispatchLoop({
232+
intervalMs: BASE,
233+
maxIdleIntervalMs: FIVE_MINUTES,
234+
soleWriter: true,
235+
// The cold-start tick finds nothing; every later tick rejects.
236+
runTick: async () => {
237+
tickStarts.push(Date.now());
238+
if (tickStarts.length > 1) throw new Error('store down');
239+
return 0;
240+
},
241+
nextDueAt: async () => 20_000,
242+
onTickError: () => {},
243+
});
244+
loop.start();
245+
await vi.advanceTimersByTimeAsync(MINUTE);
246+
await loop.stop();
247+
248+
// The due tick at 20 s rejects; the next is a ceiling away.
249+
expect(tickStarts).toEqual([0, 20_000]);
250+
});
251+
252+
it('a due time at or before the tick that found nothing is not chased (visible, but not this loop\'s to claim)', async () => {
253+
useClockAtZero();
254+
const h = harness({
255+
soleWriter: true,
256+
maxIdleIntervalMs: 30_000,
257+
// Another node holds the row's partition: it is due, and never claimable here.
258+
runTick: async () => { h.tickStarts.push(Date.now()); return 0; },
259+
nextDueAt: async () => 0,
260+
});
261+
h.loop.start();
262+
await vi.advanceTimersByTimeAsync(MINUTE);
263+
await h.loop.stop();
264+
265+
expect(h.tickStarts).toEqual([0, 30_000, 60_000]);
266+
});
267+
268+
it('a rejected due read is reported, and the loop sleeps by its backoff alone', async () => {
269+
useClockAtZero();
270+
const h = harness({
271+
soleWriter: true,
272+
maxIdleIntervalMs: 30_000,
273+
nextDueAt: async () => { throw new Error('read failed'); },
274+
});
275+
h.loop.start();
276+
await vi.advanceTimersByTimeAsync(MINUTE);
277+
await h.loop.stop();
278+
279+
expect(h.tickStarts).toEqual([0, 30_000, 60_000]);
280+
expect(h.errors).toHaveLength(3);
281+
});
282+
283+
it('stop() is final: a wakeAt() after it is a no-op', async () => {
284+
useClockAtZero();
285+
const h = harness({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
286+
h.loop.start();
287+
await vi.advanceTimersByTimeAsync(1);
288+
await h.loop.stop();
289+
h.loop.wakeAt(10_000);
290+
await vi.advanceTimersByTimeAsync(MINUTE);
291+
292+
expect(h.tickStarts).toEqual([0]);
293+
});
294+
});

‎packages/services/service-messaging/src/dispatcher-idle-backoff.test.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ function sendProbe(hold?: { recipient: string; until: Promise<void> }): SendProb
7373
};
7474
}
7575

76-
function setup(options: { maxIdleIntervalMs?: number; probe?: SendProbe } = {}) {
76+
function setup(options: { maxIdleIntervalMs?: number; probe?: SendProbe; soleWriter?: boolean } = {}) {
7777
const outbox = new TickRecordingOutbox(1);
7878
const probe = options.probe ?? sendProbe();
7979
const dispatcher = new NotificationDispatcher({
@@ -84,6 +84,7 @@ function setup(options: { maxIdleIntervalMs?: number; probe?: SendProbe } = {})
8484
partitionCount: 1,
8585
intervalMs: BASE,
8686
maxIdleIntervalMs: options.maxIdleIntervalMs,
87+
soleWriter: options.soleWriter,
8788
});
8889
return { outbox, probe, dispatcher };
8990
}
@@ -254,3 +255,43 @@ describe('#17610 MessagingService.emit() wakes the dispatcher its outbox is wire
254255
await dispatcher.stop();
255256
});
256257
});
258+
259+
describe('#29919 NotificationDispatcher — a sole writer wakes at the next due time', () => {
260+
const FIVE_MINUTES = 5 * MINUTE;
261+
262+
it('a fresh sole-writer dispatcher on an empty outbox ticks ONCE in its first minute', async () => {
263+
const { outbox, dispatcher } = setup({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
264+
dispatcher.start();
265+
await vi.advanceTimersByTimeAsync(MINUTE);
266+
await dispatcher.stop();
267+
expect(outbox.tickStarts).toHaveLength(1);
268+
});
269+
270+
it('a deferred delivery written before boot is sent the moment it comes due, not a ceiling later', async () => {
271+
const { outbox, probe, dispatcher } = setup({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
272+
const t0 = Date.now();
273+
await outbox.enqueue({ ...row('u1'), notBefore: t0 + 20_000 });
274+
dispatcher.start();
275+
await vi.advanceTimersByTimeAsync(MINUTE);
276+
await dispatcher.stop();
277+
278+
expect(probe.sent).toEqual(['u1']);
279+
expect(outbox.tickStarts.slice(0, 2)).toEqual([t0, t0 + 20_000]);
280+
});
281+
282+
it('a crashed node\'s claim is reaped and re-sent once its claim TTL passes, not a ceiling later', async () => {
283+
const { outbox, probe, dispatcher } = setup({ soleWriter: true, maxIdleIntervalMs: FIVE_MINUTES });
284+
const t0 = Date.now();
285+
await outbox.enqueue(row('u1'));
286+
// Claimed by a node that then died: in flight, never acked.
287+
const [claimed] = await outbox.claim({ nodeId: 'dead-node', limit: 1, claimTtlMs: 5_000 });
288+
expect(claimed?.recipientId).toBe('u1');
289+
dispatcher.start();
290+
await vi.advanceTimersByTimeAsync(MINUTE);
291+
await dispatcher.stop();
292+
293+
expect(probe.sent).toEqual(['u1']);
294+
// claimTtlMs defaults to 2 × lockTtlMs = 10 × intervalMs; reapable just after.
295+
expect(outbox.tickStarts[1]! - t0).toBe(10 * BASE + 1);
296+
});
297+
});

‎packages/services/service-messaging/src/dispatcher-idle-cost.integration.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,43 @@ describe('#17610 #28383 NotificationDispatcher — idle tick cost', () => {
290290
expect(sent).toEqual(['u1']);
291291
});
292292
});
293+
294+
describe('#29919 SqlNotificationOutbox.nextDueAt — the one read a sole-writer loop wakes by', () => {
295+
it('an empty outbox answers null in TWO statements, both reads', async () => {
296+
statements = [];
297+
expect(await outbox.nextDueAt({ claimTtlMs: TTL })).toBeNull();
298+
expect(statements).toHaveLength(2);
299+
expect(statements.every((sql) => /^select /i.test(sql))).toBe(true);
300+
});
301+
302+
it('answers the earliest deferred row — batched or not — and ignores a row already due', async () => {
303+
const now = Date.now();
304+
await outbox.enqueue({ notificationId: 'n_now', recipientId: 'u1', channel: 'inbox', payload: { title: 't' } });
305+
await outbox.enqueue({
306+
notificationId: 'n_later', recipientId: 'u2', channel: 'inbox', payload: { title: 't' },
307+
notBefore: now + 60_000,
308+
});
309+
expect(await outbox.nextDueAt({ claimTtlMs: TTL, now })).toBe(now + 60_000);
310+
311+
// A digest window closing is a deferred row too.
312+
await outbox.enqueue({
313+
notificationId: 'n_digest', recipientId: 'u3', channel: 'inbox', payload: { title: 't' },
314+
digestKey: 'u3|inbox|w1', notBefore: now + 30_000,
315+
});
316+
expect(await outbox.nextDueAt({ claimTtlMs: TTL, now })).toBe(now + 30_000);
317+
});
318+
319+
it('answers when the oldest in-flight claim becomes reapable, when that is sooner', async () => {
320+
const now = Date.now();
321+
await outbox.enqueue({
322+
notificationId: 'n_later', recipientId: 'u2', channel: 'inbox', payload: { title: 't' },
323+
notBefore: now + 10 * TTL,
324+
});
325+
await outbox.enqueue({ notificationId: 'n_claimed', recipientId: 'u1', channel: 'inbox', payload: { title: 't' } });
326+
const [claimed] = await outbox.claim({ nodeId: 'node-crashed', limit: 10, claimTtlMs: TTL, now: now - 1_000 });
327+
expect(claimed?.recipientId).toBe('u1');
328+
329+
// `reapExpired` takes a claim strictly older than the TTL.
330+
expect(await outbox.nextDueAt({ claimTtlMs: TTL, now })).toBe(now - 1_000 + TTL + 1);
331+
});
332+
});

0 commit comments

Comments
 (0)