1use crate::args::{Arguments, TimeThreshold};
2use crate::bench::AsyncBencher;
3use crate::execution::{DepWireBytes, TestExecution, TestSuiteExecution};
4use crate::internal;
5use crate::internal::{
6 generate_tests, get_ensure_time, CapturedOutput, CloneableCodec, FailureCause,
7 FlakinessControl, HostedRpcChannel, HostedRpcError, HostedRpcOwnerCell, HostedRpcTransport,
8 InProcessHostedRpcTransport, RegisteredTest, RpcFactory, SuiteResult, TestFunction, TestResult,
9 WorkerReconstructor,
10};
11use crate::ipc::{
12 ipc_name, read_frame_async, write_frame_async, HostedRpcReplyBody, IpcCommand, IpcResponse,
13};
14use crate::output::{test_runner_output, TestRunnerOutput};
15use desert_rust::{deserialize, serialize_to_byte_vec};
16use futures::FutureExt;
17use interprocess::local_socket::tokio::prelude::*;
18use interprocess::local_socket::tokio::{Listener, Stream};
19use interprocess::local_socket::{GenericNamespaced, ListenerOptions};
20use std::any::Any;
21use std::collections::HashMap;
22use std::collections::VecDeque;
23use std::future::Future;
24use std::panic::AssertUnwindSafe;
25use std::pin::Pin;
26use std::process::{ExitCode, Stdio};
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::sync::Arc;
29use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
30use tokio::process::{Child, Command};
31use tokio::spawn;
32use tokio::sync::Mutex;
33use tokio::task::{spawn_blocking, JoinHandle, JoinSet};
34use tokio::time::Instant;
35use uuid::Uuid;
36
37pub fn test_runner() -> ExitCode {
38 tokio::runtime::Builder::new_multi_thread()
39 .enable_all()
40 .build()
41 .unwrap()
42 .block_on(async_test_runner())
43}
44
45#[allow(clippy::await_holding_lock)]
46async fn async_test_runner() -> ExitCode {
47 crate::panic_hook::install_panic_hook();
48 let mut args = Arguments::from_args();
49 if let Some(idx) = args.worker_index {
53 crate::worker::set_worker_index(idx);
54 }
55 let output = test_runner_output(&args);
59
60 let registered_tests = internal::REGISTERED_TESTS.lock().unwrap();
61 let registered_dependency_constructors =
62 internal::REGISTERED_DEPENDENCY_CONSTRUCTORS.lock().unwrap();
63 let registered_testsuite_props = internal::REGISTERED_TESTSUITE_PROPS.lock().unwrap();
64 let registered_test_generators = internal::REGISTERED_TEST_GENERATORS.lock().unwrap();
65
66 let generated_tests = generate_tests(®istered_test_generators).await;
67
68 let all_tests: Vec<RegisteredTest> = registered_tests
69 .iter()
70 .cloned()
71 .chain(generated_tests)
72 .collect();
73
74 if args.list {
75 let tests_with_props =
79 internal::apply_suite_props_to_tests(&all_tests, ®istered_testsuite_props);
80 let filtered_tests = internal::filter_registered_tests(&args, &tests_with_props);
81 output.test_list(&filtered_tests);
82 ExitCode::SUCCESS
83 } else {
84 let mut remaining_retries = args.flaky_run.unwrap_or(1);
85
86 let mut exit_code = ExitCode::from(101);
87 while remaining_retries > 0 {
88 let (mut execution, filtered_tests) = TestSuiteExecution::construct(
89 &args,
90 registered_dependency_constructors.as_slice(),
91 &all_tests,
92 registered_testsuite_props.as_slice(),
93 );
94 args.finalize_for_execution(&execution, output.clone());
95 let mut host_capture = crate::host_capture::install_if_needed(&args);
99 let host_capture_epoch: Option<std::time::Instant> =
100 host_capture.as_ref().map(|hc| hc.epoch());
101 let host_capture_epoch_wall: Option<std::time::SystemTime> =
102 host_capture.as_ref().map(|hc| hc.epoch_wall());
103 let is_top_level_parent = args.is_top_level_parent();
104 let has_selected_tests = execution.remaining() > 0;
105 let needs_parent_shared = execution.has_cloneable_dependencies()
110 || execution.has_hosted_dependencies()
111 || execution.has_hosted_rpc_dependencies();
112 let parent_shared = if is_top_level_parent && has_selected_tests && needs_parent_shared
113 {
114 execution.collect_parent_shared_dependencies_async().await
115 } else {
116 crate::execution::ParentSharedDependencies {
117 cloneable_wire_bytes: Vec::new(),
118 cloneable_local_values: Vec::new(),
119 hosted_descriptor_bytes: Vec::new(),
120 hosted_owners: Vec::new(),
121 hosted_rpc_owner_cells: Vec::new(),
122 parent_constructed_shared_values: Vec::new(),
123 }
124 };
125 let cloneable_wire_bytes = parent_shared.cloneable_wire_bytes;
126 let cloneable_local_values = parent_shared.cloneable_local_values;
127 let hosted_descriptor_bytes = parent_shared.hosted_descriptor_bytes;
128 let _hosted_owners = parent_shared.hosted_owners;
129 let hosted_rpc_owner_cells: HashMap<String, Arc<HostedRpcOwnerCell>> =
130 parent_shared.hosted_rpc_owner_cells.into_iter().collect();
131 let parent_constructed_shared_values = parent_shared.parent_constructed_shared_values;
132 let rpc_factories: HashMap<String, RpcFactory> = registered_dependency_constructors
136 .iter()
137 .filter_map(|d| {
138 if d.scope == crate::internal::DepScope::HostedRpc {
139 d.rpc_factory
140 .as_ref()
141 .map(|f| (d.qualified_id(), f.clone()))
142 } else {
143 None
144 }
145 })
146 .collect();
147 let cloneable_codecs: HashMap<String, (CloneableCodec, WorkerReconstructor)> =
155 registered_dependency_constructors
156 .iter()
157 .filter_map(|d| {
158 let codec_opt = match d.scope {
159 crate::internal::DepScope::Cloneable => d.cloneable_codec.as_ref(),
160 crate::internal::DepScope::Hosted => d.hosted_codec.as_ref(),
161 _ => None,
162 };
163 match (codec_opt, &d.worker_fn) {
164 (Some(codec), Some(worker_fn)) => {
165 Some((d.qualified_id(), (codec.clone(), worker_fn.clone())))
166 }
167 _ => None,
168 }
169 })
170 .collect();
171 if is_top_level_parent && !args.spawn_workers && !cloneable_local_values.is_empty() {
181 apply_cloneable_values_locally(&mut execution, &cloneable_local_values);
182 }
183 if is_top_level_parent && !args.spawn_workers && !hosted_descriptor_bytes.is_empty() {
191 apply_hosted_descriptors_locally(
192 &mut execution,
193 &cloneable_codecs,
194 &hosted_descriptor_bytes,
195 )
196 .await;
197 }
198 if is_top_level_parent && !args.spawn_workers && !hosted_rpc_owner_cells.is_empty() {
203 install_local_hosted_rpc_stubs(
204 &mut execution,
205 &rpc_factories,
206 &hosted_rpc_owner_cells,
207 );
208 }
209 if is_top_level_parent
216 && !args.spawn_workers
217 && !parent_constructed_shared_values.is_empty()
218 {
219 apply_parent_constructed_shared_values_locally(
220 &mut execution,
221 &parent_constructed_shared_values,
222 );
223 }
224 if args.spawn_workers {
225 execution.skip_creating_dependencies();
226 }
227
228 let count = execution.remaining();
233 let results = Arc::new(Mutex::new(Vec::with_capacity(count)));
234 let host_windows: Arc<Mutex<Vec<crate::host_capture::HostWindow>>> =
239 Arc::new(Mutex::new(Vec::with_capacity(count)));
240
241 let start = Instant::now();
242 output.start_suite(&filtered_tests);
243
244 let execution = Arc::new(Mutex::new(execution));
245 let cloneable_wire_bytes = Arc::new(cloneable_wire_bytes);
246 let hosted_descriptor_bytes = Arc::new(hosted_descriptor_bytes);
247 let cloneable_codecs = Arc::new(cloneable_codecs);
248 let rpc_factories = Arc::new(rpc_factories);
249 let hosted_rpc_owner_cells = Arc::new(hosted_rpc_owner_cells);
250 let mut join_set = JoinSet::new();
251 let threads = args.test_threads().get();
252
253 for worker_idx in 0..threads {
254 let execution_clone = execution.clone();
255 let output_clone = output.clone();
256 let mut args_clone = args.clone();
259 if args_clone.spawn_workers {
260 args_clone.worker_index = Some(worker_idx);
261 }
262 let results_clone = results.clone();
263 let host_windows_clone = host_windows.clone();
264 let wire_bytes_clone = cloneable_wire_bytes.clone();
265 let hosted_bytes_clone = hosted_descriptor_bytes.clone();
266 let codecs_clone = cloneable_codecs.clone();
267 let rpc_factories_clone = rpc_factories.clone();
268 let hosted_rpc_owner_cells_clone = hosted_rpc_owner_cells.clone();
269 let handle = tokio::runtime::Handle::current();
270 join_set.spawn_blocking(move || {
271 handle.block_on(test_thread(
272 args_clone,
273 execution_clone,
274 output_clone,
275 count,
276 results_clone,
277 host_windows_clone,
278 wire_bytes_clone,
279 hosted_bytes_clone,
280 codecs_clone,
281 rpc_factories_clone,
282 hosted_rpc_owner_cells_clone,
283 host_capture_epoch,
284 ))
285 });
286 }
287
288 while let Some(res) = join_set.join_next().await {
289 res.expect("Failed to join task");
290 }
291
292 drop(execution);
293
294 let mut results = results.lock().await;
295 if is_top_level_parent {
296 assert_eq!(
297 results.len(),
298 count,
299 "IPC worker exhaustion stranded tests in the parent execution plan"
300 );
301 }
302 drop(hosted_rpc_owner_cells);
310 drop(_hosted_owners);
311
312 if let Some(hc) = host_capture.take() {
316 let epoch_wall = host_capture_epoch_wall.unwrap_or_else(|| hc.epoch_wall());
317 let records = hc.finalize();
318 let windows = host_windows.lock().await;
319 let windows_indexed: Vec<(usize, crate::host_capture::HostWindow)> =
320 windows.iter().copied().enumerate().collect();
321 crate::host_capture::attribute_records_to_tests(
322 epoch_wall,
323 &records,
324 &windows_indexed,
325 &mut results,
326 );
327 }
328 output.finished_suite(&all_tests, &results, start.elapsed());
329 exit_code = SuiteResult::exit_code(&results);
330
331 if !is_top_level_parent || exit_code == ExitCode::SUCCESS {
336 break;
337 } else {
338 remaining_retries -= 1;
339 }
340 }
341 exit_code
342 }
343}
344
345#[allow(clippy::too_many_arguments)]
346async fn test_thread(
347 args: Arguments,
348 execution: Arc<Mutex<TestSuiteExecution>>,
349 output: Arc<dyn TestRunnerOutput>,
350 count: usize,
351 results: Arc<Mutex<Vec<(RegisteredTest, TestResult)>>>,
352 host_windows: Arc<Mutex<Vec<crate::host_capture::HostWindow>>>,
353 cloneable_wire_bytes: Arc<Vec<DepWireBytes>>,
354 hosted_descriptor_bytes: Arc<Vec<DepWireBytes>>,
355 cloneable_codecs: Arc<HashMap<String, (CloneableCodec, WorkerReconstructor)>>,
356 rpc_factories: Arc<HashMap<String, RpcFactory>>,
357 hosted_rpc_owner_cells: Arc<HashMap<String, Arc<HostedRpcOwnerCell>>>,
358 host_capture_epoch: Option<std::time::Instant>,
359) {
360 let mut worker = spawn_worker_if_needed(&args).await;
361 if let Some(worker) = worker.as_mut() {
366 worker.set_hosted_rpc_owner_cells(hosted_rpc_owner_cells.clone());
367 }
368 let connection_arc = if let Some(ref name) = args.ipc {
369 let name = ipc_name(name.clone());
370 let stream = Stream::connect(name)
371 .await
372 .expect("Failed to connect to IPC socket");
373 Some(Arc::new(Mutex::new(stream)))
374 } else {
375 None
376 };
377
378 let ipc_output = connection_arc
380 .as_ref()
381 .map(|_| Arc::new(crate::output::ipc::IpcWorkerOutput::new(!args.nocapture)));
382 let output: Arc<dyn TestRunnerOutput> = ipc_output
383 .as_ref()
384 .map(|output| output.clone() as Arc<dyn TestRunnerOutput>)
385 .unwrap_or(output);
386
387 if let Some(worker) = worker.as_mut() {
388 for (dep_id, wire_bytes) in cloneable_wire_bytes.iter() {
389 worker
390 .provide_cloneable(dep_id.clone(), wire_bytes.clone())
391 .await;
392 }
393 for (dep_id, descriptor_bytes) in hosted_descriptor_bytes.iter() {
395 worker
396 .provide_hosted_descriptor(dep_id.clone(), descriptor_bytes.clone())
397 .await;
398 }
399 }
400
401 if let Some(connection) = connection_arc.as_ref() {
406 if !rpc_factories.is_empty() {
407 install_worker_subprocess_hosted_rpc_stubs(
408 &execution,
409 &rpc_factories,
410 connection.clone(),
411 )
412 .await;
413 }
414 }
415
416 let mut expected_test = None;
417 let mut owned_worker_exhausted = false;
418
419 'test_loop: loop {
420 let is_ipc_worker = connection_arc.is_some();
421 if crate::ipc::test_loop_should_exit(
422 is_ipc_worker,
423 is_done(&execution).await,
424 owned_worker_exhausted,
425 ) {
426 break;
427 }
428
429 if let Some(connection) = connection_arc.as_ref() {
430 while expected_test.is_none() {
431 let mut conn = connection.lock().await;
432 let command_bytes = read_frame_async(&mut *conn)
433 .await
434 .expect("Failed to read IPC command frame");
435 drop(conn);
436 let command: IpcCommand =
437 deserialize(&command_bytes).expect("Failed to decode IPC command");
438
439 match command {
440 IpcCommand::RunTest {
441 name,
442 crate_name,
443 module_path,
444 } => {
445 expected_test = Some((name, crate_name, module_path));
446 }
447 IpcCommand::Shutdown => break 'test_loop,
448 IpcCommand::ProvideCloneable { dep_id, wire_bytes } => {
449 apply_provided_wire_bytes(
451 &execution,
452 &cloneable_codecs,
453 &dep_id,
454 &wire_bytes,
455 "ProvideCloneable",
456 )
457 .await;
458 let response = IpcResponse::CloneableAccepted { dep_id };
459 let msg = serialize_to_byte_vec(&response)
460 .expect("Failed to encode IPC response");
461 let mut conn = connection.lock().await;
462 write_frame_async(&mut *conn, &msg)
463 .await
464 .expect("Failed to write IPC response frame");
465 }
466 IpcCommand::ProvideHostedDescriptor { dep_id, wire_bytes } => {
467 apply_provided_wire_bytes(
471 &execution,
472 &cloneable_codecs,
473 &dep_id,
474 &wire_bytes,
475 "ProvideHostedDescriptor",
476 )
477 .await;
478 let response = IpcResponse::HostedDescriptorAccepted { dep_id };
479 let msg = serialize_to_byte_vec(&response)
480 .expect("Failed to encode IPC response");
481 let mut conn = connection.lock().await;
482 write_frame_async(&mut *conn, &msg)
483 .await
484 .expect("Failed to write IPC response frame");
485 }
486 IpcCommand::HostedRpcReply { .. } => {
487 panic!(
494 "unexpected `HostedRpcReply` while waiting for the next \
495 between-tests command in the tokio worker subprocess: a \
496 stub call must have left a reply on the wire without \
497 draining it inline"
498 );
499 }
500 }
501 }
502 }
503
504 if let Some(next) = pick_next(&execution).await {
505 let skip = if let Some((name, crate_name, module_path)) = &expected_test {
506 next.test.name != *name
507 || next.test.crate_name != *crate_name
508 || next.test.module_path != *module_path
509 } else {
510 false
511 };
512
513 if !skip {
514 expected_test = None;
515
516 let ensure_time = get_ensure_time(&args, &next.test);
517
518 let window_start = std::time::Instant::now();
526
527 output.start_running_test(&next.test, next.index, count);
528 let result = run_test(
529 output.clone(),
530 next.index,
531 count,
532 args.nocapture,
533 args.include_ignored,
534 ensure_time,
535 next.deps.clone(),
536 &next.test,
537 &mut worker,
538 )
539 .await;
540 owned_worker_exhausted = worker
541 .as_ref()
542 .map(|worker| worker.exhausted)
543 .unwrap_or(false);
544 output.finished_running_test(&next.test, next.index, count, &result);
545 let window_end = std::time::Instant::now();
546
547 if let Some(connection) = connection_arc.as_ref() {
548 let finish_marker = Uuid::new_v4().to_string();
549 let finish_marker_line = format!("{finish_marker}\n");
550 let mut stdout = tokio::io::stdout();
551 stdout
552 .write_all(finish_marker_line.as_bytes())
553 .await
554 .unwrap();
555 stdout.flush().await.unwrap();
556
557 let mut stderr = tokio::io::stderr();
558 stderr
559 .write_all(finish_marker_line.as_bytes())
560 .await
561 .unwrap();
562 stderr.flush().await.unwrap();
563
564 let response = IpcResponse::TestFinished {
565 result: (&result).into(),
566 finish_marker,
567 retries: ipc_output.as_ref().unwrap().take_retries(),
568 worker_exhausted: is_done(&execution).await,
569 };
570 let msg =
571 serialize_to_byte_vec(&response).expect("Failed to encode IPC response");
572 let mut conn = connection.lock().await;
573 write_frame_async(&mut *conn, &msg)
574 .await
575 .expect("Failed to write IPC response frame");
576 }
577
578 let window = crate::host_capture::HostWindow::from_instants(
582 host_capture_epoch,
583 window_start,
584 window_end,
585 )
586 .unwrap_or(crate::host_capture::HostWindow {
587 start: std::time::Duration::ZERO,
588 end: std::time::Duration::ZERO,
589 });
590 let mut results_guard = results.lock().await;
591 let mut windows_guard = host_windows.lock().await;
592 results_guard.push((next.test.clone(), result));
593 windows_guard.push(window);
594 }
595 }
596 }
597
598 if let Some(worker) = worker {
599 worker.shutdown().await;
600 }
601}
602
603async fn is_done(execution: &Arc<Mutex<TestSuiteExecution>>) -> bool {
604 let execution = execution.lock().await;
605 execution.is_done()
606}
607
608async fn apply_provided_wire_bytes(
618 execution: &Arc<Mutex<TestSuiteExecution>>,
619 wire_codecs: &HashMap<String, (CloneableCodec, WorkerReconstructor)>,
620 dep_id: &str,
621 wire_bytes: &[u8],
622 source_command: &str,
623) {
624 let (codec, worker_fn) = wire_codecs.get(dep_id).unwrap_or_else(|| {
625 panic!("{source_command} referenced unknown wire-shipped dep '{dep_id}'")
626 });
627
628 let wire_payload = (codec.from_wire_bytes)(wire_bytes);
629 let empty_deps: Arc<dyn internal::DependencyView + Send + Sync> =
630 Arc::new(HashMap::<String, Arc<dyn Any + Send + Sync>>::new());
631 let reconstructed = match worker_fn {
632 WorkerReconstructor::Sync(f) => f(wire_payload, empty_deps),
633 WorkerReconstructor::Async(f) => f(wire_payload, empty_deps).await,
634 };
635
636 let mut execution = execution.lock().await;
637 let applied = execution.provide_cloneable_value(dep_id, reconstructed);
638 assert!(
639 applied,
640 "{source_command} for dep '{dep_id}' did not match any registered dep in this worker"
641 );
642}
643
644fn apply_cloneable_values_locally(
659 execution: &mut TestSuiteExecution,
660 cloneable_local_values: &[(String, Arc<dyn Any + Send + Sync>)],
661) {
662 for (dep_id, value) in cloneable_local_values {
663 let applied = execution.provide_cloneable_value(dep_id, value.clone());
664 assert!(
665 applied,
666 "Cloneable dep '{dep_id}' could not be pre-populated locally"
667 );
668 }
669}
670
671fn apply_parent_constructed_shared_values_locally(
677 execution: &mut TestSuiteExecution,
678 values: &[(String, Arc<dyn Any + Send + Sync>)],
679) {
680 for (dep_id, value) in values {
681 let applied = execution.provide_materialized_shared_value(dep_id, value.clone());
682 assert!(
683 applied,
684 "Shared/PerWorker dep '{dep_id}' could not be pre-populated locally"
685 );
686 }
687}
688
689async fn apply_hosted_descriptors_locally(
702 execution: &mut TestSuiteExecution,
703 wire_codecs: &HashMap<String, (CloneableCodec, WorkerReconstructor)>,
704 descriptor_bytes: &[DepWireBytes],
705) {
706 for (dep_id, wire_bytes) in descriptor_bytes {
707 let (codec, worker_fn) = wire_codecs.get(dep_id).unwrap_or_else(|| {
708 panic!("Hosted dep '{dep_id}' missing codec/worker_fn for local handle reconstruction")
709 });
710 let wire_payload = (codec.from_wire_bytes)(wire_bytes);
711 let empty_deps: Arc<dyn internal::DependencyView + Send + Sync> =
712 Arc::new(HashMap::<String, Arc<dyn Any + Send + Sync>>::new());
713 let reconstructed = match worker_fn {
714 WorkerReconstructor::Sync(f) => f(wire_payload, empty_deps),
715 WorkerReconstructor::Async(f) => f(wire_payload, empty_deps).await,
716 };
717 let applied = execution.provide_cloneable_value(dep_id, reconstructed);
718 assert!(
719 applied,
720 "Hosted dep '{dep_id}' could not be pre-populated locally"
721 );
722 }
723}
724
725async fn pick_next(execution: &Arc<Mutex<TestSuiteExecution>>) -> Option<TestExecution> {
726 let mut execution = execution.lock().await;
727 execution.pick_next().await
728}
729
730async fn run_with_flakiness_control<F>(
731 output: Arc<dyn TestRunnerOutput>,
732 test_description: &RegisteredTest,
733 idx: usize,
734 count: usize,
735 test: F,
736) -> TestResult
737where
738 F: Fn(
739 Instant,
740 )
741 -> Pin<Box<dyn Future<Output = Result<Result<(), FailureCause>, Box<dyn Any + Send>>>>>
742 + Send
743 + Sync,
744{
745 let total_start = Instant::now();
746 let mut attempts = Vec::new();
747 let max_attempts = match test_description.props.flakiness_control {
748 FlakinessControl::None => 1,
749 FlakinessControl::ProveNonFlaky(n) | FlakinessControl::RetryKnownFlaky(n) => n,
750 };
751 if max_attempts == 0
752 && matches!(
753 test_description.props.flakiness_control,
754 FlakinessControl::ProveNonFlaky(_)
755 )
756 {
757 return TestResult::from_result(
758 &test_description.props.should_panic,
759 total_start.elapsed(),
760 Ok(Ok(())),
761 );
762 }
763 let mut n = 1;
764 loop {
765 let start = Instant::now();
766 let raw = test(start).await;
767 let repeat = match test_description.props.flakiness_control {
768 FlakinessControl::None => false,
769 FlakinessControl::ProveNonFlaky(_) => matches!(&raw, Ok(Ok(()))),
770 FlakinessControl::RetryKnownFlaky(_) => matches!(
771 &raw,
772 Err(_)
773 | Ok(Err(
774 FailureCause::ReturnedError { .. } | FailureCause::ReturnedMessage(_)
775 ))
776 ),
777 };
778 let mut result =
779 TestResult::from_result(&test_description.props.should_panic, start.elapsed(), raw);
780 attempts.push(internal::TestAttempt {
781 result: Box::new(result.clone()),
782 finish_marker: output.finish_test_attempt(test_description),
783 });
784 if !repeat || n >= max_attempts {
785 match &mut result {
786 TestResult::Passed { exec_time, .. } | TestResult::Failed { exec_time, .. } => {
787 *exec_time = total_start.elapsed()
788 }
789 _ => {}
790 }
791 result.set_attempts(attempts);
792 return result;
793 }
794 n += 1;
795 output.repeat_running_test(
796 test_description,
797 idx,
798 count,
799 n,
800 max_attempts,
801 if matches!(
802 test_description.props.flakiness_control,
803 FlakinessControl::ProveNonFlaky(_)
804 ) {
805 "to ensure test is not flaky"
806 } else {
807 "because test is known to be flaky"
808 },
809 );
810 }
811}
812
813#[allow(clippy::too_many_arguments)]
814async fn run_test(
815 output: Arc<dyn TestRunnerOutput>,
816 idx: usize,
817 count: usize,
818 nocapture: bool,
819 include_ignored: bool,
820 ensure_time: Option<TimeThreshold>,
821 dependency_view: Arc<dyn internal::DependencyView + Send + Sync>,
822 test: &RegisteredTest,
823 worker: &mut Option<Worker>,
824) -> TestResult {
825 if test.props.is_ignored && !include_ignored {
826 TestResult::ignored()
827 } else if let Some(worker) = worker.as_mut() {
828 worker.run_test(nocapture, test, &*output, idx, count).await
829 } else {
830 let start = Instant::now();
831 let test = test.clone();
832 match &test.run {
833 TestFunction::Sync(_) => {
834 let handle = spawn_blocking(move || {
835 let test = test.clone();
836 crate::sync::run_sync_test_function(
837 output,
838 &test,
839 idx,
840 count,
841 ensure_time,
842 dependency_view,
843 )
844 });
845 handle.await.unwrap_or_else(|join_error| {
846 TestResult::failed(
847 start.elapsed(),
848 FailureCause::HarnessError(format!(
849 "Failed joining test task: {join_error}"
850 )),
851 )
852 })
853 }
854 TestFunction::Async(test_fn) => {
855 let timeout = test.props.timeout;
856 let test_fn = test_fn.clone();
857 let detached_panic_policy = test.props.detached_panic_policy.clone();
858 let mut test_result =
859 run_with_flakiness_control(output, &test, idx, count, |start| {
860 let dependency_view = dependency_view.clone();
861 let test_fn = test_fn.clone();
862 Box::pin(async move {
863 let test_id = crate::panic_hook::next_test_id();
864 crate::panic_hook::set_current_test_id(test_id);
865 crate::panic_hook::create_detached_collector(test_id);
866 let result = AssertUnwindSafe(Box::pin(async move {
867 match timeout {
868 None => test_fn(dependency_view).await,
869 Some(duration) => {
870 let result = tokio::time::timeout(
871 duration,
872 test_fn(dependency_view),
873 )
874 .await;
875 match result {
876 Ok(result) => result,
877 Err(_) => {
878 return Err(FailureCause::HarnessError(
879 "Test timed out".to_string(),
880 ))
881 }
882 }
883 }
884 }
885 .into_result()?;
886 if let Some(ensure_time) = ensure_time {
887 let elapsed = start.elapsed();
888 if ensure_time.is_critical(&elapsed) {
889 return Err(FailureCause::HarnessError(format!(
890 "Test run time exceeds critical threshold: {elapsed:?}"
891 )));
892 }
893 }
894 Ok(())
895 }))
896 .catch_unwind()
897 .await;
898 result
899 })
900 })
901 .await;
902 if let Some(test_id) = crate::panic_hook::current_test_id() {
903 if let Some(collector) = crate::panic_hook::take_detached_collector(test_id) {
904 let panics = match collector.lock() {
905 Ok(p) => p,
906 Err(poisoned) => poisoned.into_inner(),
907 };
908 if !panics.is_empty()
909 && detached_panic_policy == internal::DetachedPanicPolicy::FailTest
910 && test_result.is_passed()
911 {
912 let messages: Vec<String> = panics.iter().map(|p| p.render()).collect();
913 let mut attempts = test_result.attempts().clone();
914 let cause = FailureCause::Panic(internal::PanicCause {
915 message: Some(format!(
916 "Detached task(s) panicked:\n{}",
917 messages.join("\n---\n")
918 )),
919 location: panics.first().and_then(|p| p.location.clone()),
920 backtrace: panics.first().and_then(|p| p.backtrace.clone()),
921 });
922 test_result = TestResult::failed(start.elapsed(), cause.clone());
923 if let Some(last) = attempts.last_mut() {
924 let TestResult::Passed { exec_time, .. } = last.result.as_ref()
925 else {
926 unreachable!(
927 "a passed logical test has a passed final invocation"
928 );
929 };
930 *last.result = TestResult::failed(*exec_time, cause);
931 }
932 test_result.set_attempts(attempts);
933 }
934 }
935 }
936 crate::panic_hook::clear_current_test_id();
937 test_result
938 }
939 TestFunction::SyncBench(_) => {
940 let handle = spawn_blocking(move || {
941 let test = test.clone();
942 crate::sync::run_sync_test_function(
943 output,
944 &test,
945 idx,
946 count,
947 ensure_time,
948 dependency_view,
949 )
950 });
951 handle.await.unwrap_or_else(|join_error| {
952 TestResult::failed(
953 start.elapsed(),
954 FailureCause::HarnessError(format!(
955 "Failed joining test task: {join_error}"
956 )),
957 )
958 })
959 }
960 TestFunction::AsyncBench(bench_fn) => {
961 let mut bencher = AsyncBencher::new();
962 let test_id = crate::panic_hook::next_test_id();
963 crate::panic_hook::set_current_test_id(test_id);
964 let result = AssertUnwindSafe(async move {
965 bench_fn(&mut bencher, dependency_view).await;
966 (
967 bencher
968 .summary()
969 .expect("iter() was not called in bench function"),
970 bencher.bytes,
971 )
972 })
973 .catch_unwind()
974 .await;
975 let bytes = result.as_ref().map(|(_, bytes)| *bytes).unwrap_or_default();
976 let test_result = TestResult::from_summary(
977 &test.props.should_panic,
978 start.elapsed(),
979 result.map(|(summary, _)| summary),
980 bytes,
981 );
982 crate::panic_hook::clear_current_test_id();
983 test_result
984 }
985 }
986 }
987}
988
989struct Worker {
990 _listener: Listener,
991 process: Child,
992 _out_handle: JoinHandle<()>,
993 _err_handle: JoinHandle<()>,
994 out_lines: Arc<Mutex<VecDeque<CapturedOutput>>>,
995 err_lines: Arc<Mutex<VecDeque<CapturedOutput>>>,
996 capture_enabled: Arc<Mutex<bool>>,
997 connection: Stream,
998 exhausted: bool,
999 hosted_rpc_owner_cells: Arc<HashMap<String, Arc<HostedRpcOwnerCell>>>,
1003}
1004
1005impl Worker {
1006 fn set_hosted_rpc_owner_cells(&mut self, cells: Arc<HashMap<String, Arc<HostedRpcOwnerCell>>>) {
1010 self.hosted_rpc_owner_cells = cells;
1011 }
1012
1013 async fn handle_hosted_rpc_call(
1019 &mut self,
1020 dump_on_ipc_failure: &DumpOnFailure,
1021 request_id: u64,
1022 dep_id: String,
1023 method_idx: u32,
1024 args_bytes: Vec<u8>,
1025 ) {
1026 let body = match self.hosted_rpc_owner_cells.get(&dep_id) {
1027 Some(cell) => match cell.dispatch_async(method_idx, &args_bytes).await {
1033 Ok(result_bytes) => HostedRpcReplyBody::Ok { result_bytes },
1034 Err(message) => HostedRpcReplyBody::Err { message },
1035 },
1036 None => HostedRpcReplyBody::Err {
1037 message: format!(
1038 "HostedRpc dispatch: unknown dep id '{dep_id}' in parent owner-cell map"
1039 ),
1040 },
1041 };
1042 let reply = IpcCommand::HostedRpcReply { request_id, body };
1043 let msg = serialize_to_byte_vec(&reply).expect("Failed to encode HostedRpcReply");
1044 dump_on_ipc_failure
1045 .run(write_frame_async(&mut self.connection, &msg).await)
1046 .await;
1047 }
1048
1049 pub async fn run_test(
1050 &mut self,
1051 nocapture: bool,
1052 test: &RegisteredTest,
1053 output: &dyn TestRunnerOutput,
1054 idx: usize,
1055 count: usize,
1056 ) -> TestResult {
1057 let mut capture_enabled = self.capture_enabled.lock().await;
1058 *capture_enabled = test.props.capture_control.requires_capturing(!nocapture);
1059 drop(capture_enabled);
1060
1061 let cmd = IpcCommand::RunTest {
1063 name: test.name.clone(),
1064 crate_name: test.crate_name.clone(),
1065 module_path: test.module_path.clone(),
1066 };
1067
1068 let dump_on_ipc_failure = self.dump_on_failure();
1069
1070 let msg = serialize_to_byte_vec(&cmd).expect("Failed to encode IPC command");
1071 dump_on_ipc_failure
1072 .run(write_frame_async(&mut self.connection, &msg).await)
1073 .await;
1074
1075 let response = loop {
1076 let response_bytes = dump_on_ipc_failure
1077 .run(read_frame_async(&mut self.connection).await)
1078 .await;
1079 let response: IpcResponse = dump_on_ipc_failure.run(deserialize(&response_bytes)).await;
1080 match response {
1081 IpcResponse::TestFinished { .. } => break response,
1082 IpcResponse::CloneableAccepted { .. }
1083 | IpcResponse::HostedDescriptorAccepted { .. } => continue,
1084 IpcResponse::HostedRpcCall {
1085 request_id,
1086 dep_id,
1087 method_idx,
1088 args_bytes,
1089 } => {
1090 self.handle_hosted_rpc_call(
1091 &dump_on_ipc_failure,
1092 request_id,
1093 dep_id,
1094 method_idx,
1095 args_bytes,
1096 )
1097 .await;
1098 continue;
1099 }
1100 }
1101 };
1102
1103 let IpcResponse::TestFinished {
1104 result,
1105 finish_marker,
1106 retries,
1107 worker_exhausted,
1108 } = response
1109 else {
1110 unreachable!("loop only breaks on TestFinished")
1111 };
1112 self.exhausted = worker_exhausted;
1113
1114 for retry in retries {
1115 output.repeat_running_test(
1116 test,
1117 idx,
1118 count,
1119 retry.attempt,
1120 retry.max_attempts,
1121 &retry.reason,
1122 );
1123 }
1124
1125 if test.props.capture_control.requires_capturing(!nocapture) {
1126 let out_lines: Vec<_> =
1127 Self::drain_until(self.out_lines.clone(), finish_marker.clone()).await;
1128 let err_lines: Vec<_> =
1129 Self::drain_until(self.err_lines.clone(), finish_marker.clone()).await;
1130 result.into_test_result(out_lines, err_lines)
1131 } else {
1132 result.into_test_result(Vec::new(), Vec::new())
1133 }
1134 }
1135
1136 async fn shutdown(mut self) {
1140 let msg = serialize_to_byte_vec(&IpcCommand::Shutdown)
1141 .expect("Failed to encode IPC shutdown command");
1142 let dump_on_ipc_failure = self.dump_on_failure();
1143 dump_on_ipc_failure
1144 .run(write_frame_async(&mut self.connection, &msg).await)
1145 .await;
1146
1147 self.process
1148 .wait()
1149 .await
1150 .expect("Failed to wait for worker process");
1151 }
1152
1153 async fn provide_cloneable(&mut self, dep_id: String, wire_bytes: Vec<u8>) {
1156 let dump_on_ipc_failure = self.dump_on_failure();
1157 let cmd = IpcCommand::ProvideCloneable {
1158 dep_id: dep_id.clone(),
1159 wire_bytes,
1160 };
1161 let msg = serialize_to_byte_vec(&cmd).expect("Failed to encode IPC command");
1162 dump_on_ipc_failure
1163 .run(write_frame_async(&mut self.connection, &msg).await)
1164 .await;
1165
1166 loop {
1167 let response_bytes = dump_on_ipc_failure
1168 .run(read_frame_async(&mut self.connection).await)
1169 .await;
1170 let response: IpcResponse = dump_on_ipc_failure.run(deserialize(&response_bytes)).await;
1171 match response {
1172 IpcResponse::CloneableAccepted { dep_id: ack_id } => {
1173 if ack_id == dep_id {
1174 return;
1175 }
1176 }
1177 IpcResponse::HostedDescriptorAccepted { .. } => {
1178 }
1180 IpcResponse::TestFinished { .. } => {
1181 }
1183 IpcResponse::HostedRpcCall {
1184 request_id,
1185 dep_id: rpc_dep_id,
1186 method_idx,
1187 args_bytes,
1188 } => {
1189 self.handle_hosted_rpc_call(
1194 &dump_on_ipc_failure,
1195 request_id,
1196 rpc_dep_id,
1197 method_idx,
1198 args_bytes,
1199 )
1200 .await;
1201 }
1202 }
1203 }
1204 }
1205
1206 async fn provide_hosted_descriptor(&mut self, dep_id: String, wire_bytes: Vec<u8>) {
1208 let dump_on_ipc_failure = self.dump_on_failure();
1209 let cmd = IpcCommand::ProvideHostedDescriptor {
1210 dep_id: dep_id.clone(),
1211 wire_bytes,
1212 };
1213 let msg = serialize_to_byte_vec(&cmd).expect("Failed to encode IPC command");
1214 dump_on_ipc_failure
1215 .run(write_frame_async(&mut self.connection, &msg).await)
1216 .await;
1217
1218 loop {
1219 let response_bytes = dump_on_ipc_failure
1220 .run(read_frame_async(&mut self.connection).await)
1221 .await;
1222 let response: IpcResponse = dump_on_ipc_failure.run(deserialize(&response_bytes)).await;
1223 match response {
1224 IpcResponse::HostedDescriptorAccepted { dep_id: ack_id } => {
1225 if ack_id == dep_id {
1226 return;
1227 }
1228 }
1229 IpcResponse::CloneableAccepted { .. } => {
1230 }
1232 IpcResponse::TestFinished { .. } => {
1233 }
1235 IpcResponse::HostedRpcCall {
1236 request_id,
1237 dep_id: rpc_dep_id,
1238 method_idx,
1239 args_bytes,
1240 } => {
1241 self.handle_hosted_rpc_call(
1244 &dump_on_ipc_failure,
1245 request_id,
1246 rpc_dep_id,
1247 method_idx,
1248 args_bytes,
1249 )
1250 .await;
1251 }
1252 }
1253 }
1254 }
1255
1256 fn dump_on_failure(&self) -> DumpOnFailure {
1257 DumpOnFailure {
1258 out_lines: self.out_lines.clone(),
1259 err_lines: self.err_lines.clone(),
1260 }
1261 }
1262
1263 async fn drain_until(
1264 source: Arc<Mutex<VecDeque<CapturedOutput>>>,
1265 finish_marker: String,
1266 ) -> Vec<CapturedOutput> {
1267 let mut result = Vec::new();
1268 loop {
1269 let mut source = source.lock().await;
1270 while let Some(line) = source.pop_front() {
1271 if line.line() == finish_marker {
1272 return result;
1273 } else {
1274 result.push(line.clone());
1275 }
1276 }
1277 drop(source);
1278
1279 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1280 }
1281 }
1282}
1283
1284struct DumpOnFailure {
1285 out_lines: Arc<Mutex<VecDeque<CapturedOutput>>>,
1286 err_lines: Arc<Mutex<VecDeque<CapturedOutput>>>,
1287}
1288
1289impl DumpOnFailure {
1290 pub async fn run<T, E>(&self, result: Result<T, E>) -> T {
1291 match result {
1292 Ok(value) => value,
1293 Err(_error) => {
1294 let out_lines: Vec<_> = self.out_lines.lock().await.drain(..).collect();
1295 let err_lines: Vec<_> = self.err_lines.lock().await.drain(..).collect();
1296 let mut all_lines = [out_lines, err_lines].concat();
1297 all_lines.sort();
1298
1299 use std::io::Write;
1307 let mut err = crate::host_capture::TerminalStderr;
1308 for line in all_lines {
1309 let _ = writeln!(err, "{}", line.line());
1310 }
1311 let _ = err.flush();
1312
1313 std::process::exit(1);
1314 }
1315 }
1316 }
1317}
1318
1319async fn spawn_worker_if_needed(args: &Arguments) -> Option<Worker> {
1320 if args.spawn_workers {
1321 let id = Uuid::new_v4();
1322 let name_str = format!("{id}.sock");
1323 let name = name_str
1324 .clone()
1325 .to_ns_name::<GenericNamespaced>()
1326 .expect("Invalid local socket name");
1327 let opts = ListenerOptions::new().name(name.clone());
1328 let listener = opts
1329 .create_tokio()
1330 .expect("Failed to create local socket listener");
1331
1332 let exe = std::env::current_exe().expect("Failed to get current executable path");
1333
1334 let mut args = args.clone();
1335 args.ipc = Some(name_str);
1336 args.spawn_workers = false;
1337 args.logfile = None;
1338 let args = args.to_args();
1339
1340 let mut process = Command::new(exe)
1341 .args(args)
1342 .stdin(Stdio::inherit())
1343 .stderr(Stdio::piped())
1344 .stdout(Stdio::piped())
1345 .spawn()
1346 .expect("Failed to spawn worker process");
1347
1348 let stdout = process.stdout.take().unwrap();
1349 let stderr = process.stderr.take().unwrap();
1350
1351 let out_lines = Arc::new(Mutex::new(VecDeque::new()));
1352 let err_lines = Arc::new(Mutex::new(VecDeque::new()));
1353 let capture_enabled = Arc::new(Mutex::new(true));
1354
1355 let out_lines_clone = out_lines.clone();
1356 let capture_enabled_clone = capture_enabled.clone();
1357 let out_handle = spawn(async move {
1358 let reader = BufReader::new(stdout);
1359 let mut lines = reader.lines();
1360 while let Some(line) = lines
1361 .next_line()
1362 .await
1363 .expect("Failed to read from worker stdout")
1364 {
1365 if *capture_enabled_clone.lock().await {
1366 out_lines_clone
1367 .lock()
1368 .await
1369 .push_back(CapturedOutput::stdout(line));
1370 } else {
1371 use std::io::Write;
1377 let mut out = crate::host_capture::TerminalStdout;
1378 let _ = writeln!(out, "{line}");
1379 let _ = out.flush();
1380 }
1381 }
1382 });
1383
1384 let err_lines_clone = err_lines.clone();
1385 let capture_enabled_clone = capture_enabled.clone();
1386 let err_handle = spawn(async move {
1387 let reader = BufReader::new(stderr);
1388 let mut lines = reader.lines();
1389 while let Some(line) = lines
1390 .next_line()
1391 .await
1392 .expect("Failed to read from worker stderr")
1393 {
1394 if *capture_enabled_clone.lock().await {
1395 err_lines_clone
1396 .lock()
1397 .await
1398 .push_back(CapturedOutput::stderr(line));
1399 } else {
1400 use std::io::Write;
1404 let mut err = crate::host_capture::TerminalStderr;
1405 let _ = writeln!(err, "{line}");
1406 let _ = err.flush();
1407 }
1408 }
1409 });
1410
1411 let connection = listener
1412 .accept()
1413 .await
1414 .expect("Failed to accept connection");
1415
1416 Some(Worker {
1417 _listener: listener,
1418 process,
1419 _out_handle: out_handle,
1420 _err_handle: err_handle,
1421 out_lines,
1422 err_lines,
1423 connection,
1424 capture_enabled,
1425 exhausted: false,
1426 hosted_rpc_owner_cells: Arc::new(HashMap::new()),
1427 })
1428 } else {
1429 None
1430 }
1431}
1432
1433fn install_local_hosted_rpc_stubs(
1439 execution: &mut TestSuiteExecution,
1440 rpc_factories: &HashMap<String, RpcFactory>,
1441 owner_cells: &HashMap<String, Arc<HostedRpcOwnerCell>>,
1442) {
1443 let transport: Arc<dyn HostedRpcTransport> =
1444 Arc::new(InProcessHostedRpcTransport::new(owner_cells.clone()));
1445 for (dep_id, factory) in rpc_factories.iter() {
1446 if !owner_cells.contains_key(dep_id) {
1447 continue;
1451 }
1452 let channel = HostedRpcChannel::new(dep_id.clone(), transport.clone());
1453 let stub = (factory.build_stub)(channel);
1454 let applied = execution.provide_cloneable_value(dep_id, stub);
1455 if !applied {
1456 continue;
1462 }
1463 }
1464}
1465
1466async fn install_worker_subprocess_hosted_rpc_stubs(
1471 execution: &Arc<Mutex<TestSuiteExecution>>,
1472 rpc_factories: &HashMap<String, RpcFactory>,
1473 connection_arc: Arc<Mutex<Stream>>,
1474) {
1475 let transport: Arc<dyn HostedRpcTransport> =
1476 Arc::new(IpcHostedRpcTransport::new(connection_arc));
1477 for (dep_id, factory) in rpc_factories.iter() {
1478 let channel = HostedRpcChannel::new(dep_id.clone(), transport.clone());
1479 let stub = (factory.build_stub)(channel);
1480 let mut execution = execution.lock().await;
1481 let applied = execution.provide_cloneable_value(dep_id, stub);
1482 let _ = applied;
1485 }
1486}
1487
1488struct IpcHostedRpcTransport {
1506 connection: Arc<Mutex<Stream>>,
1507 next_request_id: AtomicU64,
1508}
1509
1510impl IpcHostedRpcTransport {
1511 fn new(connection: Arc<Mutex<Stream>>) -> Self {
1512 Self {
1513 connection,
1514 next_request_id: AtomicU64::new(0),
1515 }
1516 }
1517}
1518
1519impl HostedRpcTransport for IpcHostedRpcTransport {
1520 fn call(
1521 &self,
1522 dep_id: &str,
1523 method_idx: u32,
1524 args: Vec<u8>,
1525 ) -> Result<Vec<u8>, HostedRpcError> {
1526 let request_id = self.next_request_id.fetch_add(1, Ordering::SeqCst);
1527 let call = IpcResponse::HostedRpcCall {
1528 request_id,
1529 dep_id: dep_id.to_string(),
1530 method_idx,
1531 args_bytes: args,
1532 };
1533 let msg = serialize_to_byte_vec(&call).map_err(|e| {
1534 HostedRpcError::Transport(format!("encode HostedRpcCall failed: {e:?}"))
1535 })?;
1536
1537 let connection = self.connection.clone();
1538 let handle = tokio::runtime::Handle::current();
1539
1540 tokio::task::block_in_place(move || {
1545 handle.block_on(async move {
1546 let mut conn = connection.lock().await;
1547 write_frame_async(&mut *conn, &msg).await.map_err(|e| {
1548 HostedRpcError::Transport(format!("write HostedRpcCall failed: {e:?}"))
1549 })?;
1550 let reply_bytes = read_frame_async(&mut *conn).await.map_err(|e| {
1551 HostedRpcError::Transport(format!("read HostedRpcReply failed: {e:?}"))
1552 })?;
1553 let command: IpcCommand = deserialize(&reply_bytes).map_err(|e| {
1554 HostedRpcError::Transport(format!("decode HostedRpcReply failed: {e:?}"))
1555 })?;
1556 match command {
1557 IpcCommand::HostedRpcReply {
1558 request_id: reply_id,
1559 body,
1560 } => {
1561 if reply_id != request_id {
1562 return Err(HostedRpcError::Transport(format!(
1563 "HostedRpcReply request_id mismatch: expected {request_id}, got {reply_id}"
1564 )));
1565 }
1566 match body {
1567 HostedRpcReplyBody::Ok { result_bytes } => Ok(result_bytes),
1568 HostedRpcReplyBody::Err { message } => {
1569 Err(HostedRpcError::Dispatch(message))
1570 }
1571 }
1572 }
1573 other => Err(HostedRpcError::Transport(format!(
1574 "unexpected IpcCommand while waiting for HostedRpcReply: {other:?}"
1575 ))),
1576 }
1577 })
1578 })
1579 }
1580}