odem-rs-core 0.3.0

Core components of the odem-rs simulation framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use crate::{
	Puck,
	agent::Agent,
	config::Config,
	job::Job,
	ops::defer,
	simulator::{Prec, Sim, simulation},
};

use std::{
	boxed::Box,
	cell::Cell,
	collections::VecDeque,
	pin::{Pin, pin},
	rc::Rc,
	vec,
};

/// Simple configuration.
#[derive(Default)]
struct CustomConfig;

impl Config for CustomConfig {
	type Time = i32;
	type Rank = i32;
	type Data = ();
	type Plan = super::DefaultPlan<Self>;

	fn default_time(&self) -> Self::Time {
		0
	}

	fn default_rank(&self) -> Self::Rank {
		0
	}

	fn global_data(&self) -> &Self::Data {
		&()
	}
}

/// Wrapper around a shared counter to determine the ordering of scheduling ops.
struct Order(Cell<usize>);

impl Order {
	/// Creates a new shared counter with an initial value of 0.
	const fn new() -> Self {
		Self(Cell::new(0))
	}

	/// Returns the current value and advances the counter.
	fn next(&self) -> usize {
		let r = self.0.get();
		self.0.set(r + 1);
		r
	}
}

#[test]
fn stable_ordering() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		let shared = Order::new();

		// Create 100 agents.
		let mut pool = (0..100)
			.map(|_| Job::new(async { shared.next() }))
			.collect::<Box<_>>();

		// Activate them at the same time.
		let pucks = pool
			.iter_mut()
			.map(|job| sim.activate(unsafe { Pin::new_unchecked(job) }))
			.collect::<Box<_>>();

		// Await them in ascending order.
		for (order, puck) in pucks.into_iter().enumerate() {
			assert_eq!(
				puck.await,
				order,
				"Barring any other distinguishing factor, sorting of\
				 continuations is stable"
			);
		}
	}

	simulation(sim_main).unwrap();
}

#[test]
fn defer_passes_no_time() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		let now = sim.now();
		sim.defer().await;
		assert_eq!(now, sim.now(), "`defer` causes no model time to advance");
	}

	simulation(sim_main).unwrap();
}

#[test]
fn defer_skips_same_rank_jobs() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		let shared = Order::new();

		// Create 100 jobs.
		let mut pool = (0..100)
			.map(|_| Job::new(async { shared.next() }))
			.collect::<Box<_>>();

		// Activate them at the same time.
		for job in pool.iter_mut() {
			sim.activate(unsafe { Pin::new_unchecked(job) });
		}

		// Have them bypass the main job.
		sim.defer().await;

		assert_eq!(
			shared.next(),
			100,
			"`defer` causes all other continuations to be active first"
		);
	}

	simulation(sim_main).unwrap();
}

#[test]
fn defer_skips_lower_rank_agents() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		let shared = Rc::new(Order::new());

		// Create 100 lower-ranked agents.
		let mut pool = (0..100)
			.map(|_| {
				Agent::build()
					.with_rank(-1)
					.with_subject(shared.clone())
					.with_actions(async |shared: &Rc<Order>, _: &Sim<_>| shared.next())
					.finish()
			})
			.collect::<Box<_>>();

		// Activate them at the same time.
		for agent in pool.iter_mut() {
			sim.activate(unsafe { Pin::new_unchecked(agent) });
		}

		// Have them bypass the main job, even though they have a lower rank.
		sim.defer().await;

		assert_eq!(
			shared.next(),
			100,
			"`defer` causes all other continuations to be active first"
		);
	}

	simulation(sim_main).unwrap();
}

#[test]
fn time_ordering() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		// Create 100 jobs.
		let mut pool = (0..100)
			.map(|i| Job::new(async move { i }))
			.collect::<Box<_>>();

		// Activate them at different times.
		let pucks = pool
			.iter_mut()
			.enumerate()
			.map(|(i, job)| sim.schedule(unsafe { Pin::new_unchecked(job) }, i as i32))
			.collect::<Box<_>>();

		// Await them in ascending order and assert their equality with the
		// current model time.
		for puck in pucks {
			assert_eq!(
				puck.await,
				sim.now(),
				"Earlier continuations are processed before later ones"
			);
		}
	}

	simulation(sim_main).unwrap();
}

