host.rs 34.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Validation host - is the primary interface for this crate. It allows the clients to enqueue
//! jobs for PVF execution or preparation.
//!
//! The validation host is represented by a future/task that runs an event-loop and by a handle,
//! [`ValidationHost`], that allows communication with that event-loop.

use crate::{
24
	artifacts::{ArtifactId, ArtifactPathId, ArtifactState, Artifacts},
25
26
	execute,
	metrics::Metrics,
27
	prepare, PrepareResult, Priority, Pvf, ValidationError, LOG_TARGET,
28
29
};
use always_assert::never;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
30
use async_std::path::{Path, PathBuf};
31
32
use futures::{
	channel::{mpsc, oneshot},
Shawn Tabrizi's avatar
Shawn Tabrizi committed
33
34
35
36
37
38
	Future, FutureExt, SinkExt, StreamExt,
};
use polkadot_parachain::primitives::ValidationResult;
use std::{
	collections::HashMap,
	time::{Duration, SystemTime},
39
40
41
42
43
};

/// An alias to not spell the type for the oneshot sender for the PVF execution result.
pub(crate) type ResultSender = oneshot::Sender<Result<ValidationResult, ValidationError>>;

44
45
46
/// Transmission end used for sending the PVF preparation result.
pub(crate) type PrepareResultSender = oneshot::Sender<PrepareResult>;

47
48
49
50
51
52
53
/// A handle to the async process serving the validation host requests.
#[derive(Clone)]
pub struct ValidationHost {
	to_host_tx: mpsc::Sender<ToHost>,
}

impl ValidationHost {
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
	/// Precheck PVF with the given code, i.e. verify that it compiles within a reasonable time limit.
	/// The result of execution will be sent to the provided result sender.
	///
	/// This is async to accommodate the fact a possibility of back-pressure. In the vast majority of
	/// situations this function should return immediately.
	///
	/// Returns an error if the request cannot be sent to the validation host, i.e. if it shut down.
	pub async fn precheck_pvf(
		&mut self,
		pvf: Pvf,
		result_tx: PrepareResultSender,
	) -> Result<(), String> {
		self.to_host_tx
			.send(ToHost::PrecheckPvf { pvf, result_tx })
			.await
			.map_err(|_| "the inner loop hung up".to_string())
	}

72
73
	/// Execute PVF with the given code, execution timeout, parameters and priority.
	/// The result of execution will be sent to the provided result sender.
74
	///
Bernhard Schuster's avatar
Bernhard Schuster committed
75
76
	/// This is async to accommodate the fact a possibility of back-pressure. In the vast majority of
	/// situations this function should return immediately.
77
78
79
80
81
	///
	/// Returns an error if the request cannot be sent to the validation host, i.e. if it shut down.
	pub async fn execute_pvf(
		&mut self,
		pvf: Pvf,
82
		execution_timeout: Duration,
83
84
85
86
87
		params: Vec<u8>,
		priority: Priority,
		result_tx: ResultSender,
	) -> Result<(), String> {
		self.to_host_tx
88
			.send(ToHost::ExecutePvf { pvf, execution_timeout, params, priority, result_tx })
89
90
91
92
93
94
			.await
			.map_err(|_| "the inner loop hung up".to_string())
	}

	/// Sends a signal to the validation host requesting to prepare a list of the given PVFs.
	///
Bernhard Schuster's avatar
Bernhard Schuster committed
95
96
	/// This is async to accommodate the fact a possibility of back-pressure. In the vast majority of
	/// situations this function should return immediately.
97
98
99
100
101
102
103
104
105
106
107
	///
	/// Returns an error if the request cannot be sent to the validation host, i.e. if it shut down.
	pub async fn heads_up(&mut self, active_pvfs: Vec<Pvf>) -> Result<(), String> {
		self.to_host_tx
			.send(ToHost::HeadsUp { active_pvfs })
			.await
			.map_err(|_| "the inner loop hung up".to_string())
	}
}

enum ToHost {
108
109
110
111
	PrecheckPvf {
		pvf: Pvf,
		result_tx: PrepareResultSender,
	},
112
113
114
115
116
117
118
119
120
121
	ExecutePvf {
		pvf: Pvf,
		execution_timeout: Duration,
		params: Vec<u8>,
		priority: Priority,
		result_tx: ResultSender,
	},
	HeadsUp {
		active_pvfs: Vec<Pvf>,
	},
122
123
124
125
126
127
128
129
}

/// Configuration for the validation host.
pub struct Config {
	/// The root directory where the prepared artifacts can be stored.
	pub cache_path: PathBuf,
	/// The path to the program that can be used to spawn the prepare workers.
	pub prepare_worker_program_path: PathBuf,
Denis_P's avatar
Denis_P committed
130
	/// The time allotted for a prepare worker to spawn and report to the host.
131
132
133
134
135
136
137
138
	pub prepare_worker_spawn_timeout: Duration,
	/// The maximum number of workers that can be spawned in the prepare pool for tasks with the
	/// priority below critical.
	pub prepare_workers_soft_max_num: usize,
	/// The absolute number of workers that can be spawned in the prepare pool.
	pub prepare_workers_hard_max_num: usize,
	/// The path to the program that can be used to spawn the execute workers.
	pub execute_worker_program_path: PathBuf,
Denis_P's avatar
Denis_P committed
139
	/// The time allotted for an execute worker to spawn and report to the host.
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
	pub execute_worker_spawn_timeout: Duration,
	/// The maximum number of execute workers that can run at the same time.
	pub execute_workers_max_num: usize,
}

