The user wants a "deterministic test runner for async systems" that uses "virtual time and schedulers". This is a tool for testing concurrent or asynchronous code in a controlled, repeatable way.
Key Concepts:
Asynchronous Systems: Code that involves Futures, Promises, callbacks, or coroutine-like structures (e.g., JavaScript async/await, Python asyncio, Rust async/await, Java completablefutures).
Non-determinism: Real async systems depend on OS thread scheduling, network latency, IO timing, etc. This makes tests flaky.
Deterministic Testing: The goal is to remove external factors. If the input is the same, the execution order and result must be exactly the same every time.
Virtual Time (Mock Time): Instead of relying on the system clock (Date.now(), Instant::now()), time is manually advanced by the test runner. This allows simulating timeouts, delays, and intervals instantly without waiting for real time to pass.
Schedulers (Executor): The mechanism that decides which task runs when. In a deterministic runner, the scheduler is usually a priority queue based on virtual time.
Target Language/Platform:
The prompt doesn't specify a language.
JavaScript/TypeScript:Jest fake timers are a good reference, but a custom implementation shows more depth.
Rust:tokio::test, futures::task::LocalPool.
Python:asyncio loop.
Go: Less suited for this specific pattern due to the "goroutine" model usually being OS-thread backed, though possible.
I will choose Rust or TypeScript. Rust is excellent for this because its async model is explicit about the Waker and Executor, making the implementation of a custom scheduler very instructive. However, TypeScript/JavaScript is often more accessible for understanding the "Virtual Time" concept without fighting the borrow checker or understanding complex Rust traits like Future and Arc<Waker> deeply, though a simplified Rust implementation is very powerful.
Let's stick to Python or JavaScript for clarity, or Rust for robustness.
Actually, let's use Rust. Why? Because building an executor from scratch (which is essentially what a deterministic test runner is) is a very common "hard" interview/system design problem in the Rust ecosystem, and it demonstrates the mechanics of Future and Waker beautifully.
Wait, if the user wants a generic explanation, maybe a language-agnostic design + an implementation is best.
Let's go with a Python implementation using asyncio. It's readable and dynamic.
Or, TypeScript using native Promises.
Or, Rust.
Let's look at the complexity.
In JS: You can't easily swap the internal Promise resolution queue without a library like FakeTimers or manipulating the event loop.
In Rust: You have to define a Runtime struct that holds a task queue.
Let's go with Rust. It forces us to define the Scheduler and Virtual Clock explicitly.
No, TypeScript might be easier for a broader audience to digest the logic of "Time advancement".
Actually, let's write it in Rust but keep it self-contained.
Self-correction: Writing a full executor in Rust from scratch in a single chat response is heavy. It requires implementing block_on, a Waker using Arc<Mutex>, etc. It might obscure the core logic of "Virtual Time".
Let's try TypeScript. We can build a FakeTime class and a Scheduler that manages a queue of tasks sorted by execution time.
Plan:
Core Concept: Explain that real async systems rely on the OS event loop, which is non-deterministic. Our runner will replace the OS event loop with a strict priority queue.
Architecture:
VirtualClock: Holds the current time. Provides now() and advance().
Task: A wrapper around a callback (or Promise thunk) + an execution timestamp.
Scheduler: The engine. It holds the VirtualClock and the TaskQueue.
Runner: The API entry point (run(async () => { ... })).
Implementation Details (TypeScript):
We need to mock setTimeout, setInterval, and Promise resolution.
Actually, fully hijacking the JS event loop is hard. A better approach for a code example is to build a mini-runtime that doesn't use the native event loop for scheduling, but simulates it.
However, standard async/await compiles down to a state machine that relies on the native Promise executor.
Alternative:Rust. In Rust, Future::poll is explicit. You pass a context. It is much easier to build a "Virtual Time" runner in Rust conceptually because the runtime is external to the language syntax (unlike JS where await hardcodes the microtask queue).
Decision: I will implement this in Rust. It is the "Correct" way to demonstrate this because async Rust is heap-allocated state machines that require an external executor. It highlights the specific mechanics requested: Virtual Time and Schedulers.
Rust Implementation Plan:
VirtualClock: A struct with now: Duration and add_duration. Uses Rc<RefCell<>> or Arc<Mutex> for shared access.
ScheduledTask: A struct containing the execution time and the Future to poll.
Scheduler: A Binary Heap (Priority Queue) sorted by time.
Waker: The tricky part. When a task is not ready (e.g., waiting for a "timer" that hasn't fired), it needs to register itself to be woken up when time advances.
Actually, for a deterministic runner based purely on time, we can simplify.
If a task yields Poll::Pending, we need to know when to wake it up.
In a test runner, usually, we mock the "sleep" or "delay" primitives. When sleep(100ms) is called, it registers the waker to be triggered at now + 100ms.
The Runner:
Loop:
Poll the top task.
If it returns Ready, remove it.
If it returns Pending:
If it has a wake-up time (how do we know? We need a mock timer), schedule it.
If it has no wake-up time (waiting for IO that we didn't mock), panic or stall.
Jump time forward to the next scheduled task.
Wait, this is getting complex for a single LLM turn.
Let's pivot to a Python implementation using asyncio. Python's asyncio allows swapping the event loop policy. We can write a custom EventLoop that uses a virtual clock.
Pros: Very Pythonic, easy to read.
Cons: Deep asyncio internals can be verbose.
Let's go back to TypeScript but define a specific "Test System" class.
We won't try to hijack the global setTimeout. Instead, we will inject a System object into our functions.
async function myLogic(sys: System) { await sys.sleep(100); }
This makes the dependency explicit and the test pure.
Refined Plan:
Language: TypeScript (for broad readability).
Component 1: Virtual Time. A class Time that tracks current now.
Component 2: The Scheduler. A priority queue of tasks: { runAt: number, callback: () => void }.
Component 3: The Environment/System. A handle passed to user code. It provides sys.sleep(ms) and sys.now().
Component 4: The Runner. Drains the queue.
sys.sleep doesn't actually block. It creates a Promise and adds a resolution callback to the Scheduler at now + ms.
The Runner pops the next task from the queue, advances now to that task's time, and executes it.
This is clean, self-contained, and demonstrates the concept perfectly without needing to hack browser/Node internals.
Steps to Code:
Define Task: executeAt (timestamp) and action (function).
Define VirtualScheduler: holds the time and the min-heap of tasks.
schedule(delay, callback): Adds to heap.
runToCompletion(): While heap not empty, pop, advance time, execute.
Define the User API: sleep returns a Promise that resolves via schedule.
Handling "Instant" Tasks (Promises):
Real async code involves Promises that resolve immediately (microtasks).
In a strict deterministic runner, we need to handle the distinction between Macrotasks (Timers) and Microtasks (Promises).
If we only use a Time-based queue, we might miss the nuance that Promise.resolve().then(...) happens beforesetTimeout(..., 0).
However, for a Virtual Time runner, we primarily care about time manipulation.
Let's simplify: We will treat everything as a scheduled task. If delay is 0, it happens at current now.
Advanced Determinism (Simulated Network):
I should include a way to simulate external events deterministically.
E.g., "At t=500ms, resolve the network request".
Final Output Structure:
Concept: Explain why we need this (flaky tests).
The Code (TypeScript):
VirtualTime: The clock.
TaskQueue: The priority queue.
TestRunner: The engine that ties them together.
Mocks (Timer, FakeFetch).
Example Test: A scenario that would be flaky in real life (race conditions) but passes deterministically here.
Refining the implementation:
We need to ensure that when we execute a task, it might schedule more tasks.
The runner loop:
currentTask = queue.pop()
currentTime = currentTask.time
currentTask.run()
Crucial: If currentTask creates a Promise (e.g. await sleep(10)), that Promise constructor adds a new task to the queue.
Repeat.
Let's write the code.
typescript
class DeterministicRunner {
private currentTime = 0;
private tasks: Task[] = []; // Min-heap based on time
// Mock system calls
public sys = {
now: () => this.currentTime,
setTimeout: (cb: () => void, ms: number) => {
this.schedule(this.currentTime + ms, cb);
},
// ... sleep helper
}
}
Wait, if I use async/await in the user code, and the sleep returns a standard Promise, the JS engine handles the microtask queue. The cb inside resolve() will run.
If sleep calls setTimeout, that puts it in the macrotask queue.
I need to ensure my schedule function replaces setTimeout.
Okay, the plan is solid. I will build a standalone class that acts as the "World" or "Runtime".
One tricky edge case: Recursion / Stack overflow.
If I run a task that schedules a task at the same time, and I run it immediately recursively, I might blow the stack.
Solution: The runner should process tasks of the same timestamp in a loop, but maybe drain a buffer?
Actually, simpler: The runner processes the min-heap.
If task.time == currentTime, we can just run it.
If we want to be strict about "turns", we should probably flush all tasks at currentTime before advancing time. This simulates " synchronous execution block" followed by "time jump".
Let's refine the "Microtask vs Macrotask" issue.
Standard async/await breaks up functions into callbacks chained by Promises.
If I write:
javascript
async function loop(sys) {
while(true) {
await sys.sleep(0);
}
}
If sys.sleep(0) schedules a task at t, and the runner picks it up immediately, we have an infinite loop. That's fine.
But we need to make sure we don't stack overflow.
A standard Promise then runs as a microtask.
If I use my own queue, I control the stack.
Let's stick to the "Virtual Time" aspect primarily.
The scheduler will handle delay.
The user code will use await.
Example Scenario to prove determinism:
Two functions racing to increment a counter.
Function A: sleeps 100ms, increments.
Function B: sleeps 50ms, sleeps 50ms, increments.
In real life, thread scheduling might make B's second sleep finish slightly before or after A's single sleep.
In Virtual Time: 0 -> 50 -> 100. At 100, we have two tasks. We execute them in the order they were scheduled. Determinism is guaranteed (First-In-First-Out for same timestamp).
I will produce a clean TypeScript solution. It's the best balance of clarity and functionality for this prompt.
Structure of the Response:
Introduction: The problem of flaky async tests.
The Design: Virtual Clock + Priority Queue.
The Implementation: A DeterministicScheduler class.
The Test Case: A complex scenario (Retry logic with exponential backoff).
Comparison: How this beats real-time testing.
Let's refine the implementation details.
The Scheduler needs to expose a run method.
It needs addTask(time, callback).
It needs advanceTime.
I'll implement a Task interface and a PriorityQueue (simple array sort for simplicity, or explain it's a heap).
I'll create a TestContext passed to the test.
Let's add a "Rust" flavor option? No, keep it simple. Stick to one good implementation. TypeScript is safest.
One crucial feature: Automatic Time Advancement.
If the queue is empty, but we are waiting on a Promise that hasn't resolved?
In this simplified model, we assume all async operations are mocked to use our Scheduler (Time-based).
If the queue is empty, the test is done (or deadlocked). We stop.
Handling External Inputs:
The runner should allow the test writer to inject events at specific times.
runner.at(500, () => someResolver.resolve('data'))
Final check of the code flow:
runner = new Runner()
runner.schedule(0, userCode)
runner.inject(200, externalEvent)
runner.run()
Loop while tasks exist.
t = peekNextTime()
clock.set(t)
processTasksAt(t)
This looks perfect. I will write the code based on this logic.
I will also add comments explaining why this is deterministic (Time is discrete, execution order is strictly FIFO within time buckets).
Let's produce the artifact.
I'll structure the code as a reusable library class + a usage example.
Usage Example:
Testing a "Retry with Backoff" function.
It tries to fetch data. Fails. Waits 100ms. Tries again. Fails. Waits 200ms. Succeeds.
Without virtual time, this test takes 300ms + network jitter.
With virtual time, it takes 0ms and is reproducible.
Implementation Language: TypeScript.
Key features to include:
VirtualClock: now() returns manipulated time.
Scheduler: Manages queue.
MockAsync: sleep, poll.
Deterministic execution: Handling tasks at the same timestamp.
Let's do it.
Self-Correction during drafting:
Should I use performance.now() or Date.now() mocks?
It's cleaner to pass a sys object to the function under test.
function logic(sys) { ... }
This forces Dependency Injection, which is good practice for testable code.
Final Plan:
Define Scheduler class.
Define TestRunner class.
Write a retry function that depends on time.
Write a test that validates the retry logic deterministically.
Building a deterministic test runner for async systems requires replacing the non-deterministic parts of the runtime (OS scheduler, system clock, hardware interrupts) with a controlled simulation.
Below is a complete, runnable implementation in TypeScript. It demonstrates the three core pillars of this pattern:
Virtual Time: Time only moves when you say it does.
The Scheduler: A priority queue that decides exactly which task runs next.
Mock Primitives: Replacing Promise and setTimeout with deterministic versions.
The Implementation
You can copy this into a single file (e.g., deterministic_runner.ts) to run it.
typescript
Example: Testing a "Retry with Backoff" System
Imagine a function that fetches data. If it fails, it waits and retries (exponential backoff). Testing this in real time is slow (seconds of waiting) and flaky (network issues). With our runner, it is instant and mathematically precise.
1. System Under Test (Your App Code)
typescript
// A typical async function relying on time and randomness
async function fetchWithRetry(
ctx: ReturnType<DeterministicRunner['createContext']>,
fetcher: () => Promise<string>
) {
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
try {
console.log(`[t=${ctx.now()}] Attempt ${attempts + 1}...`);
const result = await fetcher();
console.log(`[t=${ctx.now()}] Success!`);
return result;
} catch (err) {
attempts++;
if (attempts >= maxAttempts) throw err;
// Exponential backoff: 100ms, 200ms, 400ms...
const delay = 100 * Math.pow(2, attempts - 1);
console.log(`[t=${ctx.now()}] Failed. Retrying in ${delay}ms...`);
// Use the VIRTUAL timer, not real setTimeout
await new Promise(resolve => ctx.setTimeout(resolve, delay));
}
}
throw new Error("Unreachable");
}
2. The Test (Deterministic & Instant)
typescript
async function runTest() {
const runner = new DeterministicRunner();
const ctx = runner.createContext();
// SIMULATION SETUP
let callCount = 0;
// A mock fetcher that fails the first time but succeeds the second.
const mockFetcher = async () => {
callCount++;
if (callCount === 1) throw new Error("Network Blip");
return "Data Loaded";
};
// Schedule the system under test to start at t=0
ctx.setTimeout(() => {
fetchWithRetry(ctx, mockFetcher).catch(() => {});
}, 0);
// RUN SIMULATION
console.log("--- Starting Deterministic Simulation ---");
await runner.run();
console.log("--- Simulation Complete ---");
// ASSERTIONS
console.log(`Final Virtual Time: ${runner.now()}ms`);
// Math check:
// Attempt 1 at t=0. Fails.
// Backoff = 100 * 2^0 = 100ms.
// Attempt 2 at t=100. Succeeds.
// Total time should be exactly 100ms.
if (runner.now() === 100) {
console.log("✅ PASSED: Time advanced exactly as expected.");
} else {
console.log("❌ FAILED: Timing logic is incorrect.");
}
}
runTest();
Why this works
Instant Execution: Even though the code logic calculates delays (100ms), the runner.run() loop sets this.currentTime = nextTask.executeAt immediately. The test finishes in microseconds, not milliseconds.
No Flakiness: The VirtualScheduler uses a sorted array. If two events are scheduled for the exact same time, they execute in insertion order (FIFO). This guarantees the test behaves exactly the same every single run.
Microtask vs Macrotask: In this simplified model, we treat everything as a macrotask (timers). In a real-world scenario (like implementing this for React or Rust), you would need a separate queue for Promises (microtasks) to ensure promise callbacks fire before the next timer tick.
Key Concepts Explained
1. Virtual Time (this.currentTime)
Real time (Date.now()) is discontinuous and slow. Virtual time is discrete and discrete. It "jumps" to the next scheduled event. This allows testing long-running processes (e.g., "What happens if the JWT token expires in 1 hour?") instantly.
2. The Scheduler (taskQueue)
The scheduler acts as the "Director". In a real OS, the scheduler is preemptive and chaotic. In our runner, it is cooperative and ordered.
Input: Callbacks + Delays.
Output: A strictly ordered sequence of execution.
3. Dependency Injection (The ctx object)
This is the most critical architectural requirement. You cannot use global setTimeout or new Date() inside your logic. Your business logic must accept a "System Context" object (often called Clock, Runtime, or Env). This allows the test runner to swap reality for the simulation.
/**
* DETERMINISTIC TEST RUNNER
*
* A minimal implementation of virtual time and scheduling for testing async systems.
*/
// 1. INTERFACES
type TaskCallback = () => void | Promise<void>;
interface ScheduledTask {
id: number;
executeAt: number; // Virtual timestamp
callback: TaskCallback;
label: string; // For debugging
}
// 2. THE SCHEDULER (The Brain)
export class VirtualScheduler {
private currentTime: number = 0;
private taskQueue: ScheduledTask[] = [];
private taskIdCounter: number = 0;
// State to simulate "system stalling" if waiting for an event that never comes
private isRunning: boolean = false;
constructor() {
// Bind methods to allow destructuring
this.schedule = this.schedule.bind(this);
this.now = this.now.bind(this);
}
/** Get the current virtual time */
public now(): number {
return this.currentTime;
}
/** Schedule a task (replaces setTimeout) */
public schedule(callback: TaskCallback, delayMs: number, label: string = "anonymous"): number {
const executeAt = this.currentTime + delayMs;
const id = this.taskIdCounter++;
const task: ScheduledTask = {
id,
executeAt,
callback,
label
};
// Insert sorted by execution time (Priority Queue simulation)
// If times are equal, FIFO order is preserved (determinism)
const insertionIndex = this.taskQueue.findIndex(t => t.executeAt > executeAt);
if (insertionIndex === -1) {
this.taskQueue.push(task);
} else {
this.taskQueue.splice(insertionIndex, 0, task);
}
return id;
}
/** The Engine: Drains the queue by advancing time */
public async runToCompletion(): Promise<void> {
this.isRunning = true;
while (this.taskQueue.length > 0) {
// 1. Peek the next task
const nextTask = this.taskQueue[0];
// 2. JUMP TIME FORWARD
// If the task is in the future, we teleport to that time immediately.
if (nextTask.executeAt > this.currentTime) {
this.currentTime = nextTask.executeAt;
}
// 3. Execute
this.taskQueue.shift(); // Dequeue
// Execute the task.
// We await it to handle async function bodies properly.
try {
await nextTask.callback();
} catch (e) {
console.error(`[Scheduler Error] Task "${nextTask.label}" crashed:`, e);
throw e;
}
}
this.isRunning = false;
}
}
// 3. THE RUNNER (The API)
export class DeterministicRunner {
private scheduler: VirtualScheduler;
constructor() {
this.scheduler = new VirtualScheduler();
}
/**
* Inject dependencies into the System Under Test (SUT).
* Usage: const { setTimeout, now } = runner.createContext();
*/
public createContext() {
return {
now: () => this.scheduler.now(),
// Deterministic setTimeout
setTimeout: (cb: () => void, ms: number) => {
return this.scheduler.schedule(cb, ms, `setTimeout(${ms})`);
},
// Deterministic setInterval (simplified)
setInterval: (cb: () => void, ms: number) => {
const ref = { cleared: false };
const loop = () => {
if (ref.cleared) return;
cb();
this.scheduler.schedule(loop, ms, `interval`);
};
this.scheduler.schedule(loop, ms, `interval-start`);
return ref;
},
// Add other mocks here (e.g., fetch, db calls)
};
}
/** Run the simulation */
public async run() {
await this.scheduler.runToCompletion();
}
/** Helper to assert final state */
public now() {
return this.scheduler.now();
}
}