Skip to main content

dynamo_memory/nixl/
agent.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! NIXL agent wrapper and configuration.
5//!
6//! This module provides:
7//! - `NixlAgent`: Wrapper around nixl_sys::Agent that tracks initialized backends
8//! - `NixlBackendConfig`: Configuration for NIXL backends from environment variables
9
10use anyhow::Result;
11use nixl_sys::{Agent, AgentConfig, NixlError, is_stub};
12use std::collections::{HashMap, HashSet};
13
14use crate::nixl::NixlBackendConfig;
15
16/// A NIXL agent wrapper that tracks which backends were successfully initialized.
17///
18/// This wrapper provides:
19/// - Runtime validation of backend availability
20/// - Clear error messages when operations need unavailable backends
21/// - Single source of truth for backend state in tests and production
22///
23/// # Backend Tracking
24///
25/// Since `nixl_sys::Agent` doesn't provide a method to query active backends,
26/// we track them during initialization. The `available_backends` set is populated
27/// based on successful `create_backend()` calls.
28#[derive(Clone, Debug)]
29pub struct NixlAgent {
30    agent: Agent,
31    available_backends: HashSet<String>,
32}
33
34impl NixlAgent {
35    /// Create a NIXL agent without any backends.
36    pub fn new(name: &str) -> Result<Self> {
37        Self::create(|| Agent::new(name))
38    }
39
40    /// Create a NIXL agent without any backends, using the given agent configuration.
41    pub fn new_with_config(name: &str, config: &AgentConfig) -> Result<Self> {
42        Self::create(|| Agent::new_configured(name, config))
43    }
44
45    // Check for stub mode before the first NIXL call: a stub build without the NIXL
46    // library aborts the process on that call.
47    fn create(new_agent: impl FnOnce() -> Result<Agent, NixlError>) -> Result<Self> {
48        if is_stub() {
49            return Err(anyhow::anyhow!("NIXL is not supported in stub mode"));
50        }
51        Ok(Self {
52            agent: new_agent()?,
53            available_backends: HashSet::new(),
54        })
55    }
56
57    /// Creates a new agent configured with backends from the given config.
58    ///
59    /// This method iterates over all backends in the config and initializes them
60    /// with their associated parameters. If a backend has custom parameters defined
61    /// in the config, those are used; otherwise, default plugin parameters are used.
62    pub fn from_nixl_backend_config(name: &str, config: NixlBackendConfig) -> Result<Self> {
63        let mut agent = Self::new(name)?;
64        for (backend, params) in config.iter() {
65            agent.add_backend_with_params(backend, params)?;
66        }
67        Ok(agent)
68    }
69
70    /// Add a backend to the agent with default parameters.
71    pub fn add_backend(&mut self, backend: &str) -> Result<()> {
72        self.add_backend_with_params(backend, &HashMap::new())
73    }
74
75    /// Add a backend to the agent with optional custom parameters.
76    ///
77    /// If `custom_params` is non-empty, those parameters are used instead of
78    /// the plugin defaults. If empty, default parameters from the plugin are used.
79    ///
80    /// # Errors
81    /// Returns an error if custom parameters are provided (not yet supported until nixl_sys 0.9).
82    pub fn add_backend_with_params(
83        &mut self,
84        backend: &str,
85        custom_params: &HashMap<String, String>,
86    ) -> Result<()> {
87        let backend_upper = backend.to_uppercase();
88        if self.available_backends.contains(&backend_upper) {
89            return Ok(());
90        }
91
92        // TODO(DIS-1310): Custom params require nixl_sys 0.9+ which adds nixl_capi_params_add
93        if !custom_params.is_empty() {
94            anyhow::bail!(
95                "Custom NIXL backend parameters for {} are not yet supported. \
96                 This feature requires nixl_sys 0.9+. Params provided: {:?}",
97                backend_upper,
98                custom_params.keys().collect::<Vec<_>>()
99            );
100        }
101
102        // Get default params from plugin
103        let (_, params) = match self.agent.get_plugin_params(&backend_upper) {
104            Ok(result) => result,
105            Err(_) => anyhow::bail!("No {} plugin found", backend_upper),
106        };
107
108        match self.agent.create_backend(&backend_upper, &params) {
109            Ok(_) => {
110                self.available_backends.insert(backend_upper);
111                Ok(())
112            }
113            Err(e) => anyhow::bail!("Failed to create nixl backend: {}", e),
114        }
115    }
116
117    /// Create a NIXL agent requiring ALL specified backends to be available.
118    ///
119    /// Unlike `new_with_backends()` which continues if some backends fail, this method
120    /// will return an error if ANY backend fails to initialize. Use this in production
121    /// when specific backends are mandatory.
122    ///
123    /// # Arguments
124    /// * `name` - Agent name
125    /// * `backends` - List of backend names that MUST be available
126    ///
127    /// # Returns
128    /// A `NixlAgent` with all requested backends initialized.
129    ///
130    /// # Errors
131    /// Returns an error if:
132    /// - Agent creation fails
133    /// - Any backend fails to initialize
134    pub fn with_backends(name: &str, backends: &[&str]) -> Result<Self> {
135        let mut agent = Self::new(name)?;
136        let mut failed_backends = Vec::new();
137
138        for backend in backends {
139            let backend_upper = backend.to_uppercase();
140            match agent.add_backend(&backend_upper) {
141                Ok(_) => {
142                    tracing::debug!("Initialized NIXL backend: {}", backend_upper);
143                }
144                Err(e) => {
145                    tracing::error!("Failed to initialize {} backend: {}", backend_upper, e);
146                    failed_backends.push((backend_upper, e.to_string()));
147                }
148            }
149        }
150
151        if !failed_backends.is_empty() {
152            let error_details: Vec<String> = failed_backends
153                .iter()
154                .map(|(name, reason)| format!("{}: {}", name, reason))
155                .collect();
156
157            anyhow::bail!(
158                "Failed to initialize required backends: [{}]",
159                error_details.join(", ")
160            );
161        }
162
163        Ok(agent)
164    }
165
166    /// Get a reference to the underlying raw NIXL agent.
167    pub fn raw_agent(&self) -> &Agent {
168        &self.agent
169    }
170
171    /// Consume and return the underlying raw NIXL agent.
172    ///
173    /// **Warning**: Once consumed, backend tracking is lost. Use this only when
174    /// interfacing with code that requires `nixl_sys::Agent` directly.
175    pub fn into_raw_agent(self) -> Agent {
176        self.agent
177    }
178
179    /// Check if a specific backend is available.
180    pub fn has_backend(&self, backend: &str) -> bool {
181        self.available_backends.contains(&backend.to_uppercase())
182    }
183
184    /// Get all available backends.
185    pub fn backends(&self) -> &HashSet<String> {
186        &self.available_backends
187    }
188
189    /// Require a specific backend, returning an error if unavailable.
190    ///
191    /// Use this at the start of operations that need specific backends.
192    ///
193    /// Note: In general, you want to instantiate all your backends before you start registering memory.
194    /// We may change this to a builder pattern in the future to enforce all backends are instantiated
195    /// before you start registering memory.
196    pub fn require_backend(&self, backend: &str) -> Result<()> {
197        let backend_upper = backend.to_uppercase();
198        if self.has_backend(&backend_upper) {
199            Ok(())
200        } else {
201            anyhow::bail!(
202                "Operation requires {} backend, but it was not initialized. Available backends: {:?}",
203                backend_upper,
204                self.available_backends
205            )
206        }
207    }
208}
209
210// Delegate common methods to the underlying agent
211impl std::ops::Deref for NixlAgent {
212    type Target = Agent;
213
214    fn deref(&self) -> &Self::Target {
215        &self.agent
216    }
217}
218
219#[cfg(all(test, feature = "testing-nixl"))]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn test_agent_backend_tracking() {
225        // Try to create agent with UCX
226        let agent = NixlAgent::with_backends("test", &["UCX"]).expect("Need UCX for test");
227
228        // Should succeed if UCX is available
229        assert!(agent.has_backend("UCX"));
230        assert!(agent.has_backend("ucx")); // Case insensitive
231    }
232
233    #[test]
234    fn test_require_backend() {
235        let agent = NixlAgent::with_backends("test", &["UCX"]).expect("Need UCX for test");
236
237        // Should succeed for available backend
238        assert!(agent.require_backend("UCX").is_ok());
239
240        // Should fail for unavailable backend
241        assert!(agent.require_backend("GDS_MT").is_err());
242    }
243
244    #[test]
245    fn test_require_backends_strict() {
246        // Should succeed if UCX is available
247        let agent =
248            NixlAgent::with_backends("test_strict", &["UCX"]).expect("Failed to require backends");
249        assert!(agent.has_backend("UCX"));
250
251        // Should fail if any backend is missing (GDS likely not available)
252        let result = NixlAgent::with_backends("test_strict_fail", &["UCX", "DUDE"]);
253        assert!(result.is_err());
254    }
255
256    #[test]
257    fn test_new_with_config() {
258        let config = AgentConfig {
259            pthr_delay_us: 1_000,
260            ..AgentConfig::default()
261        };
262        let mut agent = NixlAgent::new_with_config("test_new_with_config", &config)
263            .expect("Failed to create agent");
264        agent.add_backend("UCX").expect("Need UCX for test");
265        assert!(agent.has_backend("UCX"));
266    }
267
268    #[test]
269    fn test_add_backend_with_empty_params() {
270        let mut agent = NixlAgent::new("test_empty_params").expect("Failed to create agent");
271
272        // Empty params should work (uses plugin defaults)
273        let result = agent.add_backend_with_params("UCX", &HashMap::new());
274        assert!(result.is_ok());
275        assert!(agent.has_backend("UCX"));
276    }
277
278    #[test]
279    fn test_add_backend_with_custom_params_fails() {
280        let mut agent = NixlAgent::new("test_custom_params").expect("Failed to create agent");
281
282        // Custom params should fail until nixl_sys 0.9
283        let mut params = HashMap::new();
284        params.insert("some_key".to_string(), "some_value".to_string());
285
286        let result = agent.add_backend_with_params("UCX", &params);
287        assert!(result.is_err());
288
289        let err_msg = result.unwrap_err().to_string();
290        assert!(err_msg.contains("not yet supported"));
291        assert!(err_msg.contains("nixl_sys 0.9"));
292        assert!(err_msg.contains("some_key"));
293    }
294
295    #[test]
296    fn test_from_nixl_backend_config_with_custom_params_fails() {
297        // Config with custom params should fail
298        let mut params = HashMap::new();
299        params.insert("threads".to_string(), "4".to_string());
300
301        let config = NixlBackendConfig::default().with_backend_params("UCX", params);
302
303        let result = NixlAgent::from_nixl_backend_config("test_config_params", config);
304        assert!(result.is_err());
305
306        let err_msg = result.unwrap_err().to_string();
307        assert!(err_msg.contains("not yet supported"));
308        assert!(err_msg.contains("threads"));
309    }
310
311    #[test]
312    fn test_from_nixl_backend_config_with_empty_params() {
313        // Config with empty params should work
314        let config = NixlBackendConfig::default().with_backend("UCX");
315
316        let result = NixlAgent::from_nixl_backend_config("test_config_empty", config);
317        assert!(result.is_ok());
318
319        let agent = result.unwrap();
320        assert!(agent.has_backend("UCX"));
321    }
322}