impl Config {
	/// Create a new instance of the configuration.
	pub fn new(cache_path: std::path::PathBuf, program_path: std::path::PathBuf) -> Self {
		// Do not contaminate the other parts of the codebase with the types from async_std.
		let cache_path = PathBuf::from(cache_path);
		let program_path = PathBuf::from(program_path);

		Self {
			cache_path,
			prepare_worker_program_path: program_path.clone(),
			prepare_worker_spawn_timeout: Duration::from_secs(3),
156
157
			prepare_workers_soft_max_num: 1,
			prepare_workers_hard_max_num: 1,
158
159
			execute_worker_program_path: program_path,
			execute_worker_spawn_timeout: Duration::from_secs(3),
160
			execute_workers_max_num: 2,
161
162
163
164
165
166
167
168
169
170
		}
	}
}

/// Start the validation host.
///
/// Returns a [handle][`ValidationHost`] to the started validation host and the future. The future
/// must be polled in order for validation host to function.
///
/// The future should not return normally but if it does then that indicates an unrecoverable error.
Denis_P's avatar
Denis_P committed
171
/// In that case all pending requests will be canceled, dropping the result senders and new ones
172
/// will be rejected.
173
pub fn start(config: Config, metrics: Metrics) -> (ValidationHost, impl Future<Output = ()>) {
174
175
176
177
178
	let (to_host_tx, to_host_rx) = mpsc::channel(10);

	let validation_host = ValidationHost { to_host_tx };

	let (to_prepare_pool, from_prepare_pool, run_prepare_pool) = prepare::start_pool(
179
		metrics.clone(),
180
181
		config.prepare_worker_program_path.clone(),
		config.cache_path.clone(),
182
183
184
185
		config.prepare_worker_spawn_timeout,
	);

	let (to_prepare_queue_tx, from_prepare_queue_rx, run_prepare_queue) = prepare::start_queue(
186
		metrics.clone(),
187
188
189
190
191
192
193
194
		config.prepare_workers_soft_max_num,
		config.prepare_workers_hard_max_num,
		config.cache_path.clone(),
		to_prepare_pool,
		from_prepare_pool,
	);

	let (to_execute_queue_tx, run_execute_queue) = execute::start(
195
		metrics.clone(),
196
197
198
199
200
201
202
203
204
205
206
		config.execute_worker_program_path.to_owned(),
		config.execute_workers_max_num,
		config.execute_worker_spawn_timeout,
	);

	let (to_sweeper_tx, to_sweeper_rx) = mpsc::channel(100);
	let run_sweeper = sweeper_task(to_sweeper_rx);

	let run = async move {
		let artifacts = Artifacts::new(&config.cache_path).await;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
207
		futures::pin_mut!(run_prepare_queue, run_prepare_pool, run_execute_queue, run_sweeper);
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

		run(
			Inner {
				cache_path: config.cache_path,
				cleanup_pulse_interval: Duration::from_secs(3600),
				artifact_ttl: Duration::from_secs(3600 * 24),
				artifacts,
				to_host_rx,
				to_prepare_queue_tx,
				from_prepare_queue_rx,
				to_execute_queue_tx,
				to_sweeper_tx,
				awaiting_prepare: AwaitingPrepare::default(),
			},
			run_prepare_pool,
			run_prepare_queue,
			run_execute_queue,
			run_sweeper,
		)
		.await
	};

	(validation_host, run)
}

/// An execution request that should execute the PVF (known in the context) and send the results
/// to the given result sender.
#[derive(Debug)]
struct PendingExecutionRequest {
237
	execution_timeout: Duration,
238
239
240
241
	params: Vec<u8>,
	result_tx: ResultSender,
}

Bernhard Schuster's avatar
Bernhard Schuster committed
242
/// A mapping from an artifact ID which is in preparation state to the list of pending execution
Denis_P's avatar
Denis_P committed
243
/// requests that should be executed once the artifact's preparation is finished.
244
245
246
247
#[derive(Default)]
struct AwaitingPrepare(HashMap<ArtifactId, Vec<PendingExecutionRequest>>);

impl AwaitingPrepare {
248
249
250
251
252
253
254
255
256
257
258
259
	fn add(
		&mut self,
		artifact_id: ArtifactId,
		execution_timeout: Duration,
		params: Vec<u8>,
		result_tx: ResultSender,
	) {
		self.0.entry(artifact_id).or_default().push(PendingExecutionRequest {
			execution_timeout,
			params,
			result_tx,
		});
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
	}

	fn take(&mut self, artifact_id: &ArtifactId) -> Vec<PendingExecutionRequest> {
		self.0.remove(artifact_id).unwrap_or_default()
	}
}

struct Inner {
	cache_path: PathBuf,
	cleanup_pulse_interval: Duration,
	artifact_ttl: Duration,
	artifacts: Artifacts,

	to_host_rx: mpsc::Receiver<ToHost>,

	to_prepare_queue_tx: mpsc::Sender<prepare::ToQueue>,
	from_prepare_queue_rx: mpsc::UnboundedReceiver<prepare::FromQueue>,

	to_execute_queue_tx: mpsc::Sender<execute::ToQueue>,
	to_sweeper_tx: mpsc::Sender<PathBuf>,

	awaiting_prepare: AwaitingPrepare,
}

#[derive(Debug)]
struct Fatal;

