Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

KeyScheduler.property.test.ts

697 lines20.9 KB

1import { fc } from '@fast-check/vitest'
2import { afterEach, describe, expect, it, vi } from 'vitest'
3import { KeyScheduler } from '../src/executor/KeyScheduler'
4import { readOfflineOracleConfig } from './oracle-config'
5import type { OfflineTransaction } from '../src/types'
6​
7type Command =
8 | {
9 type: `schedule`
10 slot: number
11 createdAt: number
12 delay: number
13 payload: number
14 }
15 | { type: `getNext` }
16 | { type: `start` }
17 | { type: `complete` }
18 | { type: `fail` }
19 | { type: `retry`; delay: number; payload: number }
20 | { type: `bulkUpdate`; payload: number }
21 | { type: `remove`; ids: Array<string> }
22 | { type: `advance`; duration: number }
23 | { type: `clear` }
24​
25type LedgerEntry = {
26 transaction: OfflineTransaction
27 sequence: number
29​
30type Model = {
31 now: number
32 nextSequence: number
33 pending: Array<LedgerEntry>
34 activeId?: string
35 retryableId?: string
37​
38type Snapshot = {
39 next?: {
40 id: string
41 payload: unknown
42 }
43 pending: Array<{
44 id: string
45 createdAt: number
46 nextAttemptAt: number
47 retryCount: number
48 payload: unknown
49 }>
50 pendingCount: number
51 runningCount: number
53​
54const BASE_TIME = Date.parse(`2026-01-01T00:00:00.000Z`)
55const {
56 runs: RUNS,
57 seed: SEED,
58 path: PATH,
59} = readOfflineOracleConfig({
60 prefix: `TANSTACK_DB_OFFLINE_ORACLE`,
61 defaultRuns: 150,
62 defaultSeed: 1815,
63})
64​
65/**
66 * # Which offline transaction may run next?
67 *
68 * Contract and source: the established KeyScheduler FIFO tests and
69 * TransactionExecutor calling order require one globally serial queue. Equal
70 * creation times retain scheduling order. A delayed FIFO head blocks younger
71 * work. Failure makes the active transaction retryable without changing its
72 * place. Replay reconciliation may retire only unissued IDs. Clear retires all
73 * scheduler work and leaves the scheduler reusable.
74 *
75 * Model: a declarative ledger, fake clock, stable creation sequence, and active
76 * ID predict scheduler observations. The model does not import scheduler state
77 * or production classifiers.
78 *
79 * History grammar: legal commands schedule, inspect, start, fulfill, reject,
80 * update one or all pending records, reconcile one replay snapshot, advance
81 * the clock, and clear. A reject is followed immediately by its retry update.
82 * IDs are unique while pending. At most five IDs exist in generated histories.
83 *
84 * Production driver and refinement check: the driver calls the real
85 * executor-facing scheduler methods. After every command, it compares the next
86 * eligible ID and payload, ordered pending records, counts, and active state.
87 *
88 * Reach and controls: one fixed history reaches every transition. Two fixed
89 * histories cross retry-deadline order. Five injected observation faults prove
90 * the comparison rejects bypass, double issue, stale payload, stale clear, and
91 * failed selective retirement. The generated lane supports seed/path replay.
92 *
93 * Limits: persistence, caller promise settlement, leadership, and real timers
94 * have separate owners. The model does not promise fairness beyond FIFO order.
95 */
96​
97type CommandToken = {
98 selector: number
99 slot: number
100 createdAt: number
101 delay: number
102 payload: number
103 duration: number
105​
106type PlanningEntry = {
107 id: string
108 createdAt: number
109 nextAttemptAt: number
110 sequence: number
112​
113type PlanningState = {
114 now: number
115 nextSequence: number
116 pending: Array<PlanningEntry>
117 activeId?: string
118 retryableId?: string
120​
121const commandToken = fc.record({
122 selector: fc.nat(),
123 slot: fc.integer({ min: 0, max: 4 }),
124 createdAt: fc.integer({ min: 0, max: 3 }),
125 delay: fc.integer({ min: 0, max: 5 }),
126 payload: fc.integer({ min: -5, max: 5 }),
127 duration: fc.integer({ min: 0, max: 5 }),
128})
129​
130function planningOrder(state: PlanningState): Array<PlanningEntry> {
131 return [...state.pending].sort(
132 (left, right) =>
133 left.createdAt - right.createdAt || left.sequence - right.sequence,
134 )
136​
137function planningNext(state: PlanningState): PlanningEntry | undefined {
138 if (state.activeId) return undefined
139 const first = planningOrder(state)[0]
140 return first && first.nextAttemptAt <= state.now ? first : undefined
142​
143function nextFreeSlot(state: PlanningState, preferred: number): number {
144 for (let offset = 0; offset < 5; offset++) {
145 const slot = (preferred + offset) % 5
146 if (!state.pending.some(({ id }) => id === `tx-${slot}`)) return slot
147 }
148 throw new Error(`No transaction slot is available`)
150​
151function applyPlanningCommand(
152 state: PlanningState,
153 nextCommand: Command,
154): void {
155 if (nextCommand.type === `schedule`) {
156 state.pending.push({
157 id: `tx-${nextCommand.slot}`,
158 createdAt: BASE_TIME + nextCommand.createdAt * 1000,
159 nextAttemptAt: state.now + nextCommand.delay * 1000,
160 sequence: state.nextSequence++,
161 })
162 } else if (nextCommand.type === `start`) {
163 state.activeId = planningNext(state)!.id
164 } else if (nextCommand.type === `complete`) {
165 state.pending = state.pending.filter(({ id }) => id !== state.activeId)
166 state.activeId = undefined
167 } else if (nextCommand.type === `fail`) {
168 state.retryableId = state.activeId
169 state.activeId = undefined
170 } else if (nextCommand.type === `retry`) {
171 const entry = state.pending.find(({ id }) => id === state.retryableId)!
172 entry.nextAttemptAt = state.now + nextCommand.delay * 1000
173 state.retryableId = undefined
174 } else if (nextCommand.type === `advance`) {
175 state.now += nextCommand.duration * 1000
176 } else if (nextCommand.type === `remove`) {
177 const ids = new Set(nextCommand.ids)
178 state.pending = state.pending.filter(
179 ({ id }) => id === state.activeId || !ids.has(id),
180 )
181 } else if (nextCommand.type === `clear`) {
182 state.pending = []
183 state.activeId = undefined
184 state.retryableId = undefined
185 }
187​
188function buildLegalHistory(tokens: Array<CommandToken>): Array<Command> {
189 const state: PlanningState = {
190 now: BASE_TIME,
191 nextSequence: 0,
192 pending: [],
193 }
194 const history: Array<Command> = []
195​
196 for (const token of tokens) {
197 const choices: Array<Command> = [
198 { type: `getNext` },
199 { type: `bulkUpdate`, payload: token.payload },
200 { type: `advance`, duration: token.duration },
201 { type: `clear` },
202 ]
203 const removable = state.pending.filter(({ id }) => id !== state.activeId)
204 if (removable.length > 0) {
205 const mode = Math.abs(token.payload) % 4
206 const ids =
207 mode === 0
208 ? []
209 : mode === 1
210 ? [removable[token.slot % removable.length]!.id]
211 : mode === 2
212 ? removable.map(({ id }) => id)
213 : [removable[0]!.id, `missing`]
214 choices.push({
215 type: `remove`,
216 ids,
217 })
218 }
219​
220 if (state.pending.length < 5) {
221 choices.push({
222 type: `schedule`,
223 slot: nextFreeSlot(state, token.slot),
224 createdAt: token.createdAt,
225 delay: token.delay,
226 payload: token.payload,
227 })
228 }
229 if (planningNext(state)) choices.push({ type: `start` })
230 if (state.activeId) {
231 choices.push({ type: `complete` }, { type: `fail` })
232 }
233​
234 const nextCommand = choices[token.selector % choices.length]!
235 history.push(nextCommand)
236 applyPlanningCommand(state, nextCommand)
237​
238 if (nextCommand.type === `fail`) {
239 const retry: Command = {
240 type: `retry`,
241 delay: token.delay,
242 payload: token.payload,
243 }
244 history.push(retry)
245 applyPlanningCommand(state, retry)
246 }
247 }
248​
249 return history
251​
252const legalHistory = fc
253 .array(commandToken, { minLength: 1, maxLength: 50 })
254 .map(buildLegalHistory)
255​
256function createTransaction(
257 id: string,
258 createdAt: number,
259 nextAttemptAt: number,
260 payload: number,
261): OfflineTransaction {
262 return {
263 id,
264 mutationFnName: `syncData`,
265 mutations: [],
266 keys: [],
267 idempotencyKey: `idempotency-${id}`,
268 createdAt: new Date(createdAt),
269 retryCount: 0,
270 nextAttemptAt,
271 metadata: { payload },
272 version: 1,
273 }
275​
276function cloneTransaction(transaction: OfflineTransaction): OfflineTransaction {
277 return {
278 ...transaction,
279 createdAt: new Date(transaction.createdAt),
280 mutations: [...transaction.mutations],
281 keys: [...transaction.keys],
282 metadata: transaction.metadata ? { ...transaction.metadata } : undefined,
283 lastError: transaction.lastError ? { ...transaction.lastError } : undefined,
284 }
286​
287function ordered(model: Model): Array<LedgerEntry> {
288 return [...model.pending].sort(
289 (left, right) =>
290 left.transaction.createdAt.getTime() -
291 right.transaction.createdAt.getTime() || left.sequence - right.sequence,
292 )
294​
295// Model law: only the oldest pending transaction can become eligible. An
296// active transaction or a delayed FIFO head makes the next result empty.
297function expectedNext(model: Model): OfflineTransaction | undefined {
298 if (model.activeId) return undefined
299 const first = ordered(model)[0]?.transaction
300 return first && first.nextAttemptAt <= model.now ? first : undefined
302​
303function snapshot(
304 scheduler: KeyScheduler,
305 observedNext: OfflineTransaction | undefined,
306): Snapshot {
307 return {
308 next: observedNext
309 ? {
310 id: observedNext.id,
311 payload: observedNext.metadata?.payload,
312 }
313 : undefined,
314 pending: scheduler.getAllPendingTransactions().map((transaction) => ({
315 id: transaction.id,
316 createdAt: transaction.createdAt.getTime(),
317 nextAttemptAt: transaction.nextAttemptAt,
318 retryCount: transaction.retryCount,
319 payload: transaction.metadata?.payload,
320 })),
321 pendingCount: scheduler.getPendingCount(),
322 runningCount: scheduler.getRunningCount(),
323 }
325​
326function expectedSnapshot(model: Model): Snapshot {
327 const next = expectedNext(model)
328 return {
329 next: next
330 ? {
331 id: next.id,
332 payload: next.metadata?.payload,
333 }
334 : undefined,
335 pending: ordered(model).map(({ transaction }) => ({
336 id: transaction.id,
337 createdAt: transaction.createdAt.getTime(),
338 nextAttemptAt: transaction.nextAttemptAt,
339 retryCount: transaction.retryCount,
340 payload: transaction.metadata?.payload,
341 })),
342 pendingCount: model.pending.length,
343 runningCount: model.activeId ? 1 : 0,
344 }
346​
347function assertSnapshot(
348 history: ReadonlyArray<Command>,
349 commandIndex: number,
350 actual: Snapshot,
351 expected: Snapshot,
352): void {
353 expect(actual, JSON.stringify({ history, commandIndex })).toEqual(expected)
355​
356type FaultInjection = {
357 commandIndex: number
358 apply: (snapshot: Snapshot) => Snapshot
360​
361function runHistory(
362 history: Array<Command>,
363 fault?: FaultInjection,
364): Set<Command[`type`]> {
365 vi.useFakeTimers()
366 vi.setSystemTime(BASE_TIME)
367 const scheduler = new KeyScheduler()
368 const model: Model = {
369 now: BASE_TIME,
370 nextSequence: 0,
371 pending: [],
372 }
373 const coverage = new Set<Command[`type`]>()
374​
375 history.forEach((nextCommand, commandIndex) => {
376 // TransactionExecutor updates a failed transaction before asking for more
377 // work. Other commands in this short state are not legal lifecycle calls.
378 if (model.retryableId && nextCommand.type !== `retry`) {
379 throw new Error(`retry must immediately follow fail`)
380 }
381​
382 if (nextCommand.type === `schedule`) {
383 const id = `tx-${nextCommand.slot}`
384 if (model.pending.some(({ transaction }) => transaction.id === id)) {
385 throw new Error(`cannot schedule duplicate transaction ${id}`)
386 }
387 const transaction = createTransaction(
388 id,
389 BASE_TIME + nextCommand.createdAt * 1000,
390 model.now + nextCommand.delay * 1000,
391 nextCommand.payload,
392 )
393 scheduler.schedule(transaction)
394 model.pending.push({
395 transaction: cloneTransaction(transaction),
396 sequence: model.nextSequence++,
397 })
398 } else if (nextCommand.type === `getNext`) {
399 scheduler.getNext()
400 } else if (nextCommand.type === `start`) {
401 const transaction = expectedNext(model)
402 if (!transaction) throw new Error(`cannot start without eligible work`)
403 const observedNext = scheduler.getNext()
404 expect({
405 id: observedNext?.id,
406 payload: observedNext?.metadata?.payload,
407 }).toEqual({
408 id: transaction.id,
409 payload: transaction.metadata?.payload,
410 })
411 scheduler.markStarted(observedNext!)
412 model.activeId = transaction.id
413 } else if (nextCommand.type === `complete`) {
414 if (!model.activeId)
415 throw new Error(`cannot complete without active work`)
416 const index = model.pending.findIndex(
417 ({ transaction }) => transaction.id === model.activeId,
418 )
419 const transaction = model.pending[index]!.transaction
420 scheduler.markCompleted(transaction)
421 model.pending.splice(index, 1)
422 model.activeId = undefined
423 } else if (nextCommand.type === `fail`) {
424 if (!model.activeId) throw new Error(`cannot fail without active work`)
425 const transaction = model.pending.find(
426 ({ transaction: candidate }) => candidate.id === model.activeId,
427 )!.transaction
428 scheduler.markFailed(transaction)
429 model.retryableId = transaction.id
430 model.activeId = undefined
431 } else if (nextCommand.type === `retry`) {
432 if (!model.retryableId) throw new Error(`cannot retry before a failure`)
433 const entry = model.pending.find(
434 ({ transaction }) => transaction.id === model.retryableId,
435 )!
436 const updated = {
437 ...entry.transaction,
438 retryCount: entry.transaction.retryCount + 1,
439 nextAttemptAt: model.now + nextCommand.delay * 1000,
440 metadata: { payload: nextCommand.payload },
441 }
442 scheduler.updateTransaction(cloneTransaction(updated))
443 entry.transaction = updated
444 model.retryableId = undefined
445 } else if (nextCommand.type === `bulkUpdate`) {
446 const updated = model.pending.map(({ transaction }) => ({
447 ...transaction,
448 metadata: { payload: nextCommand.payload },
449 }))
450 scheduler.updateTransactions(updated.map(cloneTransaction))
451 for (const [index, transaction] of updated.entries()) {
452 model.pending[index]!.transaction = transaction
453 }
454 } else if (nextCommand.type === `advance`) {
455 const duration = nextCommand.duration * 1000
456 vi.advanceTimersByTime(duration)
457 model.now += duration
458 } else if (nextCommand.type === `remove`) {
459 const expectedRemoved = [
460 ...new Set(nextCommand.ids.filter((id) => id !== model.activeId)),
461 ]
462 expect(scheduler.removePendingTransactions(nextCommand.ids)).toEqual(
463 expectedRemoved,
464 )
465 const ids = new Set(nextCommand.ids)
466 model.pending = model.pending.filter(
467 ({ transaction }) =>
468 transaction.id === model.activeId || !ids.has(transaction.id),
469 )
470 } else {
471 scheduler.clear()
472 model.pending = []
473 model.activeId = undefined
474 model.retryableId = undefined
475 }
476​
477 coverage.add(nextCommand.type)
478 const observed = snapshot(scheduler, scheduler.getNext())
479 const actual =
480 fault?.commandIndex === commandIndex ? fault.apply(observed) : observed
481 assertSnapshot(history, commandIndex, actual, expectedSnapshot(model))
482 })
483​
484 return coverage
486​
487describe(`KeyScheduler generated lifecycle`, () => {
488 afterEach(() => vi.useRealTimers())
489​
490 it(`matches the FIFO retry ledger after every legal event`, () => {
491 fc.assert(
492 fc.property(legalHistory, (history) => {
493 runHistory(history)
494 }),
495 {
496 seed: SEED,
497 numRuns: RUNS,
498 ...(PATH ? { path: PATH } : {}),
499 },
500 )
501 })
502​
503 it(`executes every modeled transition in a fixed replay`, () => {
504 const history: Array<Command> = [
505 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
506 { type: `schedule`, slot: 1, createdAt: 0, delay: 0, payload: 2 },
507 { type: `getNext` },
508 { type: `start` },
509 { type: `remove`, ids: [`tx-0`, `tx-1`, `missing`] },
510 { type: `fail` },
511 { type: `retry`, delay: 2, payload: 3 },
512 { type: `getNext` },
513 { type: `bulkUpdate`, payload: 4 },
514 { type: `advance`, duration: 2 },
515 { type: `start` },
516 { type: `complete` },
517 { type: `clear` },
518 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 5 },
519 ]
520 expect(runHistory(history)).toEqual(
521 new Set<Command[`type`]>([
522 `schedule`,
523 `getNext`,
524 `start`,
525 `fail`,
526 `retry`,
527 `bulkUpdate`,
528 `remove`,
529 `advance`,
530 `complete`,
531 `clear`,
532 ]),
533 )
534 })
535​
536 it.each([
537 [
538 `an earlier retry deadline than its sibling`,
539 [
540 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
541 { type: `schedule`, slot: 1, createdAt: 1, delay: 5, payload: 2 },
542 { type: `start` },
543 { type: `fail` },
544 { type: `retry`, delay: 2, payload: 3 },
545 { type: `advance`, duration: 2 },
546 { type: `start` },
547 ],
548 ],
549 [
550 `a later retry deadline than its sibling`,
551 [
552 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
553 { type: `schedule`, slot: 1, createdAt: 1, delay: 1, payload: 2 },
554 { type: `start` },
555 { type: `fail` },
556 { type: `retry`, delay: 2, payload: 3 },
557 { type: `advance`, duration: 2 },
558 { type: `start` },
559 ],
560 ],
561 ] satisfies Array<[string, Array<Command>]>)(
562 `covers %s`,
563 (_name, history) => {
564 runHistory(history)
565 },
566 )
567​
568 it(`rejects bypassing the delayed FIFO head on its scheduler path`, () => {
569 const history: Array<Command> = [
570 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
571 { type: `schedule`, slot: 1, createdAt: 1, delay: 0, payload: 2 },
572 { type: `start` },
573 { type: `fail` },
574 { type: `retry`, delay: 5, payload: 3 },
575 ]
576​
577 expect(() =>
578 runHistory(history, {
579 commandIndex: 4,
580 apply: (actual) => ({
581 ...actual,
582 next: { id: `tx-1`, payload: 2 },
583 }),
584 }),
585 ).toThrow()
586 })
587​
588 it(`rejects permitting two active transactions on its scheduler path`, () => {
589 const history: Array<Command> = [
590 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
591 { type: `start` },
592 ]
593​
594 expect(() =>
595 runHistory(history, {
596 commandIndex: 1,
597 apply: (actual) => ({ ...actual, runningCount: 2 }),
598 }),
599 ).toThrow()
600 })
601​
602 it(`rejects losing an updated payload on its scheduler path`, () => {
603 const history: Array<Command> = [
604 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
605 { type: `start` },
606 { type: `fail` },
607 { type: `retry`, delay: 0, payload: 9 },
608 ]
609​
610 expect(() =>
611 runHistory(history, {
612 commandIndex: 3,
613 apply: (actual) => ({
614 ...actual,
615 next: actual.next ? { ...actual.next, payload: 1 } : undefined,
616 }),
617 }),
618 ).toThrow()
619 })
620​
621 it(`rejects retaining stale work after clear on its scheduler path`, () => {
622 const history: Array<Command> = [
623 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
624 { type: `start` },
625 { type: `clear` },
626 ]
627​
628 expect(() =>
629 runHistory(history, {
630 commandIndex: 2,
631 apply: (actual) => ({
632 ...actual,
633 pending: [
634 {
635 id: `tx-0`,
636 createdAt: BASE_TIME,
637 nextAttemptAt: BASE_TIME,
638 retryCount: 0,
639 payload: 1,
640 },
641 ],
642 pendingCount: 1,
643 }),
644 }),
645 ).toThrow()
646 })
647​
648 it(`rejects retaining selectively revoked work on its scheduler path`, () => {
649 const history: Array<Command> = [
650 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
651 { type: `schedule`, slot: 1, createdAt: 1, delay: 0, payload: 2 },
652 { type: `remove`, ids: [`tx-0`] },
653 ]
654​
655 expect(() =>
656 runHistory(history, {
657 commandIndex: 2,
658 apply: (actual) => ({
659 ...actual,
660 pending: [
661 {
662 id: `tx-0`,
663 createdAt: BASE_TIME,
664 nextAttemptAt: BASE_TIME,
665 retryCount: 0,
666 payload: 1,
667 },
668 ...actual.pending,
669 ],
670 pendingCount: actual.pendingCount + 1,
671 }),
672 }),
673 ).toThrow()
674 })
675​
676 it(`selectively removes only unissued work`, () => {
677 const scheduler = new KeyScheduler()
678 const active = createTransaction(``, BASE_TIME, BASE_TIME, 1)
679 const removed = createTransaction(`removed`, BASE_TIME + 1, BASE_TIME, 2)
680 const retained = createTransaction(`retained`, BASE_TIME + 2, BASE_TIME, 3)
681 scheduler.schedule(active)
682 scheduler.schedule(removed)
683 scheduler.schedule(retained)
684 scheduler.markStarted(active)
685​
686 expect(
687 scheduler.removePendingTransactions([active.id, removed.id, `missing`]),
688 ).toEqual([removed.id, `missing`])
689​
690 expect({
691 pending: scheduler.getAllPendingTransactions().map(({ id }) => id),
692 running: scheduler.getRunningCount(),
693 }).toEqual({ pending: [active.id, retained.id], running: 1 })
694 scheduler.markCompleted(active)
695 expect(scheduler.getNext()?.id).toBe(retained.id)
696 })
697})