The user wants a "deterministic test runner for async code with virtual time".
This is a common request in distributed systems or complex concurrent application testing (like Akka's TestKit, Tokio's time mocking, or Jest's timer mocks).
Core Concepts:
Deterministic: Given the same seed or input sequence, the execution order must always be the same. No race conditions inherent in OS thread scheduling.
Async Code: The code being tested uses Futures/Promises, async/await, or callbacks.
Virtual Time: The test runner controls the clock. sleep(5 seconds) shouldn't wait 5 real seconds. It should immediately advance the internal clock and resolve pending tasks scheduled for that time.
Key Components Needed:
Task System: A way to hold pending tasks.
Scheduler: A priority queue or sorted list of tasks sorted by execution time.
Executor: A loop that pulls tasks from the scheduler and runs them.
Time Control: Methods to advance time (tick, advance).
Mocking System: A way to intercept standard time-based operations (like setTimeout in JS or sleep in Rust/Go) and redirect them to the virtual scheduler.
Language Choice:
JavaScript/TypeScript: Good because of the single-threaded nature (easier to make deterministic) and Promise microtask queue. However, Node.js setTimeout is real-time.
Rust:tokio::test does this, but building one from scratch is instructive.
Go: Harder because goroutines are OS threads (M:N), making pure determinism tricky without a custom runtime.
Python:asyncio is good.
Decision:TypeScript is arguably the most accessible for this type of concept demonstration because of its pervasive use of async/await and the ease of manipulating the event loop via microtasks. Plus, many JS testing frameworks (Jest) use this concept, so users are familiar with the problem (flaky tests due to real time) and the solution (fake timers).
Architecture (TypeScript Implementation):
FakeTime Class:
now: current timestamp.
scheduler: A priority queue of { callback, time }.
schedule(delay, callback): Adds to queue.
advance(ms): Moves time forward, executes tasks that became due.
The Runner/Executor:
Needs to handle the async nature. When a task runs, it might return a Promise.
If a task is async, we need to wait for it to settle (microtasks to drain) before checking if we can run the next scheduled timer task. However, strictly speaking, virtual time usually only advances when explicitly told to or when awaiting a specific duration.
Correction: If we are writing a deterministic runner, we shouldn't rely on the real event loop for timing, but we must use the real event loop to execute the Javascript code.
Handling await:
Standard await puts things on the microtask queue.
await delay(100) needs to hook into our FakeTime.
Implementation Steps:
Step 1: The Scheduler (MinHeap)
We need a way to store callbacks in time order.
Step 2: The Virtual ClockcurrentTime: number.
setTimeout: Function to intercept.
Step 3: The Determinism Logic
The hard part about "Deterministic" usually involves interleaving. If two timers are set for the exact same time, which runs first?
Strict Determinism: Run them in insertion order (or sorted by ID).
Step 4: The "Runner" Loop
The user wants a "Runner". This suggests an API like:
typescript
const runner = new TestRunner();
await runner.run(async (context) => {
// context controls time
context.sleep(100);
});
Refining the approach for a standalone example:
Let's build a VirtualRuntime class.
It needs to mock setTimeout, clearTimeout, Promise, and Date.
Challenges with standard Promises:
Promise callbacks run as microtasks.
We can't easily "pause" inside an async function without using await.
We need a tick() function that processes everything scheduled for "right now" or "earlier".
Setup a global context or passed context for sleep.
The sleep function returns a Promise that puts its resolver into a priority queue keyed by currentTime + delay.
The Runner needs to drive the clock.
If we just run userLogic, it will hit await sleep(100). The promise is pending.
We need to simulate time passing.
Auto-advance vs Manual-advance:
Manual: User calls runner.advance(100).
Auto (Deterministic): The runner detects pending tasks, finds the soonest timestamp, and jumps the clock instantly to that point.
The prompt asks for a "Deterministic Test Runner".
I will implement an Auto-Advancing runner. It runs the test function, and whenever the test function awaits a time-based promise, the runner automatically advances the virtual clock to that point, effectively "fast-forwarding" time deterministically.
Plan:
Priority Queue: To handle scheduled tasks.
Virtual Clock: Tracks now.
Mock Timers:setTimeout equivalent.
Deterministic Scheduler: When multiple things happen at the same time, we ensure order.
Runner: Wraps the test execution.
Let's write the code in TypeScript. It offers the best clarity for async flows.
Drafting the code structure:
typescript
type Task = { time: number, id: number, callback: () => void };
class VirtualTime {
now = 0;
queue = new MinHeap();
counter = 0;
setTimeout(cb, delay) {
const task = { time: this.now + delay, id: this.counter++, callback: cb };
this.queue.push(task);
return task.id;
}
// Advances time to the next task and runs it
// Returns true if work was done
flushNext() {
const task = this.queue.pop();
if (!task) return false;
this.now = task.time; // Jump time
task.callback();
return true;
}
}
Wait, handling await:
If the user code is:
javascript
await sleep(100);
console.log("Done");
The sleep(100) puts a callback in the queue that resolves a promise.
The Test Runner needs to keep pumping the virtual time queue until the test Promise resolves.
The "Deterministic" Aspect:
In a real system, if two network requests fire at the same time, you don't know which returns first. In a virtual system, we define the order. I will allow the user to specify "Network Responses" or events at specific times to prove determinism.
Revised Plan:
Create VirtualClock: Manages time and scheduled tasks.
Create TestRunner: Accepts the test logic.
Create a mock System API that the test logic uses (e.g., system.sleep, system.fetch).
The Runner executes the logic.
While the logic is pending:
a. Find the next scheduled virtual time.
b. Advance clock to it.
c. Execute the task (which resolves the Promise the logic is waiting on).
d. Let the logic run until the next await.
Refining the "Runner" API:
The user wants to run tests.
typescript
const runner = new DeterministicRunner();
const result = await runner.execute(async (api) => {
await api.sleep(100);
return "Finished";
});
Edge Case: What if the code enters an infinite loop that doesn't await? The runner will hang. I should probably add a max iteration count or time limit (virtual time).
Implementation Language:
I will use TypeScript because it is standard for this type of architectural pattern (mocking async/time) and handles Promises natively.
Key Feature: Determinism
I will demonstrate this by scheduling two tasks at the exact same time and showing they execute in a specific order (insertion order), and then running the test twice to prove output is identical.
Constructing the Output:
Explanation: Brief overview of the components (Scheduler, Clock, Task Queue).
Code Implementation:
PriorityQueue (simple implementation).
VirtualTime (the core logic).
DeterministicRunner (the orchestrator).
Example Usage: A complex scenario involving race conditions handled virtually.
Let's refine the DeterministicRunner logic.
How do we "wait" for the test to finish inside the runner?
The runner calls testFn(api). This returns a Promise P.
We need to run the virtual clock until P resolves.
However, P is waiting on a Promise Q which is waiting on the Virtual Clock.
So, P is technically pending in the real event loop.
The runner cannot just await P immediately, because the code that resolves P (the virtual timer) hasn't run yet.
Crucial Logic:
We need to run the virtual clock inside the execution of the test, or interleave them.
Since JS is single-threaded, we can't interleave them easily without manual yielding.
BUT, await yields control.
sleep(10) schedules a task and returns a Promise P.
testFn returns a Promise (implicitly) representing the whole function, which is waiting on P.
The runner.execute needs to drive the clock.
Problem: If runner.execute just says while (!done) { clock.tick() }, it blocks the main thread, preventing the Promise resolution handlers from running?
Actually, clock.tick() calls the callback. The callback calls resolve() on the promise P.
Calling resolve() schedules the .then() handler of P on the real microtask queue.
So, inside tick(), when we call callback(), the Promise status changes, but the code afterawait P doesn't run until tick() returns and the current synchronous block finishes.
Wait, this is the tricky part.
If I do:
javascript
while (!promiseResolved) {
clock.advance(1); // This triggers callbacks.
}
Inside clock.advance, callback runs. It resolves a Promise.
The resolved Promise puts the "continuation of the test function" on the Microtask Queue.
The Microtask Queue only runs after the current synchronous function (clock.advance) returns.
So:
We need to let the Microtask Queue drain so the test function continues to the next await.
How to drain microtasks in JS? await Promise.resolve().
So the runner loop looks like:
javascript
async run(testFn) {
const done = testFn(); // Start it
while (true) {
// 1. Let the test run as far as it can synchronously
await Promise.resolve(); // Yield to microtasks
// Check if test is done
if (done is resolved) break;
// 2. Advance virtual time
const nextTask = this.clock.getNextTask();
if (!nextTask) throw new Error("Deadlock / Idle");
this.clock.execute(nextTask);
}
}
Wait, await Promise.resolve() drains the current queue. If the test function awaits a virtual timer, that timer isn't in the real queue. The test function is paused.
The microtask queue will drain, but the test function won't progress because it's waiting on the Virtual Timer.
So, we return control to runner.run.
Runner sees there are scheduled tasks in the virtual clock.
Runner executes the virtual task.
That virtual task calls resolve() on the real promise.
That resolve queues a new microtask.
We need to yield again to let that microtask run.
So the cycle is:
Run Test (it awaits).
Yield (let test move to await point).
Run Virtual Clock (resolve the await).
Yield (let test continue).
I will implement this in TypeScript. It's the cleanest way to demonstrate async interleaving and mock time.
Deterministic Mocking of "External" factors
To make it a complete test runner, I should probably add a way to inject specific "Deterministic Events" (e.g., "At 10ms, Network Packet A arrives").
Final Code Structure:
Heap: Basic priority queue.
VirtualTime: now, schedule, advance.
TestContext: The API given to the user (sleep, scheduleExternalEvent).
DeterministicRunner: The engine.
Intercepts async execution.
Drives virtual time.
Ensures completion.
Let's refine the advance logic.
If I have:
Timer A at 50ms
Timer B at 100ms
I want runner to automatically jump to 50ms, run A, then jump to 100ms, run B.
I will produce a self-contained TypeScript solution.
Self-Correction during thought process:
Does await Promise.resolve() reliably drain all pending microtasks in the runner's loop?
Yes, effectively. If the test has multiple .then() chains, await in the runner allows the JS engine to process that queue. Since the test is awaiting a virtual timer (not a real one), the test will pause. The runner resumes control. The runner triggers the virtual timer. This resolves the promise the test is waiting on. The runner must await again to let the test pick that up.
This is the "Deterministic Test Runner" pattern used in frameworks like jest (fake timers) but explicitly controlled rather than implicit global mocking.
I'll name the class VirtualTimeRunner.
Output Structure:
Concept: Explain the "Gate" model (Test awaits -> Time advances -> Test Resumes).
Implementation: TypeScript code.
Test Case: A scenario that would be flaky in real-time (race condition) but is deterministic here.
One specific detail: Order of execution at the same timestamp.
If I schedule A and B at t=10.
Real time: Who knows?
Virtual time: I'll enforce FIFO based on scheduling order. This guarantees determinism.
Let's write the code.
Language: TypeScript.
Key Requirements for the code:
No real time usage (no setTimeout inside the runner logic).
Must handle Promise microtasks correctly.
Must report the sequence of events to prove determinism.
(Self-correction: In a browser/node environment, you can't escape the real event loop if you use async/await. The "Virtual" part means we manually control the clock number, not that we bypass the OS scheduler. The determinism comes from us controlling exactly when the callbacks trigger relative to the test logic.)
Let's add a feature: runScenario. It takes a list of events (time, action) and the test logic, and interleaves them.
Steps for the final code:
Define Task interface.
VirtualScheduler: MinHeap of tasks.
Runner:
currentTime
schedule(time, cb)
tick(): Advance to next event.
run(async () => ...)
Start the async function.
Loop:
await flushMicrotasks()
If test done -> return.
If test pending and queue empty -> deadlock error.
If test pending and queue has items -> tick() (run callback).
Utility for flushMicrotasks: await Promise.resolve() is usually enough, but strictly speaking, to ensure we are at the end of the current event loop turn, we might use setImmediate (Node) or setTimeout(0)? No, that introduces real time.
Actually, standard practice for this logic:
The run loop itself is an async function.
When the user code hits await sleep(...), the user function returns a Promise.
The Runner needs to stop executing its logic to let the VM handle the Promise resolution?
Actually, if the Runner is synchronous, it blocks the Promise resolution.
The Runner must be async.
Correct Loop:
javascript
async run(testFn) {
const resultPromise = testFn(this.api);
while (true) {
// 1. Flush pending microtasks so the async function reaches its first 'await'
await this.yieldToMicrotasks();
if (resultPromise is resolved) return result;
// 2. We are idle. The test is waiting for time.
const nextTask = this.scheduler.pop();
if (!nextTask) throw new Error("Deadlock");
// 3. Advance time
this.currentTime = nextTask.time;
// 4. Execute the task
nextTask.callback();
}
}
How to implement yieldToMicrotasks?
await Promise.resolve() works for a single level. To be safe, await new Promise(r => process.nextTick(r)) in Node, or just await Promise.resolve().
Actually, there is a nuance.
When nextTask.callback() runs, it might call resolve(). That puts the continuation on the microtask queue.
We need to awaitagain to let that continuation run before we check if resultPromise is resolved.
So:
Run task (resolve promise).
Await (let test run).
Check if test finished.
Okay, I have the logic solidified. I will produce the TypeScript solution.
Creating a deterministic test runner for asynchronous code requires replacing the native event loop's non-deterministic timers with a scheduler that you control. This allows you to "fast-forward" time and execute tasks in a specific, reproducible order.
Below is a complete implementation of a Deterministic Virtual Time Runner in TypeScript.
Core Concepts
The Scheduler (Queue): Instead of using setTimeout, tasks are pushed into a priority queue sorted by execution time.
The Clock: A variable currentTime tracks the virtual time.
The Microtask Simulation: We use a specific yielding mechanism to ensure that code execution waits for the virtual clock to advance, preventing "real" time from interfering.
Implementation
typescript
Example Usage
Here is how you use the runner to test an async scenario. Notice how the test completes instantly in real-time, even though it simulates waiting for seconds.
typescript
// Helper to mimic an async delay using our Virtual Time
async function virtualDelay(api: VirtualTimeAPI, ms: number): Promise<void> {
return new Promise(resolve => {
api.setTimeout(resolve, ms);
});
}
// --- The Test ---
async function userLogic(api: VirtualTimeAPI) {
console.log(`[Start] Time: ${api.now()}ms`);
// Schedule parallel tasks
api.setTimeout(() => console.log(`[Timer A] Time: ${api.now()}ms`), 1000);
api.setTimeout(() => console.log(`[Timer B] Time: ${api.now()}ms`), 500);
// Wait for 2 seconds virtually
await virtualDelay(api, 2000);
console.log(`[End] Time: ${api.now()}ms`);
}
// Run the test
(async () => {
const runner = new DeterministicRunner();
console.log("--- Starting Deterministic Test ---");
const startRealTime = Date.now();
await runner.run(userLogic);
const endRealTime = Date.now();
console.log(`--- Test Finished ---`);
console.log(`Virtual Time Elapsed: ${runner.currentTime}ms`);
console.log(`Real Time Elapsed: ${endRealTime - startRealTime}ms (should be near 0)`);
})();
Expected Output
Notice that Timer B executes before Timer A because the scheduler sorts by time, and the real execution time is almost instant.
text
--- Starting Deterministic Test ---
[Start] Time: 0ms
[Timer B] Time: 500ms
[Timer A] Time: 1000ms
[End] Time: 2000ms
--- Test Finished ---
Virtual Time Elapsed: 2000ms
Real Time Elapsed: 2ms (should be near 0)
Key Design Decisions
Sorting: The queue is constantly sorted by (dueTime, taskId). This ensures that if two events happen at the exact same millisecond, they execute in the order they were scheduled (FIFO).
Sync Execution: The flushQueue runs a while loop synchronously. It does not yield to the real event loop until the queue is empty. This guarantees that state does not change unexpectedly between timers.
Promise Integration: The virtualDelay helper function wraps the api.setTimeout in a Promise. This allows you to use standard await syntax in your tests, but behind the scenes, it is feeding the runner's queue rather than the OS's queue.
/**
* Represents a scheduled task (macro-task).
*/
interface ScheduledTask {
id: number;
dueTime: number;
callback: () => void;
}
/**
* A deterministic runner that controls time and task execution order.
*/
export class DeterministicRunner {
private _currentTime: number = 0;
private taskQueue: ScheduledTask[] = [];
private taskIdCounter: number = 0;
// Flag to track if the test has completed
private isSettled: boolean = false;
public get currentTime(): number {
return this._currentTime;
}
/**
* Schedule a callback to run at a specific virtual time offset.
* This replaces setTimeout.
*/
public schedule(delay: number, callback: () => void): number {
const dueTime = this._currentTime + delay;
const task: ScheduledTask = {
id: this.taskIdCounter++,
dueTime,
callback,
};
this.taskQueue.push(task);
// Sort by time, then by insertion order for strict determinism
this.taskQueue.sort((a, b) => {
if (a.dueTime !== b.dueTime) return a.dueTime - b.dueTime;
return a.id - b.id;
});
return task.id;
}
/**
* The core loop. It drains the task queue synchronously.
*/
private flushQueue() {
while (this.taskQueue.length > 0) {
const nextTask = this.taskQueue.shift()!;
// FAST-FORWARD TIME
this._currentTime = nextTask.dueTime;
try {
nextTask.callback();
} catch (e) {
console.error("Error in scheduled task:", e);
throw e;
}
}
}
/**
* Executes the test logic deterministically.
*
* @param testFn The async test function. It receives a `VirtualTime` API object.
*/
public async run(testFn: (api: VirtualTimeAPI) => Promise<void>) {
const api: VirtualTimeAPI = {
// Wrapper around schedule to look like setTimeout
setTimeout: (cb: () => void, delay: number) => {
return this.schedule(delay, cb);
},
now: () => this._currentTime,
};
// 1. Start the test function
const testPromise = testFn(api);
// 2. Wait for the test function to finish its synchronous setup
// and hit its first 'await' on a virtual timer.
// We use setImmediate/process.nextTick logic simulation here conceptually,
// but since the testFn is async, we simply await it.
// However, we need to prevent the test from pausing indefinitely on a real timer.
// Note: The testFn MUST use the provided API to schedule time,
// otherwise it will hang waiting for real time.
// To bridge the gap between the Promise returning and the scheduler running,
// we monitor the queue.
// We wrap the execution in a Promise that resolves when the queue is empty
// and the test function is done.
return new Promise<void>(async (resolve, reject) => {
// When the user logic finishes, we trigger the flush.
testPromise.then(() => {
this.isSettled = true;
// If there are tasks left (e.g. fire-and-forget timers), we should probably flush them
// or decide if the test is strictly "done".
// For this runner, we assume test completion implies end of logical checks.
// However, to simulate time passing, we need to drive the loop.
}).catch(reject);
// 3. Drive the virtual clock loop
// We rely on the fact that `await` yields execution.
// We repeatedly flush the queue until the test promise settles.
// We need a mechanism to let the microtask queue breathe.
// This loop runs synchronously as much as possible.
try {
// Initial yield to let the testFn start
await Promise.resolve();
while (!this.isSettled || this.taskQueue.length > 0) {
if (this.taskQueue.length > 0) {
this.flushQueue();
} else {
// If queue is empty but test isn't settled, we are waiting for a Promise
// that isn't time-bound (e.g. a real fetch or logic error).
// Yield to the real event loop to prevent hard blocking.
await new Promise(r => setImmediate(r));
}
}
resolve();
} catch (e) {
reject(e);
}
});
}
}
// API Interface to pass to the user
export interface VirtualTimeAPI {
setTimeout: (callback: () => void, delay: number) => number;
now: () => number;
}