Skip to main content

mesh_process/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Infrastructure to create a multi-process mesh and spawn child processes
5//! within it.
6//!
7//! Call [`Mesh::new()`] to create a process group. Workers launched on the mesh
8//! can run in child processes connected by the platform IPC transport
9//! (`mesh_remote`): Unix domain sockets on Linux, ALPC on Windows.
10//!
11//! The child process receives an invitation via an environment variable and
12//! calls [`try_run_mesh_host()`] early in `main()` to join the mesh. Once
13//! joined, ports (and the resources they carry) flow transparently between
14//! parent and child.
15//!
16//! This crate is used by OpenVMM to launch worker processes and by OpenHCL to
17//! run device emulators in isolated child processes.
18
19// UNSAFETY: Needed to accept a raw Fd/Handle from our spawning process.
20#![expect(unsafe_code)]
21
22cfg_select! {
23    windows => {
24        use pal::windows::process;
25        use std::os::windows::prelude::*;
26
27        mod plat {
28            pub type IpcNode = mesh_remote::windows::AlpcNode;
29            pub type IpcNodeDriver = pal_async::windows::TpPool;
30        }
31    }
32    unix => {
33        use mesh_remote::InvitationAddress;
34        use pal_async::DefaultPool;
35        use std::os::unix::prelude::*;
36
37        mod plat {
38            pub type IpcNode = mesh_remote::unix::UnixNode;
39            pub type IpcNodeDriver = pal_async::DefaultDriver;
40        }
41    }
42}
43
44use anyhow::Context;
45use base64::Engine;
46use debug_ptr::DebugPtr;
47use futures::FutureExt;
48use futures::Stream;
49use futures::StreamExt;
50use futures::executor::block_on;
51use futures_concurrency::future::Race;
52use inspect::Inspect;
53use inspect::SensitivityLevel;
54use mesh::MeshPayload;
55use mesh::OneshotReceiver;
56use mesh::local_node::Port;
57use mesh::message::MeshField;
58use mesh::payload::Protobuf;
59use mesh::rpc::FailableRpc;
60use mesh::rpc::RpcSend;
61use pal_async::task::Spawn;
62use pal_async::task::Task;
63use plat::IpcNode;
64use plat::IpcNodeDriver;
65use slab::Slab;
66use std::borrow::Cow;
67use std::ffi::OsString;
68use std::fs::File;
69use std::path::Path;
70use std::path::PathBuf;
71use std::pin::Pin;
72use tracing::Instrument;
73use tracing::instrument;
74use unicycle::FuturesUnordered;
75
76#[cfg(unix)]
77const IPC_FD: i32 = 3;
78
79/// The environment variable for passing the mesh IPC invitation information to
80/// a child process. This is passed through the environment instead of a command
81/// line argument so that other processes cannot steal the invitation details
82/// and use it to break into the mesh.
83const INVITATION_ENV_NAME: &str = "MESH_WORKER_INVITATION";
84
85#[derive(Protobuf)]
86struct Invitation {
87    node_name: String,
88    #[cfg(windows)]
89    credentials: mesh_remote::windows::AlpcInvitationCredentials,
90    #[cfg(unix)]
91    address: InvitationAddress,
92    #[cfg(windows)]
93    directory_handle: usize,
94    #[cfg(unix)]
95    socket_fd: i32,
96}
97
98static PROCESS_NAME: DebugPtr<String> = DebugPtr::new();
99
100/// Runs a mesh host in the current thread, then exits the process, if this
101/// process was launched by [`Mesh::launch_host`].
102///
103/// The mesh invitation is provided via environment variables. If a mesh
104/// invitation is not available this function will return immediately with `Ok`.
105/// If a mesh invitation is available, this function joins the mesh and runs the
106/// future returned by `f` until `f` returns or the parent process shuts down
107/// the mesh.
108pub fn try_run_mesh_host<U, F, T>(base_name: &str, f: F) -> anyhow::Result<()>
109where
110    U: 'static + MeshPayload + Send,
111    F: AsyncFnOnce(U) -> anyhow::Result<T>,
112{
113    block_on(async {
114        if let Some(r) = node_from_environment().await? {
115            let NodeResult {
116                node_name,
117                node,
118                initial_port,
119            } = r;
120            PROCESS_NAME.store(&node_name);
121            set_program_name(&format!("{base_name}-{node_name}"));
122            let init = OneshotReceiver::<InitialMessage<U>>::from(initial_port)
123                .await
124                .context("failed to receive initial message")?;
125            let _drop = (
126                f(init.init_message).map(Some),
127                handle_host_requests(init.requests).map(|()| None),
128            )
129                .race()
130                .await
131                .transpose()?;
132
133            tracing::debug!("waiting to shut down node");
134            node.shutdown().await;
135            drop(_drop);
136            std::process::exit(0);
137        }
138        Ok(())
139    })
140}
141
142async fn handle_host_requests(mut recv: mesh::Receiver<HostRequest>) {
143    while let Some(req) = recv.next().await {
144        match req {
145            HostRequest::Inspect(deferred) => {
146                deferred.respond(inspect_host);
147            }
148            HostRequest::Crash => panic!("explicit panic request"),
149        }
150    }
151}
152
153fn set_program_name(name: &str) {
154    let _ = name;
155    #[cfg(target_os = "linux")]
156    {
157        let _ = std::fs::write("/proc/self/comm", name);
158    }
159}
160
161struct NodeResult {
162    node_name: String,
163    node: IpcNode,
164    initial_port: Port,
165}
166
167/// Create an IPC node from an invitation provided via the process environment.
168///
169/// Returns `None` if the invitation is not present in the environment.
170async fn node_from_environment() -> anyhow::Result<Option<NodeResult>> {
171    // return early with no node if the invitation is not present in the environment.
172    let invitation_str = match std::env::var(INVITATION_ENV_NAME) {
173        Ok(str) => str,
174        Err(_) => return Ok(None),
175    };
176
177    // Clear the string to avoid leaking the invitation information into child
178    // processes.
179    //
180    // TODO: this function is unsafe because
181    // it can cause UB if non-Rust code is concurrently accessing the
182    // environment in another thread. To be completely sound,
183    // either this function and its callers need to become
184    // `unsafe`, or we need to avoid using the environment to propagate the
185    // invitation so that we can avoid this call.
186    //
187    // SAFETY: Seems to work so far.
188    unsafe {
189        std::env::remove_var(INVITATION_ENV_NAME);
190    }
191
192    let invitation: Invitation = mesh::payload::decode(
193        &base64::engine::general_purpose::STANDARD
194            .decode(invitation_str)
195            .context("failed to base64 decode invitation")?,
196    )
197    .context("failed to protobuf decode invitation")?;
198
199    let (left, right) = Port::new_pair();
200
201    let node;
202    #[cfg(windows)]
203    {
204        // SAFETY: trusting the initiating process to pass a valid handle. A
205        // malicious process could pass a bad handle here, but a malicious
206        // process could also just corrupt our memory arbitrarily, so...
207        let directory =
208            unsafe { OwnedHandle::from_raw_handle(invitation.directory_handle as RawHandle) };
209
210        let invitation =
211            mesh_remote::windows::AlpcInvitation::new(invitation.credentials, directory);
212
213        // join the node w/ the provided invitation and the send port of the channel.
214        node = mesh_remote::windows::AlpcNode::join(
215            pal_async::windows::TpPool::system(),
216            invitation,
217            left,
218        )
219        .context("failed to join mesh")?;
220    }
221
222    #[cfg(unix)]
223    {
224        // SAFETY: trusting the initiating process to pass a valid fd. A
225        // malicious process could pass a bad fd here, but a malicious
226        // process could also just corrupt our memory arbitrarily, so...
227        let fd = unsafe { OwnedFd::from_raw_fd(invitation.socket_fd) };
228        let invitation = mesh_remote::unix::UnixInvitation {
229            address: invitation.address,
230            fd,
231        };
232
233        // FUTURE: use pool provided by the caller.
234        let (_, driver) = DefaultPool::spawn_on_thread("mesh-worker-pool");
235        node = mesh_remote::unix::UnixNode::join(driver, invitation, left)
236            .await
237            .context("failed to join mesh")?;
238    }
239
240    Ok(Some(NodeResult {
241        node_name: invitation.node_name,
242        node,
243        initial_port: right,
244    }))
245}
246
247/// Represents a mesh::Node with the ability to spawn new processes that can
248/// communicate with any other process belonging to the same mesh.
249///
250/// # Process creation
251/// A `Mesh` instance can spawn new processes with an initial communication
252/// channel associated with the mesh. All processes originating from the same
253/// mesh can potentially communicate and exchange channels with each other.
254///
255/// Each spawned process can be configured differently via [`ProcessConfig`].
256/// Processes are created with [`Mesh::launch_host`].
257///
258/// ```no_run
259/// # use mesh_process::{Mesh, ProcessConfig};
260/// # futures::executor::block_on(async {
261/// let mesh = Mesh::new("remote_mesh".to_string()).unwrap();
262/// let (send, recv) = mesh::channel();
263/// mesh.launch_host(ProcessConfig::new("test"), recv).await.unwrap();
264/// send.send(String::from("message for new process"));
265/// # })
266/// ```
267#[derive(Inspect)]
268pub struct Mesh {
269    #[inspect(rename = "name")]
270    mesh_name: String,
271    #[inspect(flatten, send = "MeshRequest::Inspect")]
272    request: mesh::Sender<MeshRequest>,
273    #[inspect(skip)]
274    task: Task<()>,
275}
276
277/// Configuration for launching a new process in the mesh.
278pub struct ProcessConfig {
279    name: String,
280    process_name: Option<PathBuf>,
281    process_args: Vec<OsString>,
282    stderr: Option<File>,
283    skip_worker_arg: bool,
284    sandbox_profile: Option<Box<sandbox::Profile>>,
285    env_vars: Vec<(OsString, OsString)>,
286}
287
288impl ProcessConfig {
289    /// Returns new process configuration using the current process as the
290    /// process name.
291    pub fn new(name: impl Into<String>) -> Self {
292        Self {
293            name: name.into(),
294            process_name: None,
295            process_args: Vec::new(),
296            stderr: None,
297            skip_worker_arg: false,
298            sandbox_profile: None,
299            env_vars: Vec::new(),
300        }
301    }
302
303    /// Returns a process configuration with sandbox launch preparation, using
304    /// the current process as the process name.
305    ///
306    /// Mesh uses the profile to prepare PAL's launch restrictions. It does not
307    /// send the profile to the child, call [`sandbox::apply`] in the child, or
308    /// verify that the child applies the same profile.
309    ///
310    /// The consumer must arrange for the child to call [`sandbox::apply`] with
311    /// the same profile before starting worker threads, joining Mesh, or
312    /// processing untrusted input, and terminate if application fails. Without
313    /// that call, only launch-time restrictions are established; worker-side
314    /// confinement is not applied.
315    pub fn new_with_sandbox(name: impl Into<String>, sandbox_profile: sandbox::Profile) -> Self {
316        Self {
317            name: name.into(),
318            process_name: None,
319            process_args: Vec::new(),
320            stderr: None,
321            skip_worker_arg: false,
322            sandbox_profile: Some(Box::new(sandbox_profile)),
323            env_vars: Vec::new(),
324        }
325    }
326
327    /// Sets the process name.
328    pub fn process_name(mut self, name: impl Into<PathBuf>) -> Self {
329        self.process_name = Some(name.into());
330        self
331    }
332
333    /// Specifies whether to  appending `<node name>` to the process's command
334    /// line.
335    ///
336    /// This is done by default to make it easier to identify the process in
337    /// task lists, but if your process parses the command line then this may
338    /// get in the way.
339    pub fn skip_worker_arg(mut self, skip: bool) -> Self {
340        self.skip_worker_arg = skip;
341        self
342    }
343
344    /// Adds arguments to the process command line.
345    pub fn args<I>(mut self, args: I) -> Self
346    where
347        I: IntoIterator,
348        I::Item: Into<OsString>,
349    {
350        self.process_args.extend(args.into_iter().map(|x| x.into()));
351        self
352    }
353
354    /// Adds environment variables when launching the process.
355    pub fn env<I>(mut self, env_vars: I) -> Self
356    where
357        I: IntoIterator,
358        I::Item: Into<(OsString, OsString)>,
359    {
360        self.env_vars.extend(env_vars.into_iter().map(|x| x.into()));
361        self
362    }
363
364    /// Sets the process's stderr to `file`.
365    pub fn stderr(mut self, file: Option<File>) -> Self {
366        self.stderr = file;
367        self
368    }
369}
370
371struct MeshInner {
372    requests: mesh::Receiver<MeshRequest>,
373    hosts: Slab<MeshHostInner>,
374    /// Handles for spawned host processes.
375    waiters: FuturesUnordered<Task<usize>>,
376    /// Mesh node for host process communication.
377    node: IpcNode,
378    /// IO driver for the mesh node, used for listener accept loops,
379    /// handshakes, and general async task spawning. This is the same
380    /// driver that was passed to the node on creation.
381    node_driver: IpcNodeDriver,
382    /// Name for this mesh instance, used for tracing/debugging.
383    mesh_name: String,
384    /// Job object. When closed, it will terminate all the child processes. This
385    /// is used to ensure the child processes don't outlive the parent.
386    #[cfg(windows)]
387    job: pal::windows::job::Job,
388}
389
390struct MeshHostInner {
391    name: String,
392    pid: i32,
393    node_id: mesh::NodeId,
394    send: mesh::Sender<HostRequest>,
395}
396
397enum MeshRequest {
398    NewHost(FailableRpc<NewHostParams, i32>),
399    Listen(FailableRpc<ListenParams, Task<()>>),
400    Inspect(inspect::Deferred),
401    Crash(i32),
402}
403
404struct ListenParams {
405    path: PathBuf,
406    port_factory: Box<dyn Fn() -> Port + Send>,
407}
408
409struct NewHostParams {
410    config: ProcessConfig,
411    recv: Port,
412    request_send: mesh::Sender<HostRequest>,
413}
414
415impl Mesh {
416    /// Creates a new mesh with the given name.
417    pub fn new(mesh_name: String) -> anyhow::Result<Self> {
418        #[cfg(windows)]
419        let job = {
420            let job = pal::windows::job::Job::new().context("failed to create job object")?;
421            job.set_terminate_on_close()
422                .context("failed to set job object terminate on close")?;
423            job
424        };
425
426        let (node, node_driver) = cfg_select! {
427            windows => {{
428                let driver = pal_async::windows::TpPool::system();
429                // Use new_named so that the ALPC directory has a path in the Ob
430                // namespace. This is required for listen() — the listener handshake
431                // creates named invitations, which need a named directory.
432                let node = mesh_remote::windows::AlpcNode::new_named(driver.clone())
433                    .context("AlpcNode creation failure")?;
434                (node, driver)
435            }}
436            unix => {{
437                // FUTURE: use pool provided by the caller.
438                let (_, driver) = DefaultPool::spawn_on_thread("mesh-worker-pool");
439                let node = mesh_remote::unix::UnixNode::new(driver.clone());
440                (node, driver)
441            }}
442        };
443
444        let (request, requests) = mesh::channel();
445
446        let mut inner = MeshInner {
447            requests,
448            hosts: Default::default(),
449            waiters: Default::default(),
450            node,
451            node_driver: node_driver.clone(),
452            mesh_name: mesh_name.clone(),
453            #[cfg(windows)]
454            job,
455        };
456
457        let task = node_driver.spawn(
458            format!("mesh-{}", mesh_name),
459            async move { inner.run().await },
460        );
461
462        Ok(Self {
463            request,
464            mesh_name,
465            task,
466        })
467    }
468
469    /// Spawns a new host in the mesh with the provided configuration and
470    /// initial message.
471    ///
472    /// The initial message will be provided to the closure passed to
473    /// [`try_run_mesh_host()`].
474    ///
475    /// Returns the process ID of the launched host.
476    pub async fn launch_host<T: 'static + MeshField + Send>(
477        &self,
478        config: ProcessConfig,
479        initial_message: T,
480    ) -> anyhow::Result<i32> {
481        let (request_send, request_recv) = mesh::channel();
482
483        let (init_send, init_recv) = mesh::oneshot::<InitialMessage<T>>();
484        init_send.send(InitialMessage {
485            requests: request_recv,
486            init_message: initial_message,
487        });
488
489        self.request
490            .call_failable(
491                MeshRequest::NewHost,
492                NewHostParams {
493                    config,
494                    recv: init_recv.into(),
495                    request_send,
496                },
497            )
498            .await
499            .context("failed to launch new host")
500    }
501
502    /// Shutdown the mesh and wait for any spawned processes to exit.
503    ///
504    /// The `Mesh` instance is no longer usable after `shutdown`.
505    pub async fn shutdown(self) {
506        let span = tracing::span!(
507            tracing::Level::INFO,
508            "mesh_shutdown",
509            name = self.mesh_name.as_str(),
510        );
511
512        async {
513            drop(self.request);
514            self.task.await;
515        }
516        .instrument(span)
517        .await;
518    }
519
520    /// Crashes the child process with the given process ID.
521    pub fn crash(&self, pid: i32) {
522        self.request.send(MeshRequest::Crash(pid));
523    }
524
525    /// Listen for mesh connections on a Unix socket.
526    ///
527    /// Returns a [`Listener<T>`] that yields items from connecting clients.
528    /// Each client gets a `Sender<T>` bridged to this listener's queue.
529    /// Dropping the [`Listener`] stops accepting new connections.
530    ///
531    /// # Security
532    ///
533    /// The socket at `path` is an external entry point for other local
534    /// processes to join the mesh. On Unix, `path` must reside in a
535    /// directory accessible only to the intended user (e.g. mode `0700`).
536    /// On Windows, the socket's parent directory should be ACL'd to
537    /// restrict access. Any local user who can connect to the socket can
538    /// join the mesh.
539    pub async fn listen<T: 'static + MeshField + Send>(
540        &self,
541        path: &Path,
542    ) -> anyhow::Result<Listener<T>> {
543        let (send, recv) = mesh::channel::<T>();
544        let port_factory: Box<dyn Fn() -> Port + Send> = Box::new(move || send.clone().into());
545
546        let task = self
547            .request
548            .call_failable(
549                MeshRequest::Listen,
550                ListenParams {
551                    path: path.to_owned(),
552                    port_factory,
553                },
554            )
555            .await
556            .context("listen failed")?;
557
558        Ok(Listener { recv, _task: task })
559    }
560}
561
562/// A listener for incoming mesh connections.
563///
564/// Each connecting client gets a `Sender<T>` bridged into this listener's
565/// queue. When the client sends a `T`, it appears in the stream.
566///
567/// Implements [`Stream`]`<Item = T>`. Dropping the listener stops accepting
568/// new connections.
569pub struct Listener<T> {
570    recv: mesh::Receiver<T>,
571    _task: Task<()>,
572}
573
574impl<T: 'static + MeshField + Send> Stream for Listener<T> {
575    type Item = T;
576
577    fn poll_next(
578        mut self: Pin<&mut Self>,
579        cx: &mut std::task::Context<'_>,
580    ) -> std::task::Poll<Option<Self::Item>> {
581        self.recv.poll_next_unpin(cx)
582    }
583}
584
585/// Connect to a mesh listener at `path`.
586///
587/// Returns a [`mesh::Sender<T>`] for sending messages to the listener, and a
588/// [`Connection`] that keeps the underlying IPC node alive. Drop
589/// [`Connection`] to disconnect.
590pub async fn connect<T: 'static + MeshField + Send>(
591    driver: impl pal_async::driver::Driver + Spawn + Clone,
592    path: &Path,
593) -> anyhow::Result<(mesh::Sender<T>, Connection)> {
594    let (send, recv) = mesh::channel::<T>();
595
596    let node = cfg_select! {
597        windows => mesh_remote::windows::AlpcNode::join_by_socket(driver, path, recv.into()).await,
598        unix => mesh_remote::unix::UnixNode::join_by_path(driver, path, recv.into()).await,
599    }
600    .context("failed to connect to mesh listener")?;
601
602    Ok((send, Connection { node }))
603}
604
605/// An active connection to a mesh listener.
606///
607/// Keeps the underlying IPC node alive. Drop to disconnect.
608pub struct Connection {
609    node: IpcNode,
610}
611
612impl Connection {
613    /// Gracefully shut down the connection, waiting for pending messages to be
614    /// delivered.
615    pub async fn shutdown(self) {
616        self.node.shutdown().await;
617    }
618}
619
620#[derive(MeshPayload)]
621struct InitialMessage<T> {
622    requests: mesh::Receiver<HostRequest>,
623    init_message: T,
624}
625
626#[derive(Debug, MeshPayload)]
627enum HostRequest {
628    #[mesh(transparent)]
629    Inspect(inspect::Deferred),
630    Crash,
631}
632
633fn inspect_host(resp: &mut inspect::Response<'_>) {
634    resp.field("tasks", inspect_task::inspect_task_list());
635}
636
637#[derive(Inspect)]
638struct HostInspect<'a> {
639    #[inspect(safe)]
640    name: &'a str,
641    #[inspect(debug, safe)]
642    node_id: mesh::NodeId,
643    #[cfg(target_os = "linux")]
644    #[inspect(safe)]
645    rlimit: inspect_rlimit::InspectRlimit,
646}
647
648impl MeshInner {
649    async fn run(&mut self) {
650        enum Event {
651            Request(MeshRequest),
652            Done(usize),
653        }
654
655        loop {
656            let event = futures::select! { // merge semantics
657                request = self.requests.select_next_some() => Event::Request(request),
658                n = self.waiters.select_next_some() => Event::Done(n),
659                complete => break,
660            };
661
662            match event {
663                Event::Request(request) => match request {
664                    MeshRequest::NewHost(rpc) => {
665                        rpc.handle_failable(async |params| self.spawn_process(params).await)
666                            .await
667                    }
668                    MeshRequest::Listen(rpc) => {
669                        rpc.handle_failable(async |params| self.start_listener(params))
670                            .await
671                    }
672                    MeshRequest::Inspect(deferred) => {
673                        deferred.respond(|resp| {
674                            resp.sensitivity_child("hosts", SensitivityLevel::Safe, |req| {
675                                let mut resp = req.respond();
676                                for host in self.hosts.iter().map(|(_, host)| host) {
677                                    resp.sensitivity_field_mut(
678                                        &host.pid.to_string(),
679                                        SensitivityLevel::Safe,
680                                        &mut inspect::adhoc(|req| {
681                                            req.respond()
682                                                .merge(&HostInspect {
683                                                    name: &host.name,
684                                                    node_id: host.node_id,
685                                                    #[cfg(target_os = "linux")]
686                                                    rlimit: inspect_rlimit::InspectRlimit::for_pid(
687                                                        host.pid,
688                                                    ),
689                                                })
690                                                .merge(inspect::send(
691                                                    &host.send,
692                                                    HostRequest::Inspect,
693                                                ));
694                                        }),
695                                    );
696                                }
697                            })
698                            .sensitivity_field_mut(
699                                &format!("hosts/{}", std::process::id()),
700                                SensitivityLevel::Safe,
701                                &mut inspect::adhoc(|req| {
702                                    let mut resp = req.respond();
703                                    resp.merge(&HostInspect {
704                                        name: &self.mesh_name,
705                                        node_id: self.node.id(),
706                                        #[cfg(target_os = "linux")]
707                                        rlimit: inspect_rlimit::InspectRlimit::new(),
708                                    });
709                                    inspect_host(&mut resp);
710                                }),
711                            );
712                        });
713                    }
714                    MeshRequest::Crash(pid) => {
715                        if pid == std::process::id() as i32 {
716                            panic!("explicit panic request");
717                        }
718
719                        let mut found = false;
720                        for (_, host) in &self.hosts {
721                            if host.pid == pid {
722                                host.send.send(HostRequest::Crash);
723                                found = true;
724                                break;
725                            }
726                        }
727
728                        if !found {
729                            tracing::error!("failed to crash process, pid {pid} not found");
730                        }
731                    }
732                },
733                Event::Done(id) => {
734                    self.hosts.remove(id);
735                }
736            }
737        }
738    }
739
740    fn start_listener(&self, params: ListenParams) -> anyhow::Result<Task<()>> {
741        // Remove a stale socket file if one exists, so that bind doesn't fail.
742        if let Ok(true) = Self::is_socket(&params.path) {
743            let _ = std::fs::remove_file(&params.path);
744        }
745
746        let mut listener = self
747            .node
748            .listen(&self.node_driver, &params.path)
749            .context("failed to bind mesh listener")?;
750
751        let driver = self.node_driver.clone();
752        let port_factory = params.port_factory;
753
754        let task = self.node_driver.spawn("mesh-listener", async move {
755            loop {
756                match listener.accept(&driver).await {
757                    Ok(pending) => {
758                        let port = port_factory();
759                        driver
760                            .spawn("mesh-listener-handshake", async move {
761                                if let Err(e) = pending.finish(port).await {
762                                    tracing::warn!(
763                                        error = &e as &dyn std::error::Error,
764                                        "mesh listener handshake failed",
765                                    );
766                                }
767                            })
768                            .detach();
769                    }
770                    Err(e) => {
771                        tracing::error!(
772                            error = &e as &dyn std::error::Error,
773                            "mesh listener accept failed",
774                        );
775                        break;
776                    }
777                }
778            }
779        });
780
781        Ok(task)
782    }
783
784    /// Checks whether `path` is a socket file.
785    fn is_socket(path: &Path) -> std::io::Result<bool> {
786        cfg_select! {
787            unix => {{
788                use std::os::unix::fs::FileTypeExt;
789                Ok(std::fs::symlink_metadata(path)?.file_type().is_socket())
790            }}
791            windows => pal::windows::fs::is_unix_socket(path),
792        }
793    }
794
795    /// Spawns a new process with a mesh channel associated with this `Mesh` instance.
796    #[instrument(name = "mesh_spawn_process", skip(self, params), fields(mesh_name = self.mesh_name.as_str(), pid = tracing::field::Empty))]
797    async fn spawn_process(&mut self, params: NewHostParams) -> anyhow::Result<i32> {
798        let NewHostParams {
799            config,
800            recv,
801            request_send,
802        } = params;
803
804        let pid;
805        let node_id;
806
807        // If no process name was passed, use the current executable path to
808        // ensure we get the right file, but set arg0 to match how this process
809        // was launched.
810        let (arg0, process_name) = if let Some(n) = &config.process_name {
811            (None, Cow::Borrowed(n))
812        } else {
813            (
814                std::env::args_os().next(),
815                Cow::Owned(std::env::current_exe().context("failed to get current exe path")?),
816            )
817        };
818
819        let name = config.name.clone();
820
821        let child = cfg_select! {
822            windows => {{
823                let (invitation, handle) =
824                    self.node.invite(recv).context("mesh node invite error")?;
825                node_id = invitation.node_id();
826                let (credentials, directory) = invitation.into_parts();
827
828                let invitation_env = base64::engine::general_purpose::STANDARD.encode(
829                    mesh::payload::encode(Invitation {
830                        node_name: name.clone(),
831                        credentials,
832                        directory_handle: directory.as_raw_handle().addr(),
833                    }),
834                );
835
836                let mut args = config.process_args;
837                if !config.skip_worker_arg {
838                    args.push(name.clone().into());
839                }
840
841                let mut builder = process::Builder::from_args(
842                    arg0.as_ref()
843                        .map_or_else(|| process_name.as_os_str(), |x| x.as_os_str()),
844                    &args,
845                );
846                if arg0.is_some() {
847                    builder.application_name(process_name.as_path());
848                }
849                builder
850                    .stdin(process::Stdio::Null)
851                    .stdout(process::Stdio::Null)
852                    .handle(&directory)
853                    .env(INVITATION_ENV_NAME, invitation_env)
854                    .extend_env(config.env_vars)
855                    .job(self.job.as_handle());
856
857                if let Some(log_file) = config.stderr.as_ref() {
858                    builder.stderr(process::Stdio::Handle(log_file.as_handle()));
859                }
860
861                if let Some(profile) = &config.sandbox_profile {
862                    let preparation = sandbox::prepare(
863                        profile,
864                        &sandbox::Identity::default(),
865                        &[sandbox::RawHandle(directory.as_raw_handle().addr() as u64)],
866                    )
867                    .context("failed to prepare sandboxed Mesh process")?;
868                    builder
869                        .configure_sandbox_launch(preparation)
870                        .context("failed to configure sandboxed Mesh process")?;
871                }
872
873                // Launch the child process on a separate thread to isolate
874                // the CreateProcess call from other IO pools.
875                let child = std::thread::scope(|s| s.spawn(|| builder.spawn()).join().unwrap())
876                    .context("failed to launch mesh process")?;
877                // Wait for the child to connect to the mesh. TODO: timeout
878                handle.await;
879                pid = child.id() as i32;
880                tracing::Span::current().record("pid", pid);
881
882                pal_async::windows::PolledProcess::new(&self.node_driver, child)
883                    .expect("failed to create process wait")
884            }}
885            unix => {{
886                use pal::unix::process;
887
888                let invitation = self
889                    .node
890                    .invite(recv)
891                    .await
892                    .context("mesh node invite error")?;
893
894                node_id = invitation.address.local_addr.node;
895
896                let invitation_env = base64::engine::general_purpose::STANDARD.encode(
897                    mesh::payload::encode(Invitation {
898                        node_name: name.clone(),
899                        address: invitation.address,
900                        socket_fd: IPC_FD,
901                    }),
902                );
903
904                let mut command = process::Builder::new(process_name.into_owned());
905                if let Some(arg0) = arg0 {
906                    command.arg0(arg0);
907                }
908                command
909                    .args(&config.process_args)
910                    .stdin(process::Stdio::Null)
911                    .stdout(process::Stdio::Null)
912                    .dup_fd(invitation.fd.as_fd(), IPC_FD)
913                    .env(INVITATION_ENV_NAME, invitation_env);
914
915                for (key, value) in &config.env_vars {
916                    command.env(key, value);
917                }
918
919                if !config.skip_worker_arg {
920                    command.arg(&name);
921                }
922
923                if let Some(log_file) = config.stderr.as_ref() {
924                    command.stderr(process::Stdio::Fd(log_file.as_fd()));
925                }
926
927                if let Some(profile) = &config.sandbox_profile {
928                    let preparation = sandbox::prepare(
929                        profile,
930                        &sandbox::Identity::default(),
931                        &[sandbox::RawHandle(IPC_FD as u64)],
932                    )
933                    .context("failed to prepare sandboxed Mesh process")?;
934                    command
935                        .configure_sandbox_launch(preparation)
936                        .context("failed to configure sandboxed Mesh process")?;
937                }
938
939                // Launch the child process on a separate thread to isolate
940                // the fork() call from other IO pools.
941                let child = std::thread::scope(|s| s.spawn(|| command.spawn()).join().unwrap())
942                    .context("failed to launch mesh process")?;
943                pid = child.id();
944                tracing::Span::current().record("pid", pid);
945
946                pal_async::process::PolledChild::<process::Child>::new(&self.node_driver, child)
947                    .expect("failed to create process wait")
948            }}
949        };
950
951        let id = self.hosts.insert(MeshHostInner {
952            name: config.name,
953            pid,
954            node_id,
955            send: request_send,
956        });
957
958        let task = self
959            .node_driver
960            .spawn(format!("wait-mesh-child-{}", pid), async move {
961                wait_mesh_child(child, &name, pid).await;
962                id
963            });
964
965        self.waiters.push(task);
966        Ok(pid)
967    }
968}
969
970#[cfg(windows)]
971async fn wait_mesh_child(mut child: pal_async::windows::PolledProcess, name: &str, pid: i32) {
972    match child.wait().await {
973        Ok(0) => {
974            tracing::info!(pid, name, "mesh child exited successfully");
975        }
976        Ok(code) => {
977            tracing::error!(pid, name, code, "mesh child abnormal exit");
978        }
979        Err(e) => {
980            tracing::error!(
981                pid,
982                name,
983                error = &e as &dyn std::error::Error,
984                "mesh child wait failed"
985            );
986        }
987    }
988}
989
990#[cfg(unix)]
991async fn wait_mesh_child(
992    mut child: pal_async::process::PolledChild<pal::unix::process::Child>,
993    name: &str,
994    pid: i32,
995) {
996    match child.wait().await {
997        Ok(status) if status.code() == Some(0) => {
998            tracing::info!(pid, name, "mesh child exited successfully");
999        }
1000        Ok(exit_status) => {
1001            tracing::error!(pid, name, %exit_status, "mesh child abnormal exit");
1002        }
1003        Err(e) => {
1004            tracing::error!(
1005                pid,
1006                name,
1007                error = &e as &dyn std::error::Error,
1008                "mesh child wait failed"
1009            );
1010        }
1011    }
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017    use mesh::rpc::Rpc;
1018    use pal_async::DefaultDriver;
1019    use pal_async::async_test;
1020    use pal_async::task::Spawn;
1021    use test_with_tracing::test;
1022
1023    // Test: Connect a client and deliver a message through the public listener stream.
1024    // Expected: The complete payload arrives before the connection shuts down.
1025    #[async_test]
1026    async fn test_listen(driver: DefaultDriver) {
1027        let dir = tempfile::tempdir().unwrap();
1028        let sock_path = dir.path().join("mesh-listen.sock");
1029
1030        let mesh = Mesh::new("test-listen".to_string()).unwrap();
1031        let mut listener = mesh.listen::<String>(&sock_path).await.unwrap();
1032
1033        // Spawn a client task that connects and sends a message.
1034        let client_driver = driver.clone();
1035        let client_path = sock_path.clone();
1036        let client_task = driver.spawn("client", async move {
1037            let (sender, conn) = connect::<String>(client_driver, &client_path)
1038                .await
1039                .unwrap();
1040            sender.send("hello from client".to_string());
1041            // Return the connection to keep the node alive until the server
1042            // has received the message. Shutting down immediately can race
1043            // with the server establishing a back-connection for port
1044            // bridging on Windows (ALPC).
1045            conn
1046        });
1047
1048        // Receive the message via the listener stream.
1049        let msg = listener.next().await.unwrap();
1050        assert_eq!(msg, "hello from client");
1051
1052        client_task.await.shutdown().await;
1053
1054        // Drop the listener and verify the accept loop stops.
1055        drop(listener);
1056
1057        mesh.shutdown().await;
1058    }
1059
1060    const CHILD_TEST: &str = "tests::host_entry_without_invitation_does_not_run_worker";
1061    const VALUE_ENV: &str = "MESH_PROCESS_TEST_VALUE";
1062    const ERROR_ENV: &str = "MESH_PROCESS_TEST_EXPECT_ERROR";
1063    const STDERR_MARKER: &str = "mesh test child diagnostic";
1064
1065    #[derive(MeshPayload)]
1066    struct ChildDetails {
1067        pid: u32,
1068        args: Vec<String>,
1069        value: Option<String>,
1070        invitation_cleared: bool,
1071        #[cfg(target_os = "linux")]
1072        namespace_ids: Vec<String>,
1073    }
1074
1075    #[cfg(target_os = "linux")]
1076    fn namespace_ids() -> Vec<String> {
1077        ["user", "mnt", "ipc", "net"]
1078            .into_iter()
1079            .map(|name| {
1080                std::fs::read_link(format!("/proc/self/ns/{name}"))
1081                    .unwrap()
1082                    .to_str()
1083                    .unwrap()
1084                    .to_owned()
1085            })
1086            .collect()
1087    }
1088
1089    #[derive(MeshPayload)]
1090    enum ChildRequest {
1091        Echo(Rpc<String, String>),
1092        WaitForCrash(mesh::OneshotSender<()>),
1093        RoundTrip(Rpc<(u64, Vec<u8>), (u64, Vec<u8>)>),
1094        Forward(Rpc<(mesh::Sender<ChildRequest>, u64, Vec<u8>), (u64, Vec<u8>)>),
1095        Delayed(Rpc<(mesh::OneshotSender<()>, OneshotReceiver<()>, String), String>),
1096        Stop(mesh::OneshotSender<()>),
1097    }
1098
1099    type ChildInit = (
1100        mesh::OneshotSender<ChildDetails>,
1101        mesh::Receiver<ChildRequest>,
1102    );
1103
1104    struct TestHost {
1105        pid: i32,
1106        details: ChildDetails,
1107        requests: mesh::Sender<ChildRequest>,
1108    }
1109
1110    // Launch only this module's child entry point, not the surrounding test suite.
1111    fn child_config(name: &str) -> ProcessConfig {
1112        ProcessConfig::new(name).args(["--exact", CHILD_TEST, "--nocapture", "--test-threads=1"])
1113    }
1114
1115    // Wait for the worker's handshake so assertions never race process startup.
1116    async fn launch(mesh: &Mesh, config: ProcessConfig) -> TestHost {
1117        let (started, ready) = mesh::oneshot();
1118        let (requests, child_requests) = mesh::channel();
1119        let pid = mesh
1120            .launch_host(config, (started, child_requests))
1121            .await
1122            .unwrap();
1123        TestHost {
1124            pid,
1125            details: ready.await.unwrap(),
1126            requests,
1127        }
1128    }
1129
1130    // Echo through the worker's public mesh channel.
1131    async fn echo(host: &TestHost, value: &str) -> String {
1132        host.requests
1133            .call(ChildRequest::Echo, value.to_owned())
1134            .await
1135            .unwrap()
1136    }
1137
1138    // Test: Run the host entry without an invitation; subprocess callers also use this entry.
1139    // Expected: No worker runs without an invitation, and invited workers exchange real mesh RPCs.
1140    #[test]
1141    fn host_entry_without_invitation_does_not_run_worker() {
1142        let called = std::cell::Cell::new(false);
1143        let result = try_run_mesh_host("unit-mesh", async |(started, mut requests): ChildInit| {
1144            called.set(true);
1145            started.send(ChildDetails {
1146                pid: std::process::id(),
1147                args: std::env::args().skip(1).collect(),
1148                value: std::env::var(VALUE_ENV).ok(),
1149                invitation_cleared: std::env::var_os(INVITATION_ENV_NAME).is_none(),
1150                #[cfg(target_os = "linux")]
1151                namespace_ids: namespace_ids(),
1152            });
1153            eprintln!("{STDERR_MARKER}");
1154            while let Some(request) = requests.next().await {
1155                match request {
1156                    ChildRequest::Echo(request) => request.handle(async |value| value).await,
1157                    ChildRequest::WaitForCrash(ready) => {
1158                        ready.send(());
1159                        std::future::pending::<()>().await;
1160                    }
1161                    ChildRequest::RoundTrip(request) => request.handle_sync(|value| value),
1162                    ChildRequest::Forward(request) => {
1163                        request
1164                            .handle(async |(peer, id, bytes)| {
1165                                peer.call(ChildRequest::RoundTrip, (id, bytes))
1166                                    .await
1167                                    .unwrap()
1168                            })
1169                            .await;
1170                    }
1171                    ChildRequest::Delayed(request) => {
1172                        let ((ready, release, value), response) = request.split();
1173                        ready.send(());
1174                        release.await.unwrap();
1175                        response.complete(value);
1176                    }
1177                    ChildRequest::Stop(ready) => {
1178                        ready.send(());
1179                        break;
1180                    }
1181                }
1182            }
1183            Ok(())
1184        });
1185
1186        if let Ok(expected) = std::env::var(ERROR_ENV) {
1187            let error = result.unwrap_err();
1188            assert!(
1189                error.chain().any(|e| e.to_string() == expected),
1190                "{error:#}"
1191            );
1192            assert!(!called.get());
1193            assert!(std::env::var_os(INVITATION_ENV_NAME).is_none());
1194        } else {
1195            result.unwrap();
1196            assert!(!called.get(), "an uninvited worker must not be called");
1197        }
1198    }
1199
1200    // Test: Provide malformed invitations in isolated child-process environments.
1201    // Expected: Base64 and protobuf errors retain context, clear the secret, and never run a worker.
1202    #[test]
1203    fn malformed_invitations_are_rejected_before_starting_a_worker() {
1204        for (invitation, expected) in [
1205            ("%%%", "failed to base64 decode invitation"),
1206            ("/w==", "failed to protobuf decode invitation"),
1207        ] {
1208            let output = std::process::Command::new(std::env::current_exe().unwrap())
1209                .args(["--exact", CHILD_TEST, "--nocapture", "--test-threads=1"])
1210                .env(INVITATION_ENV_NAME, invitation)
1211                .env(ERROR_ENV, expected)
1212                .output()
1213                .unwrap();
1214            assert!(output.status.success(), "{output:?}");
1215        }
1216    }
1217
1218    // Test: Launch a worker using the current executable, extra environment, and redirected stderr.
1219    // Expected: The reported PID and arguments match the launch; RPCs and clean shutdown succeed.
1220    #[async_test]
1221    async fn launched_worker_receives_configuration_and_exchanges_messages() {
1222        let mesh = Mesh::new("worker-lifecycle".into()).unwrap();
1223        let log = tempfile::NamedTempFile::new().unwrap();
1224        let host = launch(
1225            &mesh,
1226            child_config("configured-worker")
1227                .env([(OsString::from(VALUE_ENV), OsString::from("configured"))])
1228                .stderr(Some(log.reopen().unwrap())),
1229        )
1230        .await;
1231
1232        assert_eq!(host.pid as u32, host.details.pid);
1233        assert_ne!(host.details.pid, std::process::id());
1234        assert_eq!(host.details.value.as_deref(), Some("configured"));
1235        assert!(host.details.invitation_cleared);
1236        assert_eq!(
1237            host.details.args,
1238            [
1239                "--exact",
1240                CHILD_TEST,
1241                "--nocapture",
1242                "--test-threads=1",
1243                "configured-worker",
1244            ]
1245        );
1246        assert_eq!(echo(&host, "first message").await, "first message");
1247        assert_eq!(echo(&host, "second message").await, "second message");
1248        drop(host);
1249        mesh.shutdown().await;
1250        assert!(
1251            std::fs::read_to_string(log.path())
1252                .unwrap()
1253                .contains(STDERR_MARKER)
1254        );
1255    }
1256
1257    // Test: Launch an explicit executable with no appended worker argument.
1258    // Expected: The environment and argument opt-out reach the child.
1259    #[async_test]
1260    async fn explicit_executable_configuration_reaches_the_child() {
1261        let mesh = Mesh::new("explicit-executable".into()).unwrap();
1262        let host = launch(
1263            &mesh,
1264            ProcessConfig::new("explicit-worker")
1265                .process_name(std::env::current_exe().unwrap())
1266                .args(["--exact", CHILD_TEST, "--nocapture", "--test-threads=1"])
1267                .env([(OsString::from(VALUE_ENV), OsString::from("configured"))])
1268                .skip_worker_arg(true),
1269        )
1270        .await;
1271        assert_eq!(host.details.value.as_deref(), Some("configured"));
1272        assert_eq!(
1273            host.details.args,
1274            ["--exact", CHILD_TEST, "--nocapture", "--test-threads=1"]
1275        );
1276        assert_eq!(echo(&host, "explicit echo").await, "explicit echo");
1277        drop(host);
1278        mesh.shutdown().await;
1279    }
1280
1281    #[cfg(target_os = "linux")]
1282    #[async_test]
1283    #[ignore = "requires user namespaces and UID/GID mapping permitted by host policy"]
1284    async fn sandbox_launch_creates_private_namespaces() {
1285        let mesh = Mesh::new("sandbox-lifecycle".into()).unwrap();
1286        let host = launch(
1287            &mesh,
1288            ProcessConfig::new_with_sandbox("sandbox-worker", sandbox::Profile::deny_all().build())
1289                .args(["--exact", CHILD_TEST, "--nocapture", "--test-threads=1"]),
1290        )
1291        .await;
1292        for (parent, child) in namespace_ids().iter().zip(&host.details.namespace_ids) {
1293            assert_ne!(parent, child);
1294        }
1295        assert_eq!(echo(&host, "sandbox echo").await, "sandbox echo");
1296        drop(host);
1297        mesh.shutdown().await;
1298    }
1299
1300    // Test: Fail to launch an executable, then launch a valid worker on the same mesh.
1301    // Expected: The original OS error remains available and a failed launch does not poison the mesh.
1302    #[async_test]
1303    async fn failed_launch_retains_context_and_allows_retry() {
1304        let mesh = Mesh::new("failed-launch".into()).unwrap();
1305        let dir = tempfile::tempdir().unwrap();
1306        let error = mesh
1307            .launch_host(
1308                ProcessConfig::new("missing").process_name(dir.path().join("no-executable")),
1309                (),
1310            )
1311            .await
1312            .unwrap_err();
1313        assert!(
1314            error
1315                .chain()
1316                .any(|e| e.to_string() == "failed to launch mesh process"),
1317            "{error:#}"
1318        );
1319        assert!(error.chain().any(|e| {
1320            e.downcast_ref::<std::io::Error>()
1321                .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound)
1322        }));
1323        let host = launch(&mesh, child_config("retry-worker")).await;
1324        assert_eq!(echo(&host, "retry").await, "retry");
1325        drop(host);
1326        mesh.shutdown().await;
1327    }
1328
1329    // Test: Send a crash request to a live worker while its application channel remains open.
1330    // Expected: The worker panics and closes that channel; the parent can shut down cleanly.
1331    #[async_test]
1332    async fn crash_request_terminates_only_the_target_worker() {
1333        let mesh = Mesh::new("crash-lifecycle".into()).unwrap();
1334        let log = tempfile::NamedTempFile::new().unwrap();
1335        let crashed = launch(
1336            &mesh,
1337            child_config("crash-worker").stderr(Some(log.reopen().unwrap())),
1338        )
1339        .await;
1340        let survivor = launch(&mesh, child_config("surviving-worker")).await;
1341        let (ready, waiting) = mesh::oneshot();
1342        crashed.requests.send(ChildRequest::WaitForCrash(ready));
1343        waiting.await.unwrap();
1344        mesh.crash(crashed.pid);
1345        assert!(
1346            crashed
1347                .requests
1348                .call(ChildRequest::Echo, String::from("after crash"))
1349                .await
1350                .is_err()
1351        );
1352        assert_eq!(echo(&survivor, "still alive").await, "still alive");
1353        mesh.crash(-1);
1354        drop(crashed);
1355        drop(survivor);
1356        mesh.shutdown().await;
1357        assert!(
1358            std::fs::read_to_string(log.path())
1359                .unwrap()
1360                .contains("explicit panic request")
1361        );
1362    }
1363
1364    // Test: Listen on a regular file and connect to a missing endpoint.
1365    // Expected: Both operations report their failure context and the existing file is unchanged.
1366    #[async_test]
1367    async fn invalid_endpoints_report_errors_without_removing_regular_files(driver: DefaultDriver) {
1368        let dir = tempfile::tempdir().unwrap();
1369        let path = dir.path().join("not-a-socket");
1370        std::fs::write(&path, "preserve this file").unwrap();
1371        let mesh = Mesh::new("invalid-endpoints".into()).unwrap();
1372        let error = mesh.listen::<String>(&path).await.err().unwrap();
1373        assert!(
1374            error
1375                .chain()
1376                .any(|e| e.to_string() == "failed to bind mesh listener"),
1377            "{error:#}"
1378        );
1379        assert_eq!(
1380            std::fs::read_to_string(&path).unwrap(),
1381            "preserve this file"
1382        );
1383        let error = connect::<String>(driver, &dir.path().join("missing"))
1384            .await
1385            .err()
1386            .unwrap();
1387        assert!(
1388            error
1389                .chain()
1390                .any(|e| e.to_string() == "failed to connect to mesh listener"),
1391            "{error:#}"
1392        );
1393        mesh.shutdown().await;
1394    }
1395
1396    // Test: Reuse a stale Unix socket for a listener with two independent clients.
1397    // Expected: Binding succeeds, each client's ordering is preserved, and one disconnect is isolated.
1398    #[cfg(unix)]
1399    #[async_test]
1400    async fn stale_socket_is_replaced_and_clients_remain_independent(driver: DefaultDriver) {
1401        let dir = tempfile::tempdir().unwrap();
1402        let path = dir.path().join("stale.sock");
1403        drop(std::os::unix::net::UnixListener::bind(&path).unwrap());
1404        let mesh = Mesh::new("stale-socket".into()).unwrap();
1405        let mut listener = mesh.listen::<String>(&path).await.unwrap();
1406        let (a, connection_a) = connect::<String>(driver.clone(), &path).await.unwrap();
1407        let (b, connection_b) = connect::<String>(driver, &path).await.unwrap();
1408        for i in 0..2 {
1409            a.send(format!("a{i}"));
1410            b.send(format!("b{i}"));
1411        }
1412        let mut messages = Vec::new();
1413        for _ in 0..4 {
1414            messages.push(listener.next().await.unwrap());
1415        }
1416        for prefix in ['a', 'b'] {
1417            assert_eq!(
1418                messages
1419                    .iter()
1420                    .filter(|s| s.starts_with(prefix))
1421                    .cloned()
1422                    .collect::<Vec<_>>(),
1423                [format!("{prefix}0"), format!("{prefix}1")]
1424            );
1425        }
1426        drop(a);
1427        connection_a.shutdown().await;
1428        b.send("b2".to_owned());
1429        assert_eq!(listener.next().await.as_deref(), Some("b2"));
1430        drop(b);
1431        connection_b.shutdown().await;
1432        drop(listener);
1433        mesh.shutdown().await;
1434    }
1435
1436    // Test: Gracefully shut down a connected client immediately after queuing messages.
1437    // Expected: Every queued message reaches the listener in order while shutdown
1438    //       and reception complete without keeping the sender alive.
1439    #[async_test]
1440    async fn graceful_client_shutdown_delivers_queued_messages(driver: DefaultDriver) {
1441        let dir = tempfile::tempdir().unwrap();
1442        let path = dir.path().join("drain.sock");
1443        let mesh = Mesh::new("drain-client".into()).unwrap();
1444        let mut listener = mesh.listen::<u32>(&path).await.unwrap();
1445        let (sender, connection) = connect::<u32>(driver, &path).await.unwrap();
1446
1447        // Establish the server's return bridge before shutdown, including on ALPC.
1448        sender.send(0);
1449        assert_eq!(listener.next().await, Some(0));
1450        for value in 1..=16 {
1451            sender.send(value);
1452        }
1453        drop(sender);
1454        let (_, received) = futures::join!(connection.shutdown(), async {
1455            let mut received = Vec::new();
1456            for _ in 1..=16 {
1457                received.push(listener.next().await.unwrap());
1458            }
1459            received
1460        });
1461        assert_eq!(received, (1..=16).collect::<Vec<_>>());
1462        drop(listener);
1463        mesh.shutdown().await;
1464    }
1465
1466    // Test: Transfer a peer's request sender into another worker and queue two
1467    //       correlated, multi-page byte payloads before dropping local ownership.
1468    // Expected: Both replies preserve every byte and their request IDs after the
1469    //       parent's buffers are overwritten and its peer handle is dropped.
1470    #[async_test]
1471    async fn delegated_peer_channel_preserves_owned_payloads_and_correlation() {
1472        let mesh = Mesh::new("delegated-peer".into()).unwrap();
1473        let relay = launch(&mesh, child_config("relay")).await;
1474        let peer = launch(&mesh, child_config("peer")).await;
1475        let mut first: Vec<u8> = (0..8193).map(|i| (i * 37 + 11) as u8).collect();
1476        let mut second: Vec<u8> = (0..4097).map(|i| (i * 19 + 7) as u8).collect();
1477        let first_reply = relay.requests.call(
1478            ChildRequest::Forward,
1479            (peer.requests.clone(), 0x1_0000_0001, first.clone()),
1480        );
1481        let second_reply = relay.requests.call(
1482            ChildRequest::Forward,
1483            (peer.requests.clone(), 0xffff_ffff_0000_0002, second.clone()),
1484        );
1485        first.fill(0);
1486        second.fill(0);
1487        drop(peer);
1488        let (first_reply, second_reply) = futures::join!(first_reply, second_reply);
1489        assert_eq!(
1490            first_reply.unwrap(),
1491            (
1492                0x1_0000_0001,
1493                (0..8193).map(|i| (i * 37 + 11) as u8).collect::<Vec<_>>(),
1494            )
1495        );
1496        assert_eq!(
1497            second_reply.unwrap(),
1498            (
1499                0xffff_ffff_0000_0002,
1500                (0..4097).map(|i| (i * 19 + 7) as u8).collect::<Vec<_>>(),
1501            )
1502        );
1503        assert_eq!(
1504            echo(&relay, "relay remains usable").await,
1505            "relay remains usable"
1506        );
1507        drop(relay);
1508        mesh.shutdown().await;
1509    }
1510
1511    // Test: Drop the reply receiver after a worker accepts a delayed request,
1512    //       then release that request and send another RPC on the same channel.
1513    // Expected: Completing an abandoned response does not poison the worker or
1514    //       another peer; subsequent replies retain their own payloads.
1515    #[async_test]
1516    async fn canceled_rpc_reply_does_not_block_worker_or_peer_progress() {
1517        let mesh = Mesh::new("canceled-reply".into()).unwrap();
1518        let worker = launch(&mesh, child_config("delayed-worker")).await;
1519        let peer = launch(&mesh, child_config("independent-peer")).await;
1520        let (accepted, ready) = mesh::oneshot();
1521        let (release, released) = mesh::oneshot();
1522        let abandoned = worker.requests.call(
1523            ChildRequest::Delayed,
1524            (accepted, released, "abandoned response".to_owned()),
1525        );
1526        ready.await.unwrap();
1527        drop(abandoned);
1528        assert_eq!(echo(&peer, "peer progresses").await, "peer progresses");
1529        release.send(());
1530        assert_eq!(
1531            echo(&worker, "after cancellation").await,
1532            "after cancellation"
1533        );
1534        drop(worker);
1535        drop(peer);
1536        mesh.shutdown().await;
1537    }
1538
1539    // Test: Let a worker finish its application while the parent retains its
1540    //       request sender, then use a survivor and launch a replacement.
1541    // Expected: The exited worker's RPCs fail, while the other worker and a new
1542    //       worker continue exchanging messages and the mesh shuts down cleanly.
1543    #[async_test]
1544    async fn worker_exit_closes_only_its_channel_and_allows_replacement() {
1545        let mesh = Mesh::new("worker-exit".into()).unwrap();
1546        let exiting = launch(&mesh, child_config("exiting-worker")).await;
1547        let survivor = launch(&mesh, child_config("survivor")).await;
1548        let (stop, stopped) = mesh::oneshot();
1549        exiting.requests.send(ChildRequest::Stop(stop));
1550        stopped.await.unwrap();
1551        assert!(
1552            exiting
1553                .requests
1554                .call(ChildRequest::Echo, "after exit".to_owned())
1555                .await
1556                .is_err()
1557        );
1558        assert_eq!(echo(&survivor, "survivor reply").await, "survivor reply");
1559        let replacement = launch(&mesh, child_config("replacement")).await;
1560        assert_eq!(
1561            echo(&replacement, "replacement reply").await,
1562            "replacement reply"
1563        );
1564        drop(exiting);
1565        drop(survivor);
1566        drop(replacement);
1567        mesh.shutdown().await;
1568    }
1569}