Open History to see the last commit
1import { fc } from '@fast-check/vitest'
2import { afterEach, describe, expect, it, vi } from 'vitest'
3import { KeyScheduler } from '../src/executor/KeyScheduler'
4import {
5 oraclePropertyOptions,
6 oracleReplayTest,
7 oracleRuns,
8} from '../../db/tests/oracle-config'
9import { declareOracle } from '../../db/tests/oracle-declaration'
10import { BASE_TIME, createTransaction } from './key-scheduler-support'
11import type { OfflineTransaction } from '../src/types'
12
13const FIFO_LEDGER_PROPERTY = `offline.key-scheduler-fifo-ledger`
14
15type Command =
16 | {
17 type: `schedule`
18 slot: number
19 createdAt: number
20 delay: number
21 payload: number
22 }
23 | { type: `getNext` }
24 | { type: `start` }
25 | { type: `complete` }
26 | { type: `fail` }
27 | { type: `retry`; delay: number; payload: number }
28 | { type: `bulkUpdate`; payload: number }
29 | { type: `remove`; ids: Array<string> }
30 | { type: `advance`; duration: number }
31 | { type: `clear` }
32
33type LedgerEntry = {
34 transaction: OfflineTransaction
35 sequence: number
36}
37
38type Model = {
39 now: number
40 nextSequence: number
41 pending: Array<LedgerEntry>
42 activeId?: string
43 retryableId?: string
44}
45
46// retryableId is the driver-only failed transaction awaiting its retry update;
47// it is not scheduler state. sequence records the insertion-order tie breaker
48// for equal creation times without relying on the runtime sort implementation.
49
50type Snapshot = {
51 next?: {
52 id: string
53 payload: unknown
54 }
55 pending: Array<{
56 id: string
57 createdAt: number
58 nextAttemptAt: number
59 retryCount: number
60 payload: unknown
61 }>
62 pendingCount: number
63 runningCount: number
64}
65
66const FIXED_SEED = 1815
67const RUNS = oracleRuns(150)
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 observation mutants 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_ORACLE_SEED,
107 * TANSTACK_DB_ORACLE_PATH, and TANSTACK_DB_ORACLE_PROPERTY to replay a failure
108 * directly.
109 *
110 * Limits: persistence, caller promise settlement, leadership, and real timers
111 * have separate owners. The model does not promise fairness beyond FIFO order.
112 */
113
114type CommandToken = {
115 selector: number
116 slot: number
117 createdAt: number
118 delay: number
119 payload: number
120 duration: number
121}
122
123type PlanningEntry = {
124 id: string
125 createdAt: number
126 nextAttemptAt: number
127 sequence: number
128}
129
130type PlanningState = {
131 now: number
132 nextSequence: number
133 pending: Array<PlanningEntry>
134 activeId?: string
135 retryableId?: string
136}
137
138// PlanningState is a generator-only projection of the ledger. It tracks just
139// enough IDs and deadlines to choose legal commands. Its retryableId denotes
140// the TransactionExecutor step between mutation failure and retry update; the
141// scheduler has no corresponding retryable state.
142
143const commandToken = fc.record({
144 selector: fc.nat(),
145 slot: fc.integer({ min: 0, max: 4 }),
146 createdAt: fc.integer({ min: 0, max: 3 }),
147 delay: fc.integer({ min: 0, max: 5 }),
148 payload: fc.integer({ min: -5, max: 5 }),
149 duration: fc.integer({ min: 0, max: 5 }),
150})
151
152function planningOrder(state: PlanningState): Array<PlanningEntry> {
153 return [...state.pending].sort(
154 (left, right) =>
155 left.createdAt - right.createdAt || left.sequence - right.sequence,
156 )
157}
158
159function planningNext(state: PlanningState): PlanningEntry | undefined {
160 if (state.activeId) return undefined
161 const first = planningOrder(state)[0]
162 return first && first.nextAttemptAt <= state.now ? first : undefined
163}
164
165function nextFreeSlot(state: PlanningState, preferred: number): number {
166 for (let offset = 0; offset < 5; offset++) {
167 const slot = (preferred + offset) % 5
168 if (!state.pending.some(({ id }) => id === `tx-${slot}`)) return slot
169 }
170 throw new Error(`No transaction slot is available`)
171}
172
173function applyPlanningCommand(
174 state: PlanningState,
175 nextCommand: Command,
176): void {
177 if (nextCommand.type === `schedule`) {
178 state.pending.push({
179 id: `tx-${nextCommand.slot}`,
180 createdAt: BASE_TIME + nextCommand.createdAt * 1000,
181 nextAttemptAt: state.now + nextCommand.delay * 1000,
182 sequence: state.nextSequence++,
183 })
184 } else if (nextCommand.type === `start`) {
185 state.activeId = planningNext(state)!.id
186 } else if (nextCommand.type === `complete`) {
187 state.pending = state.pending.filter(({ id }) => id !== state.activeId)
188 state.activeId = undefined
189 } else if (nextCommand.type === `fail`) {
190 state.retryableId = state.activeId
191 } else if (nextCommand.type === `retry`) {
192 const entry = state.pending.find(({ id }) => id === state.retryableId)!
193 entry.nextAttemptAt = state.now + nextCommand.delay * 1000
194 state.activeId = undefined
195 state.retryableId = undefined
196 } else if (nextCommand.type === `advance`) {
197 state.now += nextCommand.duration * 1000
198 } else if (nextCommand.type === `remove`) {
199 const ids = new Set(nextCommand.ids)
200 state.pending = state.pending.filter(
201 ({ id }) => id === state.activeId || !ids.has(id),
202 )
203 } else if (nextCommand.type === `clear`) {
204 state.pending = []
205 state.activeId = undefined
206 state.retryableId = undefined
207 }
208}
209
210function buildLegalHistory(tokens: Array<CommandToken>): Array<Command> {
211 const state: PlanningState = {
212 now: BASE_TIME,
213 nextSequence: 0,
214 pending: [],
215 }
216 const history: Array<Command> = []
217
218 for (const token of tokens) {
219 const choices: Array<Command> = [
220 { type: `getNext` },
221 { type: `bulkUpdate`, payload: token.payload },
222 { type: `advance`, duration: token.duration },
223 { type: `clear` },
224 ]
225 const removable = state.pending.filter(({ id }) => id !== state.activeId)
226 if (removable.length > 0) {
227 const mode = Math.abs(token.payload) % 4
228 const ids =
229 mode === 0
230 ? []
231 : mode === 1
232 ? [removable[token.slot % removable.length]!.id]
233 : mode === 2
234 ? removable.map(({ id }) => id)
235 : [removable[0]!.id, `missing`]
236 choices.push({
237 type: `remove`,
238 ids,
239 })
240 }
241
242 if (state.pending.length < 5) {
243 choices.push({
244 type: `schedule`,
245 slot: nextFreeSlot(state, token.slot),
246 createdAt: token.createdAt,
247 delay: token.delay,
248 payload: token.payload,
249 })
250 }
251 if (state.activeId) {
252 choices.push({
253 type: `remove`,
254 ids: [state.activeId, ...removable.slice(0, 1).map(({ id }) => id)],
255 })
256 }
257 if (planningNext(state)) choices.push({ type: `start` })
258 if (state.activeId) {
259 choices.push({ type: `complete` }, { type: `fail` })
260 }
261
262 const nextCommand = choices[token.selector % choices.length]!
263 history.push(nextCommand)
264 applyPlanningCommand(state, nextCommand)
265
266 if (nextCommand.type === `fail`) {
267 const retry: Command = {
268 type: `retry`,
269 delay: token.delay,
270 payload: token.payload,
271 }
272 history.push(retry)
273 applyPlanningCommand(state, retry)
274 }
275 }
276
277 return history
278}
279
280const legalHistory = fc
281 .array(commandToken, { minLength: 1, maxLength: 50 })
282 .map(buildLegalHistory)
283
284function cloneTransaction(transaction: OfflineTransaction): OfflineTransaction {
285 return {
286 ...transaction,
287 createdAt: new Date(transaction.createdAt),
288 mutations: [...transaction.mutations],
289 keys: [...transaction.keys],
290 metadata: transaction.metadata ? { ...transaction.metadata } : undefined,
291 lastError: transaction.lastError ? { ...transaction.lastError } : undefined,
292 }
293}
294
295function ordered(model: Model): Array<LedgerEntry> {
296 return [...model.pending].sort(
297 (left, right) =>
298 left.transaction.createdAt.getTime() -
299 right.transaction.createdAt.getTime() || left.sequence - right.sequence,
300 )
301}
302
303// Model law: only the oldest pending transaction can become eligible. An
304// active transaction or a delayed FIFO head makes the next result empty.
305function expectedNext(model: Model): OfflineTransaction | undefined {
306 if (model.activeId) return undefined
307 const first = ordered(model)[0]?.transaction
308 return first && first.nextAttemptAt <= model.now ? first : undefined
309}
310
311function snapshot(
312 scheduler: KeyScheduler,
313 observedNext: OfflineTransaction | undefined,
314): Snapshot {
315 return {
316 next: observedNext
317 ? {
318 id: observedNext.id,
319 payload: observedNext.metadata?.payload,
320 }
321 : undefined,
322 pending: scheduler.getAllPendingTransactions().map((transaction) => ({
323 id: transaction.id,
324 createdAt: transaction.createdAt.getTime(),
325 nextAttemptAt: transaction.nextAttemptAt,
326 retryCount: transaction.retryCount,
327 payload: transaction.metadata?.payload,
328 })),
329 pendingCount: scheduler.getPendingCount(),
330 runningCount: scheduler.getRunningCount(),
331 }
332}
333
334function expectedSnapshot(model: Model): Snapshot {
335 const next = expectedNext(model)
336 return {
337 next: next
338 ? {
339 id: next.id,
340 payload: next.metadata?.payload,
341 }
342 : undefined,
343 pending: ordered(model).map(({ transaction }) => ({
344 id: transaction.id,
345 createdAt: transaction.createdAt.getTime(),
346 nextAttemptAt: transaction.nextAttemptAt,
347 retryCount: transaction.retryCount,
348 payload: transaction.metadata?.payload,
349 })),
350 pendingCount: model.pending.length,
351 runningCount: model.activeId ? 1 : 0,
352 }
353}
354
355function assertSnapshot(
356 history: ReadonlyArray<Command>,
357 commandIndex: number,
358 actual: Snapshot,
359 expected: Snapshot,
360): void {
361 expect(actual, JSON.stringify({ history, commandIndex })).toEqual(expected)
362}
363
364type ObservationMutant = {
365 commandIndex: number
366 apply: (snapshot: Snapshot) => Snapshot
367}
368
369function runHistory(
370 history: Array<Command>,
371 observationMutant?: ObservationMutant,
372): Set<Command[`type`]> {
373 vi.useFakeTimers()
374 vi.setSystemTime(BASE_TIME)
375 const scheduler = new KeyScheduler()
376 const model: Model = {
377 now: BASE_TIME,
378 nextSequence: 0,
379 pending: [],
380 }
381 const coverage = new Set<Command[`type`]>()
382
383 history.forEach((nextCommand, commandIndex) => {
384 // TransactionExecutor updates a failed transaction before asking for more
385 // work. Other commands in this short state are not legal lifecycle calls.
386 if (model.retryableId && nextCommand.type !== `retry`) {
387 throw new Error(`retry must immediately follow fail`)
388 }
389
390 if (nextCommand.type === `schedule`) {
391 const id = `tx-${nextCommand.slot}`
392 if (model.pending.some(({ transaction }) => transaction.id === id)) {
393 throw new Error(`cannot schedule duplicate transaction ${id}`)
394 }
395 const transaction = createTransaction(
396 id,
397 BASE_TIME + nextCommand.createdAt * 1000,
398 model.now + nextCommand.delay * 1000,
399 nextCommand.payload,
400 )
401 scheduler.schedule(transaction)
402 model.pending.push({
403 transaction: cloneTransaction(transaction),
404 sequence: model.nextSequence++,
405 })
406 } else if (nextCommand.type === `getNext`) {
407 scheduler.getNext()
408 } else if (nextCommand.type === `start`) {
409 const transaction = expectedNext(model)
410 if (!transaction) throw new Error(`cannot start without eligible work`)
411 const observedNext = scheduler.getNext()
412 expect({
413 id: observedNext?.id,
414 payload: observedNext?.metadata?.payload,
415 }).toEqual({
416 id: transaction.id,
417 payload: transaction.metadata?.payload,
418 })
419 scheduler.markStarted(observedNext!)
420 model.activeId = transaction.id
421 } else if (nextCommand.type === `complete`) {
422 if (!model.activeId)
423 throw new Error(`cannot complete without active work`)
424 const index = model.pending.findIndex(
425 ({ transaction }) => transaction.id === model.activeId,
426 )
427 const transaction = model.pending[index]!.transaction
428 scheduler.markCompleted(transaction)
429 model.pending.splice(index, 1)
430 model.activeId = undefined
431 } else if (nextCommand.type === `fail`) {
432 if (!model.activeId) throw new Error(`cannot fail without active work`)
433 const transaction = model.pending.find(
434 ({ transaction: candidate }) => candidate.id === model.activeId,
435 )!.transaction
436 model.retryableId = transaction.id
437 } else if (nextCommand.type === `retry`) {
438 if (!model.retryableId) throw new Error(`cannot retry before a failure`)
439 const entry = model.pending.find(
440 ({ transaction }) => transaction.id === model.retryableId,
441 )!
442 const failedTransaction = entry.transaction
443 const updated = {
444 ...failedTransaction,
445 retryCount: failedTransaction.retryCount + 1,
446 nextAttemptAt: model.now + nextCommand.delay * 1000,
447 metadata: { payload: nextCommand.payload },
448 }
449 scheduler.updateTransaction(cloneTransaction(updated))
450 scheduler.markFailed(failedTransaction)
451 entry.transaction = updated
452 model.activeId = undefined
453 model.retryableId = undefined
454 } else if (nextCommand.type === `bulkUpdate`) {
455 const updated = model.pending.map(({ transaction }) => ({
456 ...transaction,
457 metadata: { payload: nextCommand.payload },
458 }))
459 scheduler.updateTransactions(updated.map(cloneTransaction))
460 for (const [index, transaction] of updated.entries()) {
461 model.pending[index]!.transaction = transaction
462 }
463 } else if (nextCommand.type === `advance`) {
464 const duration = nextCommand.duration * 1000
465 vi.advanceTimersByTime(duration)
466 model.now += duration
467 } else if (nextCommand.type === `remove`) {
468 const expectedRemoved = [
469 ...new Set(nextCommand.ids.filter((id) => id !== model.activeId)),
470 ]
471 expect(scheduler.removePendingTransactions(nextCommand.ids)).toEqual(
472 expectedRemoved,
473 )
474 const ids = new Set(nextCommand.ids)
475 model.pending = model.pending.filter(
476 ({ transaction }) =>
477 transaction.id === model.activeId || !ids.has(transaction.id),
478 )
479 } else {
480 scheduler.clear()
481 model.pending = []
482 model.activeId = undefined
483 model.retryableId = undefined
484 }
485
486 coverage.add(nextCommand.type)
487 const observed = snapshot(scheduler, scheduler.getNext())
488 const actual =
489 observationMutant?.commandIndex === commandIndex
490 ? observationMutant.apply(observed)
491 : observed
492 assertSnapshot(history, commandIndex, actual, expectedSnapshot(model))
493 })
494
495 return coverage
496}
497
498declareOracle({ check: [runHistory], model: [expectedSnapshot] })
499
500describe(`KeyScheduler generated lifecycle`, () => {
501 afterEach(() => vi.useRealTimers())
502
503 // The fixed campaign stands aside during any path replay. The random
504 // campaign is the replay of FIFO_LEDGER_PROPERTY: it reseeds under a seed
505 // alone and runs the recorded path under a path replay of that property.
506 oracleReplayTest(it)(
507 `matches the FIFO retry ledger at the fixed seed`,
508 () => {
509 fc.assert(
510 fc.property(legalHistory, (history) => {
511 runHistory(history)
512 }),
513 { seed: FIXED_SEED, numRuns: RUNS },
514 )
515 },
516 )
517
518 oracleReplayTest(it, FIFO_LEDGER_PROPERTY)(
519 `matches the FIFO retry ledger at a random or replayed seed`,
520 () => {
521 fc.assert(
522 fc.property(legalHistory, (history) => {
523 runHistory(history)
524 }),
525 oraclePropertyOptions(150, FIFO_LEDGER_PROPERTY),
526 )
527 },
528 )
529
530 it(`reconstructs active removal with a waiting sibling`, () => {
531 const token = (selector: number, slot = 0): CommandToken => ({
532 selector,
533 slot,
534 createdAt: 0,
535 delay: 0,
536 payload: 1,
537 duration: 0,
538 })
539 const history = buildLegalHistory([
540 token(4), // schedule tx-0
541 token(5, 1), // schedule tx-1
542 token(6), // start tx-0
543 token(6), // request removal of both IDs while tx-0 is active
544 token(6), // complete tx-0
545 ])
546
547 expect(history).toEqual([
548 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
549 { type: `schedule`, slot: 1, createdAt: 0, delay: 0, payload: 1 },
550 { type: `start` },
551 { type: `remove`, ids: [`tx-0`, `tx-1`] },
552 { type: `complete` },
553 ])
554 runHistory(history)
555
556 const duplicateSlotRequest = buildLegalHistory([token(4), token(5)])
557 expect(duplicateSlotRequest[1]).toEqual({
558 type: `schedule`,
559 slot: 1,
560 createdAt: 0,
561 delay: 0,
562 payload: 1,
563 })
564 })
565
566 it(`reconstructs a blocked FIFO head at the retry deadline`, () => {
567 const token = (
568 selector: number,
569 slot: number,
570 delay = 0,
571 duration = 0,
572 ): CommandToken => ({
573 selector,
574 slot,
575 createdAt: slot,
576 delay,
577 payload: 1,
578 duration,
579 })
580 const history = buildLegalHistory([
581 token(4, 0), // schedule tx-0
582 token(5, 1), // schedule tx-1
583 token(6, 0), // start tx-0
584 token(8, 0, 5), // fail tx-0, then retry after five seconds
585 token(0, 0), // tx-1 is ready but cannot bypass tx-0
586 token(2, 0, 0, 4),
587 token(0, 0), // still before the retry deadline
588 token(2, 0, 0, 1),
589 token(6, 0), // tx-0 becomes eligible at the deadline
590 ])
591
592 expect(history.map(({ type }) => type)).toEqual([
593 `schedule`,
594 `schedule`,
595 `start`,
596 `fail`,
597 `retry`,
598 `getNext`,
599 `advance`,
600 `getNext`,
601 `advance`,
602 `start`,
603 ])
604 expect(history[4]).toEqual({ type: `retry`, delay: 5, payload: 1 })
605 runHistory(history)
606 })
607
608 it(`replays a generated wrong count at the same checkpoint`, () => {
609 const wrongCount = fc.property(legalHistory, (history) => {
610 runHistory(history, {
611 commandIndex: history.length - 1,
612 apply: (actual) => ({
613 ...actual,
614 pendingCount: actual.pendingCount + 1,
615 }),
616 })
617 })
618 const first = fc.check(wrongCount, { seed: FIXED_SEED, numRuns: RUNS })
619 expect(first.failed).toBe(true)
620 expect(first.error).toContain(`AssertionError:`)
621 expect(first.error).toContain(`"commandIndex":`)
622 const replayPath = first.counterexamplePath
623 if (replayPath === null) throw new Error(`Missing shrink path`)
624
625 const replay = fc.check(wrongCount, {
626 seed: first.seed,
627 path: replayPath,
628 numRuns: RUNS,
629 })
630 expect(replay.failed).toBe(true)
631 expect(replay.counterexample).toEqual(first.counterexample)
632 expect(replay.error?.split(`\n`)[0]).toEqual(first.error.split(`\n`)[0])
633 })
634
635 it(`executes every modeled transition in a fixed replay`, () => {
636 const history: Array<Command> = [
637 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
638 { type: `schedule`, slot: 1, createdAt: 0, delay: 0, payload: 2 },
639 { type: `getNext` },
640 { type: `start` },
641 { type: `remove`, ids: [`tx-0`, `tx-1`, `missing`] },
642 { type: `fail` },
643 { type: `retry`, delay: 2, payload: 3 },
644 { type: `getNext` },
645 { type: `bulkUpdate`, payload: 4 },
646 { type: `advance`, duration: 2 },
647 { type: `start` },
648 { type: `complete` },
649 { type: `clear` },
650 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 5 },
651 ]
652 expect(runHistory(history)).toEqual(
653 new Set<Command[`type`]>([
654 `schedule`,
655 `getNext`,
656 `start`,
657 `fail`,
658 `retry`,
659 `bulkUpdate`,
660 `remove`,
661 `advance`,
662 `complete`,
663 `clear`,
664 ]),
665 )
666 })
667
668 it.each([
669 [
670 `an earlier retry deadline than its sibling`,
671 [
672 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
673 { type: `schedule`, slot: 1, createdAt: 1, delay: 5, payload: 2 },
674 { type: `start` },
675 { type: `fail` },
676 { type: `retry`, delay: 2, payload: 3 },
677 { type: `advance`, duration: 2 },
678 { type: `start` },
679 ],
680 ],
681 [
682 `a later retry deadline than its sibling`,
683 [
684 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
685 { type: `schedule`, slot: 1, createdAt: 1, delay: 1, payload: 2 },
686 { type: `start` },
687 { type: `fail` },
688 { type: `retry`, delay: 2, payload: 3 },
689 { type: `advance`, duration: 2 },
690 { type: `start` },
691 ],
692 ],
693 ] satisfies Array<[string, Array<Command>]>)(
694 `covers %s`,
695 (_name, history) => {
696 runHistory(history)
697 },
698 )
699
700 it(`rejects bypassing the delayed FIFO head on its scheduler path`, () => {
701 const history: Array<Command> = [
702 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
703 { type: `schedule`, slot: 1, createdAt: 1, delay: 0, payload: 2 },
704 { type: `start` },
705 { type: `fail` },
706 { type: `retry`, delay: 5, payload: 3 },
707 ]
708
709 expect(() =>
710 runHistory(history, {
711 commandIndex: 4,
712 apply: (actual) => ({
713 ...actual,
714 next: { id: `tx-1`, payload: 2 },
715 }),
716 }),
717 ).toThrow()
718 })
719
720 it(`rejects permitting two active transactions on its scheduler path`, () => {
721 const history: Array<Command> = [
722 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
723 { type: `start` },
724 ]
725
726 expect(() =>
727 runHistory(history, {
728 commandIndex: 1,
729 apply: (actual) => ({ ...actual, runningCount: 2 }),
730 }),
731 ).toThrow()
732 })
733
734 it(`rejects losing an updated payload on its scheduler path`, () => {
735 const history: Array<Command> = [
736 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
737 { type: `start` },
738 { type: `fail` },
739 { type: `retry`, delay: 0, payload: 9 },
740 ]
741
742 expect(() =>
743 runHistory(history, {
744 commandIndex: 3,
745 apply: (actual) => ({
746 ...actual,
747 next: actual.next ? { ...actual.next, payload: 1 } : undefined,
748 }),
749 }),
750 ).toThrow()
751 })
752
753 it(`rejects retaining stale work after clear on its scheduler path`, () => {
754 const history: Array<Command> = [
755 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
756 { type: `start` },
757 { type: `clear` },
758 ]
759
760 expect(() =>
761 runHistory(history, {
762 commandIndex: 2,
763 apply: (actual) => ({
764 ...actual,
765 pending: [
766 {
767 id: `tx-0`,
768 createdAt: BASE_TIME,
769 nextAttemptAt: BASE_TIME,
770 retryCount: 0,
771 payload: 1,
772 },
773 ],
774 pendingCount: 1,
775 }),
776 }),
777 ).toThrow()
778 })
779
780 it(`rejects retaining selectively revoked work on its scheduler path`, () => {
781 const history: Array<Command> = [
782 { type: `schedule`, slot: 0, createdAt: 0, delay: 0, payload: 1 },
783 { type: `schedule`, slot: 1, createdAt: 1, delay: 0, payload: 2 },
784 { type: `remove`, ids: [`tx-0`] },
785 ]
786
787 expect(() =>
788 runHistory(history, {
789 commandIndex: 2,
790 apply: (actual) => ({
791 ...actual,
792 pending: [
793 {
794 id: `tx-0`,
795 createdAt: BASE_TIME,
796 nextAttemptAt: BASE_TIME,
797 retryCount: 0,
798 payload: 1,
799 },
800 ...actual.pending,
801 ],
802 pendingCount: actual.pendingCount + 1,
803 }),
804 }),
805 ).toThrow()
806 })
807})