async fn run(
	Inner {
		cache_path,
		cleanup_pulse_interval,
		artifact_ttl,
		mut artifacts,
		to_host_rx,
		from_prepare_queue_rx,
		mut to_prepare_queue_tx,
		mut to_execute_queue_tx,
		mut to_sweeper_tx,
		mut awaiting_prepare,
	}: Inner,
	prepare_pool: impl Future<Output = ()> + Unpin,
	prepare_queue: impl Future<Output = ()> + Unpin,
	execute_queue: impl Future<Output = ()> + Unpin,
	sweeper: impl Future<Output = ()> + Unpin,
) {
	macro_rules! break_if_fatal {
		($expr:expr) => {
			match $expr {
				Err(Fatal) => break,
				Ok(v) => v,
			}
		};
	}

	let cleanup_pulse = pulse_every(cleanup_pulse_interval).fuse();
	futures::pin_mut!(cleanup_pulse);

	let mut to_host_rx = to_host_rx.fuse();
	let mut from_prepare_queue_rx = from_prepare_queue_rx.fuse();

	// Make sure that the task-futures are fused.
	let mut prepare_queue = prepare_queue.fuse();
	let mut prepare_pool = prepare_pool.fuse();
	let mut execute_queue = execute_queue.fuse();
	let mut sweeper = sweeper.fuse();

	loop {
		// biased to make it behave deterministically for tests.
		futures::select_biased! {
			_ = prepare_queue => {
				never!("prepare_pool: long-running task never concludes; qed");
				break;
			},
			_ = prepare_pool => {
				never!("prepare_pool: long-running task never concludes; qed");
				break;
			},
			_ = execute_queue => {
				never!("execute_queue: long-running task never concludes; qed");
				break;
			},
			_ = sweeper => {
				never!("sweeper: long-running task never concludes; qed");
				break;
			},
			() = cleanup_pulse.select_next_some() => {
				// `select_next_some` because we don't expect this to fail, but if it does, we
				// still don't fail. The tradeoff is that the compiled cache will start growing
				// in size. That is, however, rather a slow process and hopefully the operator
				// will notice it.

				break_if_fatal!(handle_cleanup_pulse(
					&cache_path,
					&mut to_sweeper_tx,
					&mut artifacts,
					artifact_ttl,
				).await);
			},
			to_host = to_host_rx.next() => {
				let to_host = break_if_fatal!(to_host.ok_or(Fatal));

				break_if_fatal!(handle_to_host(
					&cache_path,
					&mut artifacts,
					&mut to_prepare_queue_tx,
					&mut to_execute_queue_tx,
					&mut awaiting_prepare,
					to_host,
				)
				.await);
			},
			from_prepare_queue = from_prepare_queue_rx.next() => {
372
				let from_queue = break_if_fatal!(from_prepare_queue.ok_or(Fatal));
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387

				// Note that preparation always succeeds.
				//
				// That's because the error conditions are written into the artifact and will be
				// reported at the time of the  execution. It potentially, but not necessarily,
				// can be scheduled as a result of this function call, in case there are pending
				// executions.
				//
				// We could be eager in terms of reporting and plumb the result from the prepartion
				// worker but we don't for the sake of simplicity.
				break_if_fatal!(handle_prepare_done(
					&cache_path,
					&mut artifacts,
					&mut to_execute_queue_tx,
					&mut awaiting_prepare,
388
					from_queue,
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
				).await);
			},
		}
	}
}

async fn handle_to_host(
	cache_path: &Path,
	artifacts: &mut Artifacts,
	prepare_queue: &mut mpsc::Sender<prepare::ToQueue>,
	execute_queue: &mut mpsc::Sender<execute::ToQueue>,
	awaiting_prepare: &mut AwaitingPrepare,
	to_host: ToHost,
) -> Result<(), Fatal> {
	match to_host {
404
405
406
		ToHost::PrecheckPvf { pvf, result_tx } => {
			handle_precheck_pvf(artifacts, prepare_queue, pvf, result_tx).await?;
		},
407
		ToHost::ExecutePvf { pvf, execution_timeout, params, priority, result_tx } => {
408
409
410
411
412
413
414
			handle_execute_pvf(
				cache_path,
				artifacts,
				prepare_queue,
				execute_queue,
				awaiting_prepare,
				pvf,
415
				execution_timeout,
416
417
418
419
420
				params,
				priority,
				result_tx,
			)
			.await?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
421
		},
422
423
		ToHost::HeadsUp { active_pvfs } => {
			handle_heads_up(artifacts, prepare_queue, active_pvfs).await?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
424
		},
425
426
427
428
429
	}

	Ok(())
}

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
async fn handle_precheck_pvf(
	artifacts: &mut Artifacts,
	prepare_queue: &mut mpsc::Sender<prepare::ToQueue>,
	pvf: Pvf,
	result_sender: PrepareResultSender,
) -> Result<(), Fatal> {
	let artifact_id = pvf.as_artifact_id();

	if let Some(state) = artifacts.artifact_state_mut(&artifact_id) {
		match state {
			ArtifactState::Prepared { last_time_needed } => {
				*last_time_needed = SystemTime::now();
				let _ = result_sender.send(Ok(()));
			},
			ArtifactState::Preparing { waiting_for_response } =>
				waiting_for_response.push(result_sender),
			ArtifactState::FailedToProcess(result) => {
				let _ = result_sender.send(PrepareResult::Err(result.clone()));
			},
		}
	} else {
		artifacts.insert_preparing(artifact_id, vec![result_sender]);
		send_prepare(prepare_queue, prepare::ToQueue::Enqueue { priority: Priority::Normal, pvf })
			.await?;
	}
	Ok(())
}

