Skip to main content

test_r_core/
tokio.rs

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    // When the parent spawned this process as a worker it passed
50    // `--worker-index <N>`. Stash it so `crate::worker::worker_index()`
51    // returns the correct value for PerWorker dep constructors.
52    if let Some(idx) = args.worker_index {
53        crate::worker::set_worker_index(idx);
54    }
55    // Host-side output capture is installed PER retry attempt below
56    // (after `finalize_for_execution`), mirroring the sync runner.
57    // See `crate::host_capture` for the pipeline.
58    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(&registered_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        // Apply suite properties (including runtime matrix-suite multiplication)
76        // before listing, so matrix-multiplied cases appear in `--list` output
77        // with their `<test>_<case>` names and `:tag:`-selectable auto-tags.
78        let tests_with_props =
79            internal::apply_suite_props_to_tests(&all_tests, &registered_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            // Install host capture for this attempt, after
96            // `finalize_for_execution` has decided whether workers
97            // will spawn. See `sync::test_runner` for the rationale.
98            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            // Parent-side collection for dependency scopes whose worker-side
106            // value is shipped as bytes or represented as an RPC stub. Async
107            // constructors are awaited here, before workers receive their
108            // reconstructed values. Skip it for empty filtered runs.
109            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            // Pre-built RpcFactory lookup keyed by qualified id, so worker
133            // subprocesses can build stubs without re-locking the global
134            // REGISTERED_DEPENDENCY_CONSTRUCTORS.
135            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            // Build a combined Cloneable + Hosted codec/worker lookup table
148            // now, before `test_thread` workers are spawned (see sync.rs
149            // for rationale). Keyed by the dep's fully-qualified id
150            // (`{crate}::{module}::{name}`) so workers can route an incoming
151            // `ProvideCloneable` / `ProvideHostedDescriptor` to the correct
152            // dep even when two deps share a local `name` in different
153            // modules.
154            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            // Mode-consistent Cloneable semantics for the no-spawn-workers
172            // path (e.g. `--nocapture`): reuse the parent-constructed value
173            // directly instead of re-running the user constructor in
174            // `materialize_deps`. Without this, a Cloneable dep's
175            // constructor would run twice (once for parent-side
176            // `collect_parent_shared_dependencies_async`, once for the
177            // in-process test execution), which both violates the
178            // "constructor runs once" expectation and can deadlock when
179            // the constructor takes a runtime-wide lock.
180            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            // Mode-consistent Hosted semantics: when this is the top-level
184            // parent AND we do NOT spawn workers (e.g. --nocapture), the
185            // test functions run in this same process, but they must still
186            // see the *worker-side handle* produced by
187            // `HostedDep::from_descriptor`. Reconstruct each handle locally
188            // via the descriptor round-trip and pre-populate the execution
189            // tree.
190            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            // Mode-consistent HostedRpc semantics for the no-spawn-workers
199            // path: install in-process stubs that route straight to the
200            // parent-held owner cells, so tests see the same `Stub` value
201            // whether or not the runner spawns workers.
202            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            // Mirror of `sync::apply_parent_constructed_shared_values_locally`:
210            // in no-spawn-workers mode, install any `Shared`/`PerWorker` dep
211            // values the parent had to construct as transitive inputs to a
212            // Cloneable/Hosted/HostedRpc dep. The in-process test thread's
213            // `materialize_deps` then reuses them instead of re-running the
214            // constructor in the same process.
215            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            // println!("Execution plan: {execution:?}");
229            // println!("Final args: {args:?}");
230            // println!("Has dependencies: {:?}", execution.has_dependencies());
231
232            let count = execution.remaining();
233            let results = Arc::new(Mutex::new(Vec::with_capacity(count)));
234            // Parent-side per-test execution windows aligned 1:1 with
235            // `results`. The host-capture finaliser uses them after all
236            // test_threads finish to attribute spilled host-log records
237            // to the test(s) whose window contains each record.
238            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                // Stamp each test-thread's args with the worker index it will
257                // hand to its spawned child via `--worker-index <N>`.
258                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 parent-owned hosted / hosted-rpc owners BEFORE
303            // finalising host capture so any `Drop` impls that
304            // shutdown background threads / subprocesses get a chance
305            // to emit their final lines through the still-active
306            // capture pipe. If we restored fd 1/2 first, those late
307            // lines would either land on the about-to-render
308            // structured output or be swallowed entirely.
309            drop(hosted_rpc_owner_cells);
310            drop(_hosted_owners);
311
312            // Finalise host capture (if any) BEFORE rendering the
313            // suite so the attributed host-log records make it into
314            // the per-test captured-output vecs the formatter walks.
315            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            // IPC workers execute exactly one parent-controlled dispatch
332            // session. Suite-level retries belong to the top-level parent;
333            // after Shutdown this subprocess must exit instead of reconnecting
334            // to the same listener for an independent retry attempt.
335            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    // Parent dispatches incoming `HostedRpcCall` frames against the owner
362    // cells materialised in the top-level parent. Workers don't need the owner
363    // cells (they own stubs instead), so they receive an empty map and the
364    // dispatch code path is never reached in subprocesses.
365    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    // The buffer belongs to this worker command loop, not the whole suite.
379    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        // Ship every Hosted dep's descriptor bytes too.
394        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    // Worker subprocess side: build a stub for every HostedRpc dep registered
402    // in this binary using the IPC-backed transport sharing the same socket as
403    // the main IPC loop. Install the stubs in the execution tree so dependency
404    // materialisation skips the parent-only owner constructor.
405    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                        // Worker-side reconstruction (see sync.rs::apply_provided_wire_bytes).
450                        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                        // Worker-side reconstruction: same shape as
468                        // ProvideCloneable but routed through the registered
469                        // HostedDep worker_fn.
470                        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                        // HR1.2: replies for worker-initiated HostedRpc calls
488                        // are consumed inline by the IPC transport during
489                        // test execution, never by this between-tests
490                        // command loop. Receiving one here means the
491                        // protocol got out of sync; surface that loudly
492                        // rather than dropping the frame.
493                        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                // Snapshot the parent's monotonic-clock view of the
519                // test start. The matching end-instant is captured
520                // after `finished_running_test`, and the pair becomes
521                // a `HostWindow` for record attribution. Uses
522                // `std::time::Instant` because the host-capture epoch
523                // is `std::time::Instant` (tokio's `Instant` is a
524                // different type without `From` interop).
525                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                // Push the result and its window under the same
579                // critical section so the two vecs stay aligned in the
580                // face of concurrent pushes from sibling test_threads.
581                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
608/// Async counterpart to `sync::apply_provided_wire_bytes`. Decodes the wire
609/// bytes into a worker-side dependency value (looked up by the dep's
610/// fully-qualified id `{crate}::{module}::{name}`) and stores it in the
611/// execution tree so the next `materialize_deps` call uses the pre-resolved
612/// value.
613///
614/// `source_command` is the textual name of the IPC command that delivered
615/// the bytes (`"ProvideCloneable"` or `"ProvideHostedDescriptor"`); used
616/// only in panic messages.
617async 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
644/// Mode-consistent Cloneable semantics for the no-spawn-workers path on
645/// the tokio runner. Mirrors `sync::apply_cloneable_values_locally`: takes
646/// the parent-constructed Cloneable values and installs them directly
647/// into the parent's `TestSuiteExecution`, so `materialize_deps` reuses
648/// them instead of re-running the user constructor.
649///
650/// For `Cloneable`, the documented round-trip
651/// `from_wire(to_wire(value))` is semantics-preserving, so reusing the
652/// parent value directly is equivalent to round-tripping it through the
653/// wire codec while avoiding the duplicate constructor run that would
654/// otherwise occur on the no-spawn-workers code path. The duplicate run
655/// historically caused user-visible problems (extra observable side
656/// effects under `--nocapture`, and deadlocks when the constructor takes
657/// a runtime-wide lock).
658fn 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
671/// Tokio counterpart to `sync::apply_parent_constructed_shared_values_locally`.
672/// In no-spawn-workers mode, installs `Shared`/`PerWorker` dep values that
673/// the parent had to construct as transitive inputs to a
674/// Cloneable/Hosted/HostedRpc dep, so the in-process test thread reuses
675/// them instead of re-running the constructor in the same process.
676fn 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
689/// Mode-consistent Hosted semantics for the no-spawn-workers path on the
690/// tokio runner. Mirrors `sync::apply_hosted_descriptors_locally`: takes
691/// the parent-collected descriptor bytes and reconstructs each Hosted
692/// dep's worker-side handle (via the registered codec + worker_fn)
693/// directly in the parent's `TestSuiteExecution`.
694///
695/// Both `WorkerReconstructor::Sync` (`HostedDep::from_descriptor`) and
696/// `WorkerReconstructor::Async` (`AsyncHostedDep::from_descriptor`) are
697/// supported here so that `async_worker` Hosted deps see the same
698/// worker-side handle whether the runner ended up in spawned-worker mode
699/// or in the no-spawn fallback, matching the documented mode-consistent
700/// Hosted contract in `book/src/advanced_features/dependency_sharing.md`.
701async 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    /// Parent-held HostedRpc owner cells keyed by fully-qualified dep id. Used
1000    /// to dispatch incoming `IpcResponse::HostedRpcCall` frames from the worker
1001    /// subprocess back to the right owner.
1002    hosted_rpc_owner_cells: Arc<HashMap<String, Arc<HostedRpcOwnerCell>>>,
1003}
1004
1005impl Worker {
1006    /// Installs the parent-side map of HostedRpc owner cells so this worker can
1007    /// route incoming `IpcResponse::HostedRpcCall` frames to the right
1008    /// `HostedRpcOwnerCell` while waiting for a worker subprocess response.
1009    fn set_hosted_rpc_owner_cells(&mut self, cells: Arc<HashMap<String, Arc<HostedRpcOwnerCell>>>) {
1010        self.hosted_rpc_owner_cells = cells;
1011    }
1012
1013    /// Parent-side dispatcher for a single `IpcResponse::HostedRpcCall`. Looks
1014    /// up the owner cell by fully-qualified dep id, runs the dispatch on the
1015    /// parent's stored owner, and writes the matching
1016    /// `IpcCommand::HostedRpcReply` back to the worker subprocess. Mirrors
1017    /// `sync::Worker::handle_hosted_rpc_call`.
1018    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            // Use the async dispatch entry point so an owner that implements
1028            // `AsyncHostedRpcDep` directly can `.await` inside its dispatcher
1029            // without blocking the tokio runtime. Sync owners reach this
1030            // entry point through the blanket bridge and their dispatched
1031            // future resolves immediately.
1032            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        // Send IPC command and wait for IPC response, and in the meantime read from the stdout/stderr channels
1062        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    /// Ends this worker only after its owning scheduler thread has finished.
1137    /// A worker cannot infer that fact from its private execution plan because
1138    /// its test order may diverge from the shared parent scheduler.
1139    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 counterpart to `sync::Worker::provide_cloneable`. `dep_id` is the
1154    /// dep's fully-qualified id (`{crate}::{module}::{name}`).
1155    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                    // Out-of-band ack from a previous ProvideHostedDescriptor; ignore.
1179                }
1180                IpcResponse::TestFinished { .. } => {
1181                    // Should not happen before any RunTest.
1182                }
1183                IpcResponse::HostedRpcCall {
1184                    request_id,
1185                    dep_id: rpc_dep_id,
1186                    method_idx,
1187                    args_bytes,
1188                } => {
1189                    // A worker subprocess can issue a HostedRpc call from
1190                    // inside an in-progress test, even while the parent is
1191                    // mid-`ProvideCloneable` for a different dep. Dispatch it
1192                    // so the protocol doesn't desync.
1193                    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 counterpart to `sync::Worker::provide_hosted_descriptor`.
1207    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                    // Out-of-band ack from a previous ProvideCloneable; ignore.
1231                }
1232                IpcResponse::TestFinished { .. } => {
1233                    // Should not happen before any RunTest.
1234                }
1235                IpcResponse::HostedRpcCall {
1236                    request_id,
1237                    dep_id: rpc_dep_id,
1238                    method_idx,
1239                    args_bytes,
1240                } => {
1241                    // See provide_cloneable arm. Dispatch the call inline so
1242                    // the IPC stream stays in sync.
1243                    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                // Route the diagnostic through the real terminal even
1300                // when host capture has fd 2 redirected into its pipe.
1301                // We `process::exit(1)` immediately after this and
1302                // never reach `host_capture.finalize()`, so anything we
1303                // wrote into the host pipe would be lost. The capture
1304                // pipe and its reader are abandoned on exit; that is
1305                // acceptable for this fatal-IPC path.
1306                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                    // `#[never_capture]` pass-through: write to the real
1372                    // terminal even when host capture has redirected
1373                    // fd 1 into its pipe, so the worker line stays
1374                    // uncaptured live output and is not later
1375                    // re-labelled `[host]`.
1376                    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                    // Same as the stdout pass-through above: route the
1401                    // never-captured worker line to the real terminal
1402                    // stderr, not the host capture pipe.
1403                    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
1433/// Parent-side `--nocapture` / no-spawn-workers helper. Builds one stub per
1434/// HostedRpc dep using an [`InProcessHostedRpcTransport`] that points at the
1435/// parent-held owner cells, and stashes it in the execution tree so dependency
1436/// materialisation skips the owner-only constructor. Mirrors
1437/// `sync::install_local_hosted_rpc_stubs`.
1438fn 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            // No owner cell materialised for this dep (e.g. registered
1448            // globally but not pulled into the current filter). Skip so
1449            // we don't install a stub nothing routes.
1450            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            // The owner cell can be materialised solely because another
1457            // parent-side Cloneable/Hosted/HostedRpc dependency needs this
1458            // HostedRpc dep as a constructor input. In that case the stub is
1459            // intentionally not present in the worker execution tree; there is
1460            // nothing to pre-populate for no-spawn test execution.
1461            continue;
1462        }
1463    }
1464}
1465
1466/// Worker subprocess helper. Builds one stub per registered HostedRpc dep backed
1467/// by [`IpcHostedRpcTransport`], and installs it in the execution tree. Mirrors
1468/// `sync::install_worker_subprocess_hosted_rpc_stubs` but runs on the tokio
1469/// `Arc<Mutex<Stream>>` connection.
1470async 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        // Not every binary registers a HostedRpc dep that the current
1483        // execution actually uses; if so, just move on.
1484        let _ = applied;
1485    }
1486}
1487
1488/// Worker subprocess `HostedRpcTransport` for the tokio runner.
1489/// Mirrors `sync::IpcHostedRpcTransport` but bridges a sync trait method
1490/// to the async tokio IPC primitives via
1491/// `tokio::task::block_in_place` + `Handle::current().block_on(...)`.
1492///
1493/// The shared `Arc<Mutex<Stream>>` is the same one used by the
1494/// worker subprocess's main IPC loop; the lock guarantees that a stub
1495/// call and the main loop never interleave a half-written frame. Calls
1496/// serialise across all in-flight stubs by acquiring the mutex for the
1497/// full request-then-reply round trip.
1498///
1499/// This relies on the temporal invariant documented on
1500/// [`crate::internal::HostedRpcChannel::call`]: stubs are only invoked
1501/// from inside a running test body, never from `build_stub`, and never
1502/// from detached background work that outlives the test. Under those
1503/// rules the main IPC loop is only reading between tests, so it cannot
1504/// race with a stub call.
1505struct 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        // Run the async I/O round-trip from inside this sync trait
1541        // method. `block_in_place` releases this worker thread back to
1542        // the scheduler so the parent's read loop can continue making
1543        // progress on other tasks while we wait for the reply.
1544        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}