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

KeyScheduler.property.test.ts

844 lines25.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​
38// retryableId is the driver-only failed transaction awaiting its retry update;
39// it is not scheduler state. sequence records the insertion-order tie breaker
40// for equal creation times without relying on the runtime sort implementation.
41​
42type Snapshot = {
43 next?: {
44 id: string
45 payload: unknown
46 }
47 pending: Array<{
48 id: string
49 createdAt: number
50 nextAttemptAt: number
51 retryCount: number
52 payload: unknown
53 }>
54 pendingCount: number
55 runningCount: number
57​
58const BASE_TIME = Date.parse(`2026-01-01T00:00:00.000Z`)
59const FIXED_SEED = 1815
60const {
61 runs: RUNS,
62 seed: SEED,
63 path: PATH,
64} = readOfflineOracleConfig({
65 prefix: `TANSTACK_DB_OFFLINE_ORACLE`,
66 defaultRuns: 150,
67})
68​
69/**
70 * # Which offline transaction may run next?
71 *
72 * Contract and source: the established KeyScheduler FIFO tests and
73 * TransactionExecutor calling order require one globally serial queue. Equal
74 * creation times retain scheduling order. A delayed FIFO head blocks younger
75 * work. Failure updates retry data before releasing the active transaction,
76 * without changing its place. Replay reconciliation may retire only unissued
77 * IDs. Clear retires all scheduler work and leaves the scheduler reusable.
78 *
79 * Model: a declarative ledger, fake clock, stable creation sequence, and active
80 * ID predict scheduler observations. The model does not import scheduler state
81 * or production classifiers.
82 *
83 * History grammar: legal commands schedule, inspect, start, fulfill, reject,
84 * update one or all pending records, reconcile one replay snapshot, advance
85 * the clock, and clear. A reject is followed immediately by its retry update
86 * and active release, matching TransactionExecutor's update-then-release order.
87 * IDs are unique while pending. At most five IDs exist in generated histories.
88 * Slot choice prevents duplicate pending IDs; creation time controls FIFO order;
89 * delay and clock advance control readiness; payload makes updates observable.
90 * The selector reaches every legal command, including removal during a run.
91 * Histories use 1-50 tokens plus automatic retry steps. Slots span 0-4,
92 * creation times 0-3 seconds, delays and advances 0-5 seconds, and payloads
93 * -5 through 5. The domain includes equal creation times, zero and positive
94 * delays, and negative and positive payloads.
95 * The grammar excludes duplicate pending IDs, start without eligible work,
96 * completion without active work, and any intervening command before retry.
97 *
98 * Production driver and refinement check: the driver calls the real
99 * executor-facing scheduler methods. After every command, it compares the next
100 * eligible ID and payload, ordered pending records, counts, and active state.
101 *
102 * Reach and controls: one fixed history reaches every transition. Two fixed
103 * histories cross retry-deadline order. Five injected observation faults prove
104 * the comparison rejects bypass, double issue, stale payload, stale clear, and
105 * failed selective retirement. The generated property runs at fixed seed 1815
106 * and at a random seed with the same budget. Set TANSTACK_DB_OFFLINE_ORACLE_SEED
107 * and TANSTACK_DB_OFFLINE_ORACLE_PATH to replay a failure directly.
108 *
109 * Limits: persistence, caller promise settlement, leadership, and real timers
110 * have separate owners. The model does not promise fairness beyond FIFO order.
111 */
112​
113type CommandToken = {
114 selector: number
115 slot: number
116 createdAt: number
117 delay: number
118 payload: number
119 duration: number
121​
122type PlanningEntry = {
123 id: string
124 createdAt: number
125 nextAttemptAt: number
126 sequence: number
128​
129type PlanningState = {
130 now: number
131 nextSequence: number
132 pending: Array<PlanningEntry>
133 activeId?: string
134 retryableId?: string
136​
137// PlanningState is a generator-only projection of the ledger. It tracks just
138// enough IDs and deadlines to choose legal commands. Its retryableId denotes
139// the TransactionExecutor step between mutation failure and retry update; the
140// scheduler has no corresponding retryable state.
141​
142const commandToken = fc.record({
143 selector: fc.nat(),
144 slot: fc.integer({ min: 0, max: 4 }),
145 createdAt: fc.integer({ min: 0, max: 3 }),
146 delay: fc.integer({ min: 0, max: 5 }),
147 payload: fc.integer({ min: -5, max: 5 }),
148 duration: fc.integer({ min: 0, max: 5 }),
149})
150​
151function planningOrder(state: PlanningState): Array<PlanningEntry> {
152 return [...state.pending].sort(
153 (left, right) =>
154 left.createdAt - right.createdAt || left.sequence - right.sequence,
155 )
157​
158function planningNext(state: PlanningState): PlanningEntry | undefined {
159 if (state.activeId) return undefined
160 const first = planningOrder(state)[0]
161 return first && first.nextAttemptAt <= state.now ? first : undefined
163​
164function nextFreeSlot(state: PlanningState, preferred: number): number {
165 for (let offset = 0; offset < 5; offset++) {
166 const slot = (preferred + offset) % 5
167 if (!state.pending.some(({ id }) => id === `tx-${slot}`)) return slot
168 }
169 throw new Error(`No transaction slot is available`)
171​
172function applyPlanningCommand(
173 state: PlanningState,
174 nextCommand: Command,
175): void {
176 if (nextCommand.type === `schedule`) {
177 state.pending.push({
178 id: `tx-${nextCommand.slot}`,
179 createdAt: BASE_TIME + nextCommand.createdAt * 1000,
180 nextAttemptAt: state.now + nextCommand.delay * 1000,
181 sequence: state.nextSequence++,
182 })
183 } else if (nextCommand.type === `start`) {
184 state.activeId = planningNext(state)!.id
185 } else if (nextCommand.type === `complete`) {
186 state.pending = state.pending.filter(({ id }) => id !== state.activeId)
187 state.activeId = undefined
188 } else if (nextCommand.type === `fail`) {
189 state.retryableId = state.activeId
190 } else if (nextCommand.type === `retry`) {
191 const entry = state.pending.find(({ id }) => id === state.retryableId)!
192 entry.nextAttemptAt = state.now + nextCommand.delay * 1000
193 state.activeId = undefined
194 state.retryableId = undefined
195 } else if (nextCommand.type === `advance`) {
196 state.now += nextCommand.duration * 1000
197 } else if (nextCommand.type === `remove`) {
198 const ids = new Set(nextCommand.ids)
199 state.pending = state.pending.filter(
200 ({ id }) => id === state.activeId || !ids.has(id),
201 )
202 } else if (nextCommand.type === `clear`) {
203 state.pending = []
204 state.activeId = undefined
205 state.retryableId = undefined
206 }
208​
209function buildLegalHistory(tokens: Array<CommandToken>): Array<Command> {
210 const state: PlanningState = {
211 now: BASE_TIME,
212 nextSequence: 0,
213 pending: [],
214 }
215 const history: Array<Command> = []
216​
217 for (const token of tokens) {
218 const choices: Array<Command> = [
219 { type: `getNext` },
220 { type: `bulkUpdate`, payload: token.payload },
221 { type: `advance`, duration: token.duration },
222 { type: `clear` },
223 ]
224 const removable = state.pending.filter(({ id }) => id !== state.activeId)
225 if (removable.length > 0) {
226 const mode = Math.abs(token.payload) % 4
227 const ids =
228 mode === 0
229 ? []
230 : mode === 1
231 ? [removable[token.slot % removable.length]!.id]
232 : mode === 2
233 ? removable.map(({ id }) => id)
234 : [removable[0]!.id, `missing`]
235 choices.push({
236 type: `remove`,
237 ids,
238 })
239 }
240​
241 if (state.pending.length < 5) {
242 choices.push({
243 type: `schedule`,
244 slot: nextFreeSlot(state, token.slot),
245 createdAt: token.createdAt,
246 delay: token.delay,
247 payload: token.payload,
248 })
249 }
250 if (state.activeId) {
251 choices.push({
252 type: `remove`,
253 ids: [state.activeId, ...removable.slice(0, 1).map(({ id }) => id)],
254 })
255 }
256 if (planningNext(state)) choices.push({ type: `start` })
257 if (state.activeId) {
258 choices.push({ type: `complete` }, { type: `fail` })
259 }
260​
261 const nextCommand = choices[token.selector % choices.length]!
262 history.push(nextCommand)
263 applyPlanningCommand(state, nextCommand)
264​
265 if (nextCommand.type === `fail`) {
266 const retry: Command = {
267 type: `retry`,
268 delay: token.delay,
269 payload: token.payload,
270 }
271 history.push(retry)
272 applyPlanningCommand(state, retry)
273 }
274 }
275​
276 return history
278​
279const legalHistory = fc
280 .array(commandToken, { minLength: 1, maxLength: 50 })
281 .map(buildLegalHistory)
282​
283function createTransaction(
284 id: string,
285 createdAt: number,
286 nextAttemptAt: number,
287 payload: number,
288): OfflineTransaction {
289 return {
290 id,
291 mutationFnName: `syncData`,
292 mutations: [],
293 keys: [],
294 idempotencyKey: `idempotency-${id}`,
295 createdAt: new Date(createdAt),
296 retryCount: 0,
297 nextAttemptAt,
298 metadata: { payload },
299 version: 1,
300 }
302​
303function cloneTransaction(transaction: OfflineTransaction): OfflineTransaction {
304 return {
305 ...transaction,
306 createdAt: new Date(transaction.createdAt),
307 mutations: [...transaction.mutations],
308 keys: [...transaction.keys],
309 metadata: transaction.metadata ? { ...transaction.metadata } : undefined,
310 lastError: transaction.lastError ? { ...transaction.lastError } : undefined,
311 }
313​
314function ordered(model: Model): Array<LedgerEntry> {
315 return [...model.pending].sort(
316 (left, right) =>
317 left.transaction.createdAt.getTime() -
318 right.transaction.createdAt.getTime() || left.sequence - right.sequence,
319 )
321​
322// Model law: only the oldest pending transaction can become eligible. An
323// active transaction or a delayed FIFO head makes the next result empty.
324function expectedNext(model: Model): OfflineTransaction | undefined {
325 if (model.activeId) return undefined
326 const first = ordered(model)[0]?.transaction
327 return first && first.nextAttemptAt <= model.now ? first : undefined
329​
330function snapshot(
331 scheduler: KeyScheduler,
332 observedNext: OfflineTransaction | undefined,
333): Snapshot {
334 return {
335 next: observedNext
336 ? {
337 id: observedNext.id,
338 payload: observedNext.metadata?.payload,
339 }
340 : undefined,
341 pending: scheduler.getAllPendingTransactions().map((transaction) => ({
342 id: transaction.id,
343 createdAt: transaction.createdAt.getTime(),
344 nextAttemptAt: transaction.nextAttemptAt,
345 retryCount: transaction.retryCount,
346 payload: transaction.metadata?.payload,
347 })),
348 pendingCount: scheduler.getPendingCount(),
349 runningCount: scheduler.getRunningCount(),
350 }
352​
353function expectedSnapshot(model: Model): Snapshot {
354 const next = expectedNext(model)
355 return {
356 next: next
357 ? {
358 id: next.id,
359 payload: next.metadata?.payload,
360 }
361 : undefined,
362 pending: ordered(model).map(({ transaction }) => ({
363 id: transaction.id,
364 createdAt: transaction.createdAt.getTime(),
365 nextAttemptAt: transaction.nextAttemptAt,
366 retryCount: transaction.retryCount,
367 payload: transaction.metadata?.payload,
368 })),
369 pendingCount: model.pending.length,
370 runningCount: model.activeId ? 1 : 0,
371 }
373​
374function assertSnapshot(
375 history: ReadonlyArray<Command>,
376 commandIndex: number,
377 actual: Snapshot,
378 expected: Snapshot,
379): void {
380 expect(actual, JSON.stringify({ history, commandIndex })).toEqual(expected)
382​
383type FaultInjection = {
384 commandIndex: number
385 apply: (snapshot: Snapshot) => Snapshot
387​
388function runHistory(
389 history: Array<Command>,
390 fault?: FaultInjection,
391): Set<Command[`type`]> {
392 vi.useFakeTimers()
393 vi.setSystemTime(BASE_TIME)
394 const scheduler = new KeyScheduler()
395 const model: Model = {
396 now: BASE_TIME,
397 nextSequence: 0,
398 pending: [],
399 }
400 const coverage = new Set<Command[`type`]>()
401​
402 history.forEach((nextCommand, commandIndex) => {
403 // TransactionExecutor updates a failed transaction before asking for more
404 // work. Other commands in this short state are not legal lifecycle calls.
405 if (model.retryableId && nextCommand.type !== `retry`) {
406 throw new Error(`retry must immediately follow fail`)
407 }
408​
409 if (nextCommand.type === `schedule`) {
410 const id = `tx-${nextCommand.slot}`
411 if (model.pending.some(({ transaction }) => transaction.id === id)) {
412 throw new Error(`cannot schedule duplicate transaction ${id}`)
413 }
414 const transaction = createTransaction(
415 id,
416 BASE_TIME + nextCommand.createdAt * 1000,
417 model.now + nextCommand.delay * 1000,
418 nextCommand.payload,
419 )
420 scheduler.schedule(transaction)
421 model.pending.push({
422 transaction: cloneTransaction(transaction),
423 sequence: model.nextSequence++,
424 })
425 } else if (nextCommand.type === `getNext`) {
426 scheduler.getNext()
427 } else if (nextCommand.type === `start`) {
428 const transaction = expectedNext(model)
429 if (!transaction) throw new Error(`cannot start without eligible work`)
430 const observedNext = scheduler.getNext()
431 expect({
432 id: observedNext?.id,
433 payload: observedNext?.metadata?.payload,
434 }).toEqual({
435 id: transaction.id,
436 payload: transaction.metadata?.payload,
437 })
438 scheduler.markStarted(observedNext!)
439 model.activeId = transaction.id
440 } else if (nextCommand.type === `complete`) {
441 if (!model.activeId)
442 throw new Error(`cannot complete without active work`)
443 const index = model.pending.findIndex(
444 ({ transaction }) => transaction.id === model.activeId,
445 )
446 const transaction = model.pending[index]!.transaction
447 scheduler.markCompleted(transaction)
448 model.pending.splice(index, 1)
449 model.activeId = undefined
450 } else if (nextCommand.type === `fail`) {
451 if (!model.activeId) throw new Error(`cannot fail without active work`)
452 const transaction = model.pending.find(
453 ({ transaction: candidate }) => candidate.id === model.activeId,
454 )!.transaction
455 model.retryableId = transaction.id
456 } else if (nextCommand.type === `retry`) {
457 if (!model.retryableId) throw new Error(`cannot retry before a failure`)
458 const entry = model.pending.find(
459 ({ transaction }) => transaction.id === model.retryableId,
460 )!
461 const failedTransaction = entry.transaction
462 const updated = {
463 ...failedTransaction,
464 retryCount: failedTransaction.retryCount + 1,
465 nextAttemptAt: model.now + nextCommand.delay * 1000,
466 metadata: { payload: nextCommand.payload },
467 }
468 scheduler.updateTransaction(cloneTransaction(updated))
469 scheduler.markFailed(failedTransaction)
470 entry.transaction = updated
471 model.activeId = undefined
472 model.retryableId = undefined
473 } else if (nextCommand.type === `bulkUpdate`) {
474 const updated = model.pending.map(({ transaction }) => ({
475 ...transaction,
476 metadata: { payload: nextCommand.payload },
477 }))
478 scheduler.updateTransactions(updated.map(cloneTransaction))
479 for (const [index, transaction] of updated.entries()) {
480 model.pending[index]!.transaction = transaction
481 }
482 } else if (nextCommand.type === `advance`) {
483 const duration = nextCommand.duration * 1000
484 vi.advanceTimersByTime(duration)
485 model.now += duration
486 } else if (nextCommand.type === `remove`) {
487 const expectedRemoved = [
488 ...new Set(nextCommand.ids.filter((id) => id !== model.activeId)),
489 ]
490 expect(scheduler.removePendingTransactions(nextCommand.ids)).toEqual(
491 expectedRemoved,
492 )
493 const ids = new Set(nextCommand.ids)
494 model.pending = model.pending.filter(
495 ({ transaction }) =>
496 transaction.id === model.activeId || !ids.has(transaction.id),
497 )
498 } else {
499 scheduler.clear()
500 model.pending = []
501 model.activeId = undefined
502 model.retryableId = undefined
503 }
504​
505 coverage.add(nextCommand.type)
506 const observed = snapshot(scheduler, scheduler.getNext())
507 const actual =
508 fault?.commandIndex === commandIndex ? fault.apply(observed) : observed
509 assertSnapshot(history, commandIndex, actual, expectedSnapshot(model))
510 })
511​
512 return coverage
514​
515describe(`KeyScheduler generated lifecycle`, () => {
516 afterEach(() => vi.useRealTimers())
517​
518 function runGeneratedHistory(seed?: number, path?: string): void {
519 fc.assert(
520 fc.property(legalHistory, (history) => {
521 runHistory(history)
522 }),
523 {
524 ...(seed === undefined ? {} : { seed }),
525 numRuns: RUNS,
526 ...(path === undefined ? {} : { path }),
527 },
528 )
529 }
530​
531 if (SEED === undefined) {
532 it(`matches the FIFO retry ledger at the fixed seed`, () => {
533 runGeneratedHistory(FIXED_SEED)
534 })
535​
536 it(`matches the FIFO retry ledger at a random seed`, () => {
537 runGeneratedHistory()
538 })
539 } else {
540 it(`replays the FIFO retry ledger at the requested seed and path`, () => {
541 runGeneratedHistory(SEED, PATH)
542 })
543 }
544​
545 it(`reconstructs active removal with a waiting sibling`, () => {
546 const token = (selector: number, slot = 0): CommandToken => ({
547 selector,
548 slot,
549 createdAt: 0,
550 delay: 0,
551 payload: 1,
552 duration: 0,
553 })
554 const history = buildLegalHistory([
555 token(4), // schedule tx-0
556 token(5, 1), // schedule tx-1
557 token(6), // start tx-0
558 token(6), // request removal of both IDs while tx-0 is active
559 token(6), // complete tx-0
560 ])
561​
562 expect(history).toEqual([
563 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
564 { type: `schedule`, slot: 1, createdAt: 0, delay: 0, payload: 1 },
565 { type: `start` },
566 { type: `remove`, ids: [`tx-0`, `tx-1`] },
567 { type: `complete` },
568 ])
569 runHistory(history)
570​
571 const duplicateSlotRequest = buildLegalHistory([token(4), token(5)])
572 expect(duplicateSlotRequest[1]).toEqual({
573 type: `schedule`,
574 slot: 1,
575 createdAt: 0,
576 delay: 0,
577 payload: 1,
578 })
579 })
580​
581 it(`reconstructs a blocked FIFO head at the retry deadline`, () => {
582 const token = (
583 selector: number,
584 slot: number,
585 delay = 0,
586 duration = 0,
587 ): CommandToken => ({
588 selector,
589 slot,
590 createdAt: slot,
591 delay,
592 payload: 1,
593 duration,
594 })
595 const history = buildLegalHistory([
596 token(4, 0), // schedule tx-0
597 token(5, 1), // schedule tx-1
598 token(6, 0), // start tx-0
599 token(8, 0, 5), // fail tx-0, then retry after five seconds
600 token(0, 0), // tx-1 is ready but cannot bypass tx-0
601 token(2, 0, 0, 4),
602 token(0, 0), // still before the retry deadline
603 token(2, 0, 0, 1),
604 token(6, 0), // tx-0 becomes eligible at the deadline
605 ])
606​
607 expect(history.map(({ type }) => type)).toEqual([
608 `schedule`,
609 `schedule`,
610 `start`,
611 `fail`,
612 `retry`,
613 `getNext`,
614 `advance`,
615 `getNext`,
616 `advance`,
617 `start`,
618 ])
619 expect(history[4]).toEqual({ type: `retry`, delay: 5, payload: 1 })
620 runHistory(history)
621 })
622​
623 it(`replays a generated wrong count at the same checkpoint`, () => {
624 const wrongCount = fc.property(legalHistory, (history) => {
625 runHistory(history, {
626 commandIndex: history.length - 1,
627 apply: (actual) => ({
628 ...actual,
629 pendingCount: actual.pendingCount + 1,
630 }),
631 })
632 })
633 const first = fc.check(wrongCount, { seed: FIXED_SEED, numRuns: RUNS })
634 expect(first.failed).toBe(true)
635 expect(first.error).toContain(`AssertionError:`)
636 expect(first.error).toContain(`"commandIndex":`)
637 const replayPath = first.counterexamplePath
638 if (replayPath === null) throw new Error(`Missing shrink path`)
639​
640 const replay = fc.check(wrongCount, {
641 seed: first.seed,
642 path: replayPath,
643 numRuns: RUNS,
644 })
645 expect(replay.failed).toBe(true)
646 expect(replay.counterexample).toEqual(first.counterexample)
647 expect(replay.error?.split(`\n`)[0]).toEqual(first.error.split(`\n`)[0])
648 })
649​
650 it(`executes every modeled transition in a fixed replay`, () => {
651 const history: Array<Command> = [
652 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
653 { type: `schedule`, slot: 1, createdAt: 0, delay: 0, payload: 2 },
654 { type: `getNext` },
655 { type: `start` },
656 { type: `remove`, ids: [`tx-0`, `tx-1`, `missing`] },
657 { type: `fail` },
658 { type: `retry`, delay: 2, payload: 3 },
659 { type: `getNext` },
660 { type: `bulkUpdate`, payload: 4 },
661 { type: `advance`, duration: 2 },
662 { type: `start` },
663 { type: `complete` },
664 { type: `clear` },
665 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 5 },
666 ]
667 expect(runHistory(history)).toEqual(
668 new Set<Command[`type`]>([
669 `schedule`,
670 `getNext`,
671 `start`,
672 `fail`,
673 `retry`,
674 `bulkUpdate`,
675 `remove`,
676 `advance`,
677 `complete`,
678 `clear`,
679 ]),
680 )
681 })
682​
683 it.each([
684 [
685 `an earlier retry deadline than its sibling`,
686 [
687 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
688 { type: `schedule`, slot: 1, createdAt: 1, delay: 5, payload: 2 },
689 { type: `start` },
690 { type: `fail` },
691 { type: `retry`, delay: 2, payload: 3 },
692 { type: `advance`, duration: 2 },
693 { type: `start` },
694 ],
695 ],
696 [
697 `a later retry deadline than its sibling`,
698 [
699 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
700 { type: `schedule`, slot: 1, createdAt: 1, delay: 1, payload: 2 },
701 { type: `start` },
702 { type: `fail` },
703 { type: `retry`, delay: 2, payload: 3 },
704 { type: `advance`, duration: 2 },
705 { type: `start` },
706 ],
707 ],
708 ] satisfies Array<[string, Array<Command>]>)(
709 `covers %s`,
710 (_name, history) => {
711 runHistory(history)
712 },
713 )
714​
715 it(`rejects bypassing the delayed FIFO head on its scheduler path`, () => {
716 const history: Array<Command> = [
717 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
718 { type: `schedule`, slot: 1, createdAt: 1, delay: 0, payload: 2 },
719 { type: `start` },
720 { type: `fail` },
721 { type: `retry`, delay: 5, payload: 3 },
722 ]
723​
724 expect(() =>
725 runHistory(history, {
726 commandIndex: 4,
727 apply: (actual) => ({
728 ...actual,
729 next: { id: `tx-1`, payload: 2 },
730 }),
731 }),
732 ).toThrow()
733 })
734​
735 it(`rejects permitting two active transactions on its scheduler path`, () => {
736 const history: Array<Command> = [
737 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
738 { type: `start` },
739 ]
740​
741 expect(() =>
742 runHistory(history, {
743 commandIndex: 1,
744 apply: (actual) => ({ ...actual, runningCount: 2 }),
745 }),
746 ).toThrow()
747 })
748​
749 it(`rejects losing an updated payload on its scheduler path`, () => {
750 const history: Array<Command> = [
751 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
752 { type: `start` },
753 { type: `fail` },
754 { type: `retry`, delay: 0, payload: 9 },
755 ]
756​
757 expect(() =>
758 runHistory(history, {
759 commandIndex: 3,
760 apply: (actual) => ({
761 ...actual,
762 next: actual.next ? { ...actual.next, payload: 1 } : undefined,
763 }),
764 }),
765 ).toThrow()
766 })
767​
768 it(`rejects retaining stale work after clear on its scheduler path`, () => {
769 const history: Array<Command> = [
770 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
771 { type: `start` },
772 { type: `clear` },
773 ]
774​
775 expect(() =>
776 runHistory(history, {
777 commandIndex: 2,
778 apply: (actual) => ({
779 ...actual,
780 pending: [
781 {
782 id: `tx-0`,
783 createdAt: BASE_TIME,
784 nextAttemptAt: BASE_TIME,
785 retryCount: 0,
786 payload: 1,
787 },
788 ],
789 pendingCount: 1,
790 }),
791 }),
792 ).toThrow()
793 })
794​
795 it(`rejects retaining selectively revoked work on its scheduler path`, () => {
796 const history: Array<Command> = [
797 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
798 { type: `schedule`, slot: 1, createdAt: 1, delay: 0, payload: 2 },
799 { type: `remove`, ids: [`tx-0`] },
800 ]
801​
802 expect(() =>
803 runHistory(history, {
804 commandIndex: 2,
805 apply: (actual) => ({
806 ...actual,
807 pending: [
808 {
809 id: `tx-0`,
810 createdAt: BASE_TIME,
811 nextAttemptAt: BASE_TIME,
812 retryCount: 0,
813 payload: 1,
814 },
815 ...actual.pending,
816 ],
817 pendingCount: actual.pendingCount + 1,
818 }),
819 }),
820 ).toThrow()
821 })
822​
823 it(`selectively removes only unissued work`, () => {
824 const scheduler = new KeyScheduler()
825 const active = createTransaction(``, BASE_TIME, BASE_TIME, 1)
826 const removed = createTransaction(`removed`, BASE_TIME + 1, BASE_TIME, 2)
827 const retained = createTransaction(`retained`, BASE_TIME + 2, BASE_TIME, 3)
828 scheduler.schedule(active)
829 scheduler.schedule(removed)
830 scheduler.schedule(retained)
831 scheduler.markStarted(active)
832​
833 expect(
834 scheduler.removePendingTransactions([active.id, removed.id, `missing`]),
835 ).toEqual([removed.id, `missing`])
836​
837 expect({
838 pending: scheduler.getAllPendingTransactions().map(({ id }) => id),
839 running: scheduler.getRunningCount(),
840 }).toEqual({ pending: [active.id, retained.id], running: 1 })
841 scheduler.markCompleted(active)
842 expect(scheduler.getNext()?.id).toBe(retained.id)
843 })
844})