#[test]
fn agent_rank_ordering() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		// Create a shared counter for the agents to increment.
		let shared = Rc::new(Order::new());

		// Create agents and have them each increment the counter, returning
		// the previous value.
		let mut pool = (0..100)
			.map(|i| {
				Agent::build()
					.with_subject(shared.clone())
					.with_actions(async |i: &Rc<Order>, _: &Sim<_>| i.next())
					.with_rank(i)
					.finish()
			})
			.collect::<Box<_>>();

		// Activate the agents.
		let pucks = pool
			.iter_mut()
			.map(|job| sim.activate(unsafe { Pin::new_unchecked(job) }))
			.collect::<Box<_>>();

		// Defer sim_main so that the agents can run.
		defer().await;

		// Assert that the returned number is anti-proportional to the
		// agent's rank. This is because higher ranks are executed before
		// lower ranks, so an agent with rank 1 should return a number 1
		// smaller than an agent with rank 0.
		for (rank, puck) in pucks.into_iter().rev().enumerate() {
			let result = puck.await;
			assert_eq!(
				rank, result,
				"Agent's jobs are sorted according to their agent's rank \
				 in descending order"
			);
		}
	}

	simulation(sim_main).unwrap();
}

#[test]
fn job_precedence_linear_ordering() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		// Create a shared counter for the jobs to increment.
		let shared = Order::new();

		// Create 100 jobs and configure their precedence intervals.
		let mut pool = (0..100)
			.map(|prec| {
				Job::build()
					.with_actions(async { shared.next() })
					.with_precedence(Prec::from(prec))
					.finish()
			})
			.collect::<Box<_>>();

		// Activate the jobs.
		let pucks = pool
			.iter_mut()
			.map(|job| sim.activate(unsafe { Pin::new_unchecked(job) }))
			.collect::<Box<_>>();

		// Defer so that the jobs can run.
		defer().await;

		// Assert that the returned number is proportional to the job's
		// precedence, indicating the correct order of activations.
		for (prec, puck) in pucks.into_iter().enumerate() {
			let result = puck.await;
			assert_eq!(
				prec, result,
				"Jobs are scheduled according to their precedence in \
				 ascending order"
			);
		}
	}

	simulation(sim_main).unwrap();
}

#[test]
fn job_precedence_nested_ordering() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		// Create a shared counter for the jobs to increment.
		let shared = Order::new();

		let mut pool1 = vec![];
		let mut pool2 = vec![];
		let mut pool3 = vec![];

		// Split the precedence interval into nested partitions.
		for prec1 in sim.active().prec().split(4).unwrap() {
			pool1.push(
				Job::build()
					.with_actions(async { shared.next() })
					.with_precedence(prec1)
					.finish(),
			);

			for prec2 in prec1.split(3).unwrap() {
				pool2.push(
					Job::build()
						.with_actions(async { shared.next() })
						.with_precedence(prec2)
						.finish(),
				);

				for prec3 in prec2.split(2).unwrap() {
					pool3.push(
						Job::build()
							.with_actions(async { shared.next() })
							.with_precedence(prec3)
							.finish(),
					);
				}
			}
		}

		// Activate the jobs.
		let mut pucks1 = pool1
			.iter_mut()
			.map(|job| sim.activate(unsafe { Pin::new_unchecked(job) }))
			.collect::<VecDeque<_>>();

		let mut pucks2 = pool2
			.iter_mut()
			.map(|job| sim.activate(unsafe { Pin::new_unchecked(job) }))
			.collect::<VecDeque<_>>();

		let mut pucks3 = pool3
			.iter_mut()
			.map(|job| sim.activate(unsafe { Pin::new_unchecked(job) }))
			.collect::<VecDeque<_>>();

		// Defer sim_main so that the jobs can run.
		defer().await;

		// Ensure that parent nodes sort before their children and earlier
		// siblings, as well as all of their child nodes sort before later
		// siblings and their child nodes.
		//
		//       0
		//   1       5
		// 2 3 4   6 7 8
		let mut i = 0;
		for _ in 0..4 {
			assert_eq!(pucks1.pop_front().unwrap().await, i);
			i += 1;

			for _ in 0..3 {
				assert_eq!(pucks2.pop_front().unwrap().await, i);
				i += 1;

				for _ in 0..2 {
					assert_eq!(pucks3.pop_front().unwrap().await, i);
					i += 1;
				}
			}
		}
	}

	simulation(sim_main).unwrap();
}