458
459
460
461
462
463
464
async fn handle_execute_pvf(
	cache_path: &Path,
	artifacts: &mut Artifacts,
	prepare_queue: &mut mpsc::Sender<prepare::ToQueue>,
	execute_queue: &mut mpsc::Sender<execute::ToQueue>,
	awaiting_prepare: &mut AwaitingPrepare,
	pvf: Pvf,
465
	execution_timeout: Duration,
466
467
468
469
470
471
472
473
	params: Vec<u8>,
	priority: Priority,
	result_tx: ResultSender,
) -> Result<(), Fatal> {
	let artifact_id = pvf.as_artifact_id();

	if let Some(state) = artifacts.artifact_state_mut(&artifact_id) {
		match state {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
474
			ArtifactState::Prepared { ref mut last_time_needed } => {
475
476
477
478
479
				*last_time_needed = SystemTime::now();

				send_execute(
					execute_queue,
					execute::ToQueue::Enqueue {
480
						artifact: ArtifactPathId::new(artifact_id, cache_path),
481
						execution_timeout,
482
483
484
485
486
						params,
						result_tx,
					},
				)
				.await?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
487
			},
488
			ArtifactState::Preparing { waiting_for_response: _ } => {
489
490
				send_prepare(
					prepare_queue,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
491
					prepare::ToQueue::Amend { priority, artifact_id: artifact_id.clone() },
492
493
494
				)
				.await?;

495
				awaiting_prepare.add(artifact_id, execution_timeout, params, result_tx);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
496
			},
497
498
499
			ArtifactState::FailedToProcess(error) => {
				let _ = result_tx.send(Err(ValidationError::from(error.clone())));
			},
500
501
502
503
		}
	} else {
		// Artifact is unknown: register it and enqueue a job with the corresponding priority and
		//
504
		artifacts.insert_preparing(artifact_id.clone(), Vec::new());
505
506
		send_prepare(prepare_queue, prepare::ToQueue::Enqueue { priority, pvf }).await?;

507
		awaiting_prepare.add(artifact_id, execution_timeout, params, result_tx);
508
509
	}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
510
	return Ok(())
511
512
513
514
515
516
517
518
519
520
521
522
523
}

async fn handle_heads_up(
	artifacts: &mut Artifacts,
	prepare_queue: &mut mpsc::Sender<prepare::ToQueue>,
	active_pvfs: Vec<Pvf>,
) -> Result<(), Fatal> {
	let now = SystemTime::now();

	for active_pvf in active_pvfs {
		let artifact_id = active_pvf.as_artifact_id();
		if let Some(state) = artifacts.artifact_state_mut(&artifact_id) {
			match state {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
524
				ArtifactState::Prepared { last_time_needed, .. } => {
525
					*last_time_needed = now;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
526
				},
527
				ArtifactState::Preparing { waiting_for_response: _ } => {
528
529
					// Already preparing. We don't need to send a priority amend either because
					// it can't get any lower than the background.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
530
				},
531
				ArtifactState::FailedToProcess(_) => {},
532
533
534
			}
		} else {
			// The artifact is unknown: register it and put a background job into the prepare queue.
535
			artifacts.insert_preparing(artifact_id.clone(), Vec::new());
536
537
538

			send_prepare(
				prepare_queue,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
539
				prepare::ToQueue::Enqueue { priority: Priority::Background, pvf: active_pvf },
540
541
542
543
544
545
546
547
548
549
550
551
552
			)
			.await?;
		}
	}

	Ok(())
}

async fn handle_prepare_done(
	cache_path: &Path,
	artifacts: &mut Artifacts,
	execute_queue: &mut mpsc::Sender<execute::ToQueue>,
	awaiting_prepare: &mut AwaitingPrepare,
553
	from_queue: prepare::FromQueue,
554
) -> Result<(), Fatal> {
555
556
	let prepare::FromQueue { artifact_id, result } = from_queue;

557
558
559
560
561
562
563
564
565
	// Make some sanity checks and extract the current state.
	let state = match artifacts.artifact_state_mut(&artifact_id) {
		None => {
			// before sending request to prepare, the artifact is inserted with `preparing` state;
			// the requests are deduplicated for the same artifact id;
			// there is only one possible state change: prepare is done;
			// thus the artifact cannot be unknown, only preparing;
			// qed.
			never!("an unknown artifact was prepared: {:?}", artifact_id);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
566
567
			return Ok(())
		},
568
569
570
571
572
573
574
		Some(ArtifactState::Prepared { .. }) => {
			// before sending request to prepare, the artifact is inserted with `preparing` state;
			// the requests are deduplicated for the same artifact id;
			// there is only one possible state change: prepare is done;
			// thus the artifact cannot be prepared, only preparing;
			// qed.
			never!("the artifact is already prepared: {:?}", artifact_id);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
575
576
			return Ok(())
		},
577
578
579
580
581
582
		Some(ArtifactState::FailedToProcess(_)) => {
			// The reasoning is similar to the above, the artifact cannot be
			// processed at this point.
			never!("the artifact is already processed unsuccessfully: {:?}", artifact_id);
			return Ok(())
		},
583
		Some(state @ ArtifactState::Preparing { waiting_for_response: _ }) => state,
584
585
	};

586
587
588
589
590
591
	if let ArtifactState::Preparing { waiting_for_response } = state {
		for result_sender in waiting_for_response.drain(..) {
			let _ = result_sender.send(result.clone());
		}
	}

592
593
594
	// It's finally time to dispatch all the execution requests that were waiting for this artifact
	// to be prepared.
	let pending_requests = awaiting_prepare.take(&artifact_id);
595
	for PendingExecutionRequest { execution_timeout, params, result_tx } in pending_requests {
596
597
598
		if result_tx.is_canceled() {
			// Preparation could've taken quite a bit of time and the requester may be not interested
			// in execution anymore, in which case we just skip the request.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
599
			continue
600
601
		}

602
603
604
605
606
607
		// Don't send failed artifacts to the execution's queue.
		if let Err(ref error) = result {
			let _ = result_tx.send(Err(ValidationError::from(error.clone())));
			continue
		}

608
609
		send_execute(
			execute_queue,
610
611
			execute::ToQueue::Enqueue {
				artifact: ArtifactPathId::new(artifact_id.clone(), cache_path),
612
				execution_timeout,
613
614
615
				params,
				result_tx,
			},
616
617
618
619
		)
		.await?;
	}

620
621
622
623
	*state = match result {
		Ok(()) => ArtifactState::Prepared { last_time_needed: SystemTime::now() },
		Err(error) => ArtifactState::FailedToProcess(error.clone()),
	};
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648

	Ok(())
}

async fn send_prepare(
	prepare_queue: &mut mpsc::Sender<prepare::ToQueue>,
	to_queue: prepare::ToQueue,
) -> Result<(), Fatal> {
	prepare_queue.send(to_queue).await.map_err(|_| Fatal)
}

async fn send_execute(
	execute_queue: &mut mpsc::Sender<execute::ToQueue>,
	to_queue: execute::ToQueue,
) -> Result<(), Fatal> {
	execute_queue.send(to_queue).await.map_err(|_| Fatal)
}

async fn handle_cleanup_pulse(
	cache_path: &Path,
	sweeper_tx: &mut mpsc::Sender<PathBuf>,
	artifacts: &mut Artifacts,
	artifact_ttl: Duration,
) -> Result<(), Fatal> {
	let to_remove = artifacts.prune(artifact_ttl);
649
650
651
652
653
	tracing::info!(
		target: LOG_TARGET,
		"PVF pruning: {} artifacts reached their end of life",
		to_remove.len(),
	);
654
	for artifact_id in to_remove {
655
656
657
658
659
		tracing::debug!(
			target: LOG_TARGET,
			validation_code_hash = ?artifact_id.code_hash,
			"pruning artifact",
		);
660
661
662
663
664
665
666
667
668
669
670
671
672
		let artifact_path = artifact_id.path(cache_path);
		sweeper_tx.send(artifact_path).await.map_err(|_| Fatal)?;
	}

	Ok(())
}

/// A simple task which sole purpose is to delete files thrown at it.
async fn sweeper_task(mut sweeper_rx: mpsc::Receiver<PathBuf>) {
	loop {
		match sweeper_rx.next().await {
			None => break,
			Some(condemned) => {
673
674
675
676
677
678
679
				let result = async_std::fs::remove_file(&condemned).await;
				tracing::trace!(
					target: LOG_TARGET,
					?result,
					"Sweeping the artifact file {}",
					condemned.display(),
				);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
680
			},
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
		}
	}
}

/// A stream that yields a pulse continuously at a given interval.
fn pulse_every(interval: std::time::Duration) -> impl futures::Stream<Item = ()> {
	futures::stream::unfold(interval, {
		|interval| async move {
			futures_timer::Delay::new(interval).await;
			Some(((), interval))
		}
	})
	.map(|_| ())
}

#[cfg(test)]
mod tests {
	use super::*;
699
	use crate::{InvalidCandidate, PrepareError};
700
	use assert_matches::assert_matches;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
701
	use futures::future::BoxFuture;
702

703
704
	const TEST_EXECUTION_TIMEOUT: Duration = Duration::from_secs(3);

705
706
707
708
709
710
711
712
713
714
715
716
717
718
	#[async_std::test]
	async fn pulse_test() {
		let pulse = pulse_every(Duration::from_millis(100));
		futures::pin_mut!(pulse);

		for _ in 0usize..5usize {
			let start = std::time::Instant::now();
			let _ = pulse.next().await.unwrap();

			let el = start.elapsed().as_millis();
			assert!(el > 50 && el < 150, "{}", el);
		}
	}

Denis_P's avatar
Denis_P committed
719
	/// Creates a new PVF which artifact id can be uniquely identified by the given number.
720
721
722
723
724
	fn artifact_id(descriminator: u32) -> ArtifactId {
		Pvf::from_discriminator(descriminator).as_artifact_id()
	}

	fn artifact_path(descriminator: u32) -> PathBuf {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
725
		artifact_id(descriminator).path(&PathBuf::from(std::env::temp_dir())).to_owned()
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
	}

	struct Builder {
		cleanup_pulse_interval: Duration,
		artifact_ttl: Duration,
		artifacts: Artifacts,
	}

	impl Builder {
		fn default() -> Self {
			Self {
				// these are selected high to not interfere in tests in which pruning is irrelevant.
				cleanup_pulse_interval: Duration::from_secs(3600),
				artifact_ttl: Duration::from_secs(3600),

				artifacts: Artifacts::empty(),
			}
		}