#[test]
fn agent_mark_ordering() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		let shared = Rc::new(Order::new());

		// Create 4 agents.
		let mut pool = (0..4)
			.map(|i| {
				Agent::new((
					(i, shared.clone()),
					async |(i, shared): &(usize, Rc<Order>), sim: &Sim<_>| {
						// Create 2 jobs for each agent.
						let mut pool = (0..3)
							.map(|_| {
								Job::new(async {
									// Make sure that the jobs are scheduled first and run later.
									sim.advance(1).await;
									shared.next()
								})
							})
							.collect::<Box<_>>();

						// Activate them at the same time.
						let mut pucks = vec![];

						for job in pool.iter_mut() {
							pucks.push(sim.activate(unsafe { Pin::new_unchecked(job) }));

							// Leave time for other agents to activate their jobs.
							// This is necessary to cause the scheduler
							// to interleave the jobs if it sorts them stably only.
							sim.defer().await;
						}

						// Ensure that the jobs are executed contiguously, even if
						// the initially activated agents ordering interleaves.
						for (j, puck) in pucks.into_iter().enumerate() {
							let order = puck.await;
							assert_eq!(
								order,
								i * 3 + j,
								"All jobs of agent A should be sorted before the \
								 jobs of agent B, if there is at least one job \
								 of A sorted before all jobs of B."
							);
						}
					},
				))
			})
			.collect::<Box<_>>();

		// Activate them at the same time.
		for agent in pool.iter_mut() {
			sim.activate(unsafe { Pin::new_unchecked(agent) });
		}

		// Give them time to execute.
		sim.advance(2).await;
	}

	simulation(sim_main).unwrap();
}

#[test]
fn agent_rank_update() {
	async fn sim_main(sim: &Sim<CustomConfig>) {
		let shared = Rc::new(Order::new());

		// Create two agents, one with a low rank, one with a higher rank.
		let smith = pin!(
			Agent::build()
				.with_rank(0)
				.with_subject(shared.clone())
				.with_actions(async |shared: &Rc<Order>, sim: &Sim<CustomConfig>| {
					// Create two jobs and schedule them immediately.
					let j1 = pin!(Job::new(async { shared.next() }));

					// Start the job while we have the low rank.
					let p1 = sim.activate(j1);

					// Promote this agent.
					sim.update_rank(1);

					// Since this agent has been promoted, this job should have
					// executed first.
					assert_eq!(p1.await, 0);
				})
				.finish()
		);

		let brown = pin!(
			Agent::build()
				.with_rank(1)
				.with_subject(shared.clone())
				.with_actions(async |shared: &Rc<Order>, sim: &Sim<CustomConfig>| {
					// Create two jobs and schedule them at different times.
					let j1 = pin!(Job::new(async { shared.next() }));

					let p1 = sim.activate(j1);

					// Demote this agent.
					sim.update_rank(0);

					// Since this agent has been demoted, this job should have
					// executed later.
					assert_eq!(p1.await, 1);
				})
				.finish()
		);

		// Activate the agents and give them time to terminate.
		sim.activate(smith);
		sim.activate(brown);

		sim.advance(2).await;
	}

	simulation(sim_main).unwrap();
}