		fn build(self) -> Test {
			Test::new(self)
		}
	}

	struct Test {
		to_host_tx: Option<mpsc::Sender<ToHost>>,

		to_prepare_queue_rx: mpsc::Receiver<prepare::ToQueue>,
		from_prepare_queue_tx: mpsc::UnboundedSender<prepare::FromQueue>,
		to_execute_queue_rx: mpsc::Receiver<execute::ToQueue>,
		to_sweeper_rx: mpsc::Receiver<PathBuf>,

		run: BoxFuture<'static, ()>,
	}

	impl Test {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
762
		fn new(Builder { cleanup_pulse_interval, artifact_ttl, artifacts }: Builder) -> Self {
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
			let cache_path = PathBuf::from(std::env::temp_dir());

			let (to_host_tx, to_host_rx) = mpsc::channel(10);
			let (to_prepare_queue_tx, to_prepare_queue_rx) = mpsc::channel(10);
			let (from_prepare_queue_tx, from_prepare_queue_rx) = mpsc::unbounded();
			let (to_execute_queue_tx, to_execute_queue_rx) = mpsc::channel(10);
			let (to_sweeper_tx, to_sweeper_rx) = mpsc::channel(10);

			let mk_dummy_loop = || std::future::pending().boxed();

			let run = run(
				Inner {
					cache_path,
					cleanup_pulse_interval,
					artifact_ttl,
					artifacts,
					to_host_rx,
					to_prepare_queue_tx,
					from_prepare_queue_rx,
					to_execute_queue_tx,
					to_sweeper_tx,
					awaiting_prepare: AwaitingPrepare::default(),
				},
				mk_dummy_loop(),
				mk_dummy_loop(),
				mk_dummy_loop(),
				mk_dummy_loop(),
			)
			.boxed();

			Self {
				to_host_tx: Some(to_host_tx),
				to_prepare_queue_rx,
				from_prepare_queue_tx,
				to_execute_queue_rx,
				to_sweeper_rx,
				run,
			}
		}

		fn host_handle(&mut self) -> ValidationHost {
			let to_host_tx = self.to_host_tx.take().unwrap();
			ValidationHost { to_host_tx }
		}

		async fn poll_and_recv_to_prepare_queue(&mut self) -> prepare::ToQueue {
			let to_prepare_queue_rx = &mut self.to_prepare_queue_rx;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
810
811
			run_until(&mut self.run, async { to_prepare_queue_rx.next().await.unwrap() }.boxed())
				.await
812
813
814
815
		}

		async fn poll_and_recv_to_execute_queue(&mut self) -> execute::ToQueue {
			let to_execute_queue_rx = &mut self.to_execute_queue_rx;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
816
817
			run_until(&mut self.run, async { to_execute_queue_rx.next().await.unwrap() }.boxed())
				.await
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
		}

		async fn poll_ensure_to_execute_queue_is_empty(&mut self) {
			use futures_timer::Delay;

			let to_execute_queue_rx = &mut self.to_execute_queue_rx;
			run_until(
				&mut self.run,
				async {
					futures::select! {
						_ = Delay::new(Duration::from_millis(500)).fuse() => (),
						_ = to_execute_queue_rx.next().fuse() => {
							panic!("the execute queue supposed to be empty")
						}
					}
				}
				.boxed(),
			)
			.await
		}

		async fn poll_ensure_to_sweeper_is_empty(&mut self) {
			use futures_timer::Delay;

			let to_sweeper_rx = &mut self.to_sweeper_rx;
			run_until(
				&mut self.run,
				async {
					futures::select! {
						_ = Delay::new(Duration::from_millis(500)).fuse() => (),
						msg = to_sweeper_rx.next().fuse() => {
							panic!("the sweeper supposed to be empty, but received: {:?}", msg)
						}
					}
				}
				.boxed(),
			)
			.await
		}
	}

	async fn run_until<R>(
		task: &mut (impl Future<Output = ()> + Unpin),
		mut fut: (impl Future<Output = R> + Unpin),
	) -> R {
		use std::task::Poll;

		let start = std::time::Instant::now();
		let fut = &mut fut;
		loop {
			if start.elapsed() > std::time::Duration::from_secs(2) {
				// We expect that this will take only a couple of iterations and thus to take way
				// less than a second.
				panic!("timeout");
			}

			if let Poll::Ready(r) = futures::poll!(&mut *fut) {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
875
				break r
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
			}

			if futures::poll!(&mut *task).is_ready() {
				panic!()
			}
		}
	}

	#[async_std::test]
	async fn shutdown_on_handle_drop() {
		let test = Builder::default().build();

		let join_handle = async_std::task::spawn(test.run);

		// Dropping the handle will lead to conclusion of the read part and thus will make the event
		// loop to stop, which in turn will resolve the join handle.
		drop(test.to_host_tx);
		join_handle.await;
	}

	#[async_std::test]
	async fn pruning() {
		let mock_now = SystemTime::now() - Duration::from_millis(1000);

		let mut builder = Builder::default();
		builder.cleanup_pulse_interval = Duration::from_millis(100);
		builder.artifact_ttl = Duration::from_millis(500);
		builder.artifacts.insert_prepared(artifact_id(1), mock_now);
		builder.artifacts.insert_prepared(artifact_id(2), mock_now);
		let mut test = builder.build();
		let mut host = test.host_handle();

Shawn Tabrizi's avatar
Shawn Tabrizi committed
908
		host.heads_up(vec![Pvf::from_discriminator(1)]).await.unwrap();
909
910
911
912
913
914
915
916
917
918
919
920
921

		let to_sweeper_rx = &mut test.to_sweeper_rx;
		run_until(
			&mut test.run,
			async {
				assert_eq!(to_sweeper_rx.next().await.unwrap(), artifact_path(2));
			}
			.boxed(),
		)
		.await;

		// Extend TTL for the first artifact and make sure we don't receive another file removal
		// request.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
922
		host.heads_up(vec![Pvf::from_discriminator(1)]).await.unwrap();
923
924
925
926
927
928
929
930
		test.poll_ensure_to_sweeper_is_empty().await;
	}

	#[async_std::test]
	async fn amending_priority() {
		let mut test = Builder::default().build();
		let mut host = test.host_handle();

Shawn Tabrizi's avatar
Shawn Tabrizi committed
931
		host.heads_up(vec![Pvf::from_discriminator(1)]).await.unwrap();
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947

		// Run until we receive a prepare request.
		let prepare_q_rx = &mut test.to_prepare_queue_rx;
		run_until(
			&mut test.run,
			async {
				assert_matches!(
					prepare_q_rx.next().await.unwrap(),
					prepare::ToQueue::Enqueue { .. }
				);
			}
			.boxed(),
		)
		.await;

		let (result_tx, _result_rx) = oneshot::channel();
948
949
950
951
952
953
954
955
956
		host.execute_pvf(
			Pvf::from_discriminator(1),
			TEST_EXECUTION_TIMEOUT,
			vec![],
			Priority::Critical,
			result_tx,
		)
		.await
		.unwrap();
957
958
959
960

		run_until(
			&mut test.run,
			async {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
961
				assert_matches!(prepare_q_rx.next().await.unwrap(), prepare::ToQueue::Amend { .. });
962
963
964
965
966
967
968
969
970
971
972
973
			}
			.boxed(),
		)
		.await;
	}

	#[async_std::test]
	async fn execute_pvf_requests() {
		let mut test = Builder::default().build();
		let mut host = test.host_handle();

		let (result_tx, result_rx_pvf_1_1) = oneshot::channel();
974
975
976
977
978
979
980
981
982
		host.execute_pvf(
			Pvf::from_discriminator(1),
			TEST_EXECUTION_TIMEOUT,
			b"pvf1".to_vec(),
			Priority::Normal,
			result_tx,
		)
		.await
		.unwrap();
983
984
985
986

		let (result_tx, result_rx_pvf_1_2) = oneshot::channel();
		host.execute_pvf(
			Pvf::from_discriminator(1),
987
			TEST_EXECUTION_TIMEOUT,
988
989
990
991
992
993
994
995
			b"pvf1".to_vec(),
			Priority::Critical,
			result_tx,
		)
		.await
		.unwrap();

		let (result_tx, result_rx_pvf_2) = oneshot::channel();
996
997
998
999
1000
1001
1002
1003
1004
		host.execute_pvf(
			Pvf::from_discriminator(2),
			TEST_EXECUTION_TIMEOUT,
			b"pvf2".to_vec(),
			Priority::Normal,
			result_tx,
		)
		.await
		.unwrap();
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019

		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);
		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Amend { .. }
		);
		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);

		test.from_prepare_queue_tx
1020
			.send(prepare::FromQueue { artifact_id: artifact_id(1), result: Ok(()) })
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
			.await
			.unwrap();
		let result_tx_pvf_1_1 = assert_matches!(
			test.poll_and_recv_to_execute_queue().await,
			execute::ToQueue::Enqueue { result_tx, .. } => result_tx
		);
		let result_tx_pvf_1_2 = assert_matches!(
			test.poll_and_recv_to_execute_queue().await,
			execute::ToQueue::Enqueue { result_tx, .. } => result_tx
		);

		test.from_prepare_queue_tx
1033
			.send(prepare::FromQueue { artifact_id: artifact_id(2), result: Ok(()) })
1034
1035
1036
1037
1038
1039
1040
1041
			.await
			.unwrap();
		let result_tx_pvf_2 = assert_matches!(
			test.poll_and_recv_to_execute_queue().await,
			execute::ToQueue::Enqueue { result_tx, .. } => result_tx
		);

		result_tx_pvf_1_1
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1042
			.send(Err(ValidationError::InvalidCandidate(InvalidCandidate::AmbigiousWorkerDeath)))
1043
1044
1045
			.unwrap();
		assert_matches!(
			result_rx_pvf_1_1.now_or_never().unwrap().unwrap(),
1046
			Err(ValidationError::InvalidCandidate(InvalidCandidate::AmbigiousWorkerDeath))
1047
1048
1049
		);

		result_tx_pvf_1_2
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1050
			.send(Err(ValidationError::InvalidCandidate(InvalidCandidate::AmbigiousWorkerDeath)))
1051
1052
1053
			.unwrap();
		assert_matches!(
			result_rx_pvf_1_2.now_or_never().unwrap().unwrap(),
1054
			Err(ValidationError::InvalidCandidate(InvalidCandidate::AmbigiousWorkerDeath))
1055
1056
1057
		);

		result_tx_pvf_2
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1058
			.send(Err(ValidationError::InvalidCandidate(InvalidCandidate::AmbigiousWorkerDeath)))
1059
1060
1061
			.unwrap();
		assert_matches!(
			result_rx_pvf_2.now_or_never().unwrap().unwrap(),
1062
			Err(ValidationError::InvalidCandidate(InvalidCandidate::AmbigiousWorkerDeath))
1063
1064
1065
		);
	}

1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
	#[async_std::test]
	async fn precheck_pvf() {
		let mut test = Builder::default().build();
		let mut host = test.host_handle();

		// First, test a simple precheck request.
		let (result_tx, result_rx) = oneshot::channel();
		host.precheck_pvf(Pvf::from_discriminator(1), result_tx).await.unwrap();

		// The queue received the prepare request.
		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);
		// Send `Ok` right away and poll the host.
		test.from_prepare_queue_tx
			.send(prepare::FromQueue { artifact_id: artifact_id(1), result: Ok(()) })
			.await
			.unwrap();
		// No pending execute requests.
		test.poll_ensure_to_execute_queue_is_empty().await;
		// Received the precheck result.
		assert_matches!(result_rx.now_or_never().unwrap().unwrap(), Ok(()));

		// Send multiple requests for the same pvf.
		let mut precheck_receivers = Vec::new();
		for _ in 0..3 {
			let (result_tx, result_rx) = oneshot::channel();
			host.precheck_pvf(Pvf::from_discriminator(2), result_tx).await.unwrap();
			precheck_receivers.push(result_rx);
		}
		// Received prepare request.
		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);
		test.from_prepare_queue_tx
			.send(prepare::FromQueue {
				artifact_id: artifact_id(2),
				result: Err(PrepareError::TimedOut),
			})
			.await
			.unwrap();
		test.poll_ensure_to_execute_queue_is_empty().await;
		for result_rx in precheck_receivers {
			assert_matches!(
				result_rx.now_or_never().unwrap().unwrap(),
				Err(PrepareError::TimedOut)
			);
		}
	}

	#[async_std::test]
	async fn test_prepare_done() {
		let mut test = Builder::default().build();
		let mut host = test.host_handle();

		// Test mixed cases of receiving execute and precheck requests
		// for the same pvf.

		// Send PVF for the execution and request the prechecking for it.
		let (result_tx, result_rx_execute) = oneshot::channel();
		host.execute_pvf(
			Pvf::from_discriminator(1),
			TEST_EXECUTION_TIMEOUT,
			b"pvf2".to_vec(),
			Priority::Critical,
			result_tx,
		)
		.await
		.unwrap();

		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);

		let (result_tx, result_rx) = oneshot::channel();
		host.precheck_pvf(Pvf::from_discriminator(1), result_tx).await.unwrap();

		// Suppose the preparation failed, the execution queue is empty and both
		// "clients" receive their results.
		test.from_prepare_queue_tx
			.send(prepare::FromQueue {
				artifact_id: artifact_id(1),
				result: Err(PrepareError::TimedOut),
			})
			.await
			.unwrap();
		test.poll_ensure_to_execute_queue_is_empty().await;
		assert_matches!(result_rx.now_or_never().unwrap().unwrap(), Err(PrepareError::TimedOut));
		assert_matches!(
			result_rx_execute.now_or_never().unwrap().unwrap(),
			Err(ValidationError::InvalidCandidate(InvalidCandidate::WorkerReportedError(_)))
		);

		// Reversed case: first send multiple precheck requests, then ask for an execution.
		let mut precheck_receivers = Vec::new();
		for _ in 0..3 {
			let (result_tx, result_rx) = oneshot::channel();
			host.precheck_pvf(Pvf::from_discriminator(2), result_tx).await.unwrap();
			precheck_receivers.push(result_rx);
		}

		let (result_tx, _result_rx_execute) = oneshot::channel();
		host.execute_pvf(
			Pvf::from_discriminator(2),
			TEST_EXECUTION_TIMEOUT,
			b"pvf2".to_vec(),
			Priority::Critical,
			result_tx,
		)
		.await
		.unwrap();
		// Received prepare request.
		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);
		test.from_prepare_queue_tx
			.send(prepare::FromQueue { artifact_id: artifact_id(2), result: Ok(()) })
			.await
			.unwrap();
		// The execute queue receives new request, preckecking is finished and we can
		// fetch results.
		assert_matches!(
			test.poll_and_recv_to_execute_queue().await,
			execute::ToQueue::Enqueue { .. }
		);
		for result_rx in precheck_receivers {
			assert_matches!(result_rx.now_or_never().unwrap().unwrap(), Ok(()));
		}
	}

1200
1201
1202
1203
1204
1205
	#[async_std::test]
	async fn cancellation() {
		let mut test = Builder::default().build();
		let mut host = test.host_handle();

		let (result_tx, result_rx) = oneshot::channel();
1206
1207
1208
1209
1210
1211
1212
1213
1214
		host.execute_pvf(
			Pvf::from_discriminator(1),
			TEST_EXECUTION_TIMEOUT,
			b"pvf1".to_vec(),
			Priority::Normal,
			result_tx,
		)
		.await
		.unwrap();
1215
1216
1217
1218
1219
1220
1221

		assert_matches!(
			test.poll_and_recv_to_prepare_queue().await,
			prepare::ToQueue::Enqueue { .. }
		);

		test.from_prepare_queue_tx
1222
			.send(prepare::FromQueue { artifact_id: artifact_id(1), result: Ok(()) })
1223
1224
1225
1226
1227
1228
1229
1230
			.await
			.unwrap();

		drop(result_rx);

		test.poll_ensure_to_execute_queue_is_empty().await;
	}
}