Skip to main content

litert_lm/
process.rs

1use anyhow::{Context, Result};
2use std::path::PathBuf;
3use std::process::Stdio;
4use std::sync::Arc;
5use tokio::io::AsyncWriteExt;
6use tokio::process::Command;
7use tokio::sync::mpsc;
8use tokio_stream::wrappers::ReceiverStream;
9use tokio_stream::Stream;
10
11// Command sent to the process's internal loop
12enum ProcessCommand {
13    Run {
14        prompt: String,
15        // Send tokens back on this channel
16        response_tx: mpsc::Sender<Result<String>>,
17    },
18}
19
20pub struct LitProcess {
21    // Kept to send commands *to* the process
22    command_tx: mpsc::Sender<ProcessCommand>,
23    // Kept for cleanup/shutdown, but not directly accessed in normal flow
24    #[allow(dead_code)]
25    child_handle: tokio::task::JoinHandle<()>,
26}
27
28impl std::fmt::Debug for LitProcess {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("LitProcess")
31            .field("command_tx", &"<mpsc::Sender>")
32            .field("child_handle", &"<JoinHandle>")
33            .finish()
34    }
35}
36
37impl LitProcess {
38    pub async fn spawn(binary_path: PathBuf, model: String) -> Result<Self> {
39        // Try GPU first, fall back to CPU if it fails
40        match Self::spawn_with_backend(binary_path.clone(), model.clone(), "gpu").await {
41            Ok(process) => Ok(process),
42            Err(e) => {
43                tracing::warn!("GPU backend failed: {}. Trying CPU backend...", e);
44                Self::spawn_with_backend(binary_path, model, "cpu").await
45            }
46        }
47    }
48
49    async fn spawn_with_backend(binary_path: PathBuf, model: String, backend: &str) -> Result<Self> {
50        tracing::info!("Attempting to spawn lit process with backend={}", backend);
51
52        let mut child = Command::new(&binary_path)
53            .arg("run")
54            .arg(&model)
55            .arg("--backend")
56            .arg(backend)
57            .stdin(Stdio::piped())
58            .stdout(Stdio::piped())
59            .stderr(Stdio::piped())
60            .spawn()
61            .with_context(|| format!("Failed to spawn lit process with backend={}", backend))?;
62
63        let mut stdin = child.stdin.take().context("Failed to get stdin")?;
64        let stdout = child.stdout.take().context("Failed to get stdout")?;
65        let mut stderr = child.stderr.take().context("Failed to get stderr")?;
66
67        let (command_tx, mut command_rx) = mpsc::channel::<ProcessCommand>(32);
68
69        // Spawn a task to log stderr
70        tokio::spawn(async move {
71            use tokio::io::AsyncReadExt;
72            let mut buf = [0u8; 1024];
73            while let Ok(n) = stderr.read(&mut buf).await {
74                if n == 0 {
75                    break;
76                }
77                let msg = String::from_utf8_lossy(&buf[..n]);
78                tracing::debug!("lit stderr: {}", msg.trim());
79            }
80        });
81
82        // Spawn the long-running task that owns the process
83        let child_handle = tokio::spawn(async move {
84            use tokio::io::AsyncReadExt;
85
86            let mut stdout = stdout;
87            let mut buffer = Vec::new();
88            let mut temp_buf = [0u8; 1024];
89            let mut pending_commands = Vec::new();
90
91            // Wait for model to load - look for the prompt marker ">>>"
92            tracing::info!("Waiting for model to load...");
93            let init_timeout = tokio::time::Duration::from_secs(120); // 2 minute timeout
94            let init_result = tokio::time::timeout(init_timeout, async {
95                loop {
96                    tokio::select! {
97                        // Check for incoming commands while initializing - buffer them
98                        cmd = command_rx.recv() => {
99                            if let Some(cmd) = cmd {
100                                tracing::debug!("Buffering command during initialization");
101                                pending_commands.push(cmd);
102                            }
103                        }
104                        // Read from stdout
105                        result = stdout.read(&mut temp_buf) => {
106                            match result {
107                                Ok(0) => {
108                                    tracing::error!("Process stdout closed before model loaded");
109                                    return Err(anyhow::anyhow!("Process died during initialization"));
110                                }
111                                Ok(n) => {
112                                    buffer.extend_from_slice(&temp_buf[..n]);
113                                    let text = String::from_utf8_lossy(&buffer);
114
115                                    // Check for error messages
116                                    if text.contains("Error") || text.contains("error") || text.contains("failed") {
117                                        tracing::error!("Initialization error: {}", text);
118                                        return Err(anyhow::anyhow!("Process initialization failed: {}", text.trim()));
119                                    }
120
121                                    // Check if model is loaded
122                                    if text.contains("Model '") && text.contains("' loaded.") {
123                                        tracing::info!("Model loaded successfully");
124                                    }
125
126                                    // Wait for the initial prompt marker
127                                    if text.contains(">>>") {
128                                        tracing::info!("Process ready to accept prompts");
129                                        buffer.clear();
130                                        return Ok(());
131                                    }
132                                }
133                                Err(e) => {
134                                    tracing::error!("Error reading process output during init: {}", e);
135                                    return Err(e.into());
136                                }
137                            }
138                        }
139                    }
140                }
141            }).await;
142
143            match init_result {
144                Ok(Ok(())) => {
145                    tracing::info!("Model initialization complete, processing {} buffered commands", pending_commands.len());
146                }
147                Ok(Err(e)) => {
148                    tracing::error!("Initialization failed: {}", e);
149                    // Drain buffered commands with error
150                    for cmd in pending_commands {
151                        let ProcessCommand::Run { response_tx, .. } = cmd;
152                        let _ = response_tx.send(Err(anyhow::anyhow!("Process initialization failed: {}", e))).await;
153                    }
154                    let _ = child.kill().await;
155                    return;
156                }
157                Err(_) => {
158                    tracing::error!("Initialization timed out after 2 minutes");
159                    for cmd in pending_commands {
160                        let ProcessCommand::Run { response_tx, .. } = cmd;
161                        let _ = response_tx.send(Err(anyhow::anyhow!("Process initialization timed out"))).await;
162                    }
163                    let _ = child.kill().await;
164                    return;
165                }
166            }
167
168            // Process any buffered commands first
169            for cmd in pending_commands {
170                Self::handle_command(cmd, &mut stdin, &mut stdout, &mut buffer, &mut temp_buf).await;
171            }
172
173            // Now handle commands
174            while let Some(cmd) = command_rx.recv().await {
175                Self::handle_command(cmd, &mut stdin, &mut stdout, &mut buffer, &mut temp_buf).await;
176            }
177
178            // Cleanup: kill child process when command loop exits
179            let _ = child.kill().await;
180        });
181
182        Ok(Self {
183            command_tx,
184            child_handle,
185        })
186    }
187
188    async fn handle_command(
189        cmd: ProcessCommand,
190        stdin: &mut tokio::process::ChildStdin,
191        stdout: &mut tokio::process::ChildStdout,
192        buffer: &mut Vec<u8>,
193        temp_buf: &mut [u8; 1024],
194    ) {
195        use tokio::io::AsyncReadExt;
196
197        match cmd {
198            ProcessCommand::Run { prompt, response_tx } => {
199                tracing::trace!("Writing prompt to process stdin");
200                // 1. Write prompt to the process's stdin
201                if let Err(e) = stdin.write_all(prompt.as_bytes()).await {
202                    tracing::error!(error = %e, "Failed to write prompt to stdin");
203                    let _ = response_tx.send(Err(e.into())).await;
204                    return;
205                }
206                if let Err(e) = stdin.write_all(b"\n").await {
207                    tracing::error!(error = %e, "Failed to write newline to stdin");
208                    let _ = response_tx.send(Err(e.into())).await;
209                    return;
210                }
211                if let Err(e) = stdin.flush().await {
212                    tracing::error!(error = %e, "Failed to flush stdin");
213                    let _ = response_tx.send(Err(e.into())).await;
214                    return;
215                }
216
217                // 2. Read character-by-character and stream tokens
218                buffer.clear();
219                let mut last_chunk = String::new();
220
221                tracing::trace!("Reading response from process stdout");
222                loop {
223                    match stdout.read(temp_buf).await {
224                        Ok(0) => {
225                            // EOF - process died
226                            tracing::error!("Process stdout closed unexpectedly");
227                            let _ = response_tx.send(Err(anyhow::anyhow!("Process stdout closed"))).await;
228                            break;
229                        }
230                        Ok(n) => {
231                            buffer.extend_from_slice(&temp_buf[..n]);
232                            let text = String::from_utf8_lossy(buffer).to_string();
233
234                            // Check if we've reached the end marker ">>>"
235                            if text.ends_with(">>>") || text.contains("\n>>>") {
236                                tracing::trace!("Received end marker, finalizing response");
237                                // Send the final chunk (without the >>>)
238                                let final_text = text.trim_end_matches(">>>").trim_end_matches('\n');
239                                if final_text.len() > last_chunk.len() {
240                                    let new_content = &final_text[last_chunk.len()..];
241                                    if !new_content.is_empty() {
242                                        if response_tx.send(Ok(new_content.to_string())).await.is_err() {
243                                            tracing::debug!("Response channel closed by receiver");
244                                            break;
245                                        }
246                                    }
247                                }
248                                buffer.clear();
249                                break;
250                            }
251
252                            // Send incremental updates
253                            if text.len() > last_chunk.len() {
254                                let new_content = &text[last_chunk.len()..];
255                                if response_tx.send(Ok(new_content.to_string())).await.is_err() {
256                                    // Client disconnected
257                                    buffer.clear();
258                                    break;
259                                }
260                                last_chunk = text;
261                            }
262                        }
263                        Err(e) => {
264                            tracing::error!(error = %e, "Error reading from process stdout");
265                            let _ = response_tx.send(Err(e.into())).await;
266                            break;
267                        }
268                    }
269                }
270                // When done, `response_tx` is dropped, closing the stream
271            }
272        }
273    }
274
275    // New streaming method
276    pub async fn send_prompt_stream(
277        &self,
278        prompt: &str,
279    ) -> Result<impl Stream<Item = Result<String>>> {
280        tracing::debug!(prompt_length = prompt.len(), "Creating prompt stream");
281
282        // 1. Create a new, unique channel for *this* request's response
283        let (response_tx, response_rx) = mpsc::channel(100); // Token buffer
284
285        // 2. Create the command
286        let cmd = ProcessCommand::Run {
287            prompt: prompt.to_string(),
288            response_tx,
289        };
290
291        // 3. Send the command to the process loop
292        self.command_tx.send(cmd).await.map_err(|e| {
293            // Process loop died
294            tracing::error!(error = %e, "Process command channel closed");
295            anyhow::anyhow!("Failed to send command to process: {}", e)
296        })?;
297
298        tracing::debug!("Command sent to process, returning stream");
299        // 4. Return the receiver wrapped in a stream
300        Ok(ReceiverStream::new(response_rx))
301    }
302
303    // Keep the old non-streaming method for backward compatibility
304    pub async fn send_prompt(&self, prompt: &str) -> Result<String> {
305        use futures::StreamExt;
306
307        let mut stream = self.send_prompt_stream(prompt).await?;
308        let mut response = String::new();
309
310        while let Some(result) = stream.next().await {
311            let line = result?;
312            response.push_str(&line);
313            response.push('\n');
314        }
315
316        Ok(response)
317    }
318
319    #[allow(dead_code)]
320    pub async fn shutdown(self) -> Result<()> {
321        // Drop command_tx to signal shutdown
322        drop(self.command_tx);
323        // Wait for child task to finish
324        self.child_handle.await?;
325        Ok(())
326    }
327}
328
329/// Manages a pool of isolated LitProcess instances
330#[derive(Debug)]
331pub struct ProcessPool {
332    binary_path: PathBuf,
333    model: String,
334    processes: Vec<Arc<LitProcess>>,
335}
336
337impl ProcessPool {
338    pub fn new(binary_path: PathBuf, model: String, pool_size: usize) -> Self {
339        Self {
340            binary_path,
341            model,
342            processes: Vec::with_capacity(pool_size),
343        }
344    }
345
346    pub async fn initialize(&mut self) -> Result<()> {
347        let pool_size = self.processes.capacity();
348        tracing::info!(
349            pool_size = pool_size,
350            model = %self.model,
351            "Initializing process pool"
352        );
353
354        for i in 0..pool_size {
355            tracing::debug!(process_index = i, "Spawning process");
356            let process = LitProcess::spawn(self.binary_path.clone(), self.model.clone()).await?;
357            self.processes.push(Arc::new(process));
358            tracing::debug!(process_index = i, "Process spawned successfully");
359        }
360
361        tracing::info!(pool_size = pool_size, "Process pool initialized successfully");
362        Ok(())
363    }
364
365    pub async fn get_process(&self) -> Result<Arc<LitProcess>> {
366        // Simple round-robin selection
367        // In a real implementation, you might want to track which processes are busy
368        use std::sync::atomic::{AtomicUsize, Ordering};
369        static COUNTER: AtomicUsize = AtomicUsize::new(0);
370
371        if self.processes.is_empty() {
372            tracing::error!("Process pool is empty or not initialized");
373            anyhow::bail!("Process pool not initialized")
374        }
375
376        let idx = COUNTER.fetch_add(1, Ordering::Relaxed) % self.processes.len();
377        tracing::trace!(
378            process_index = idx,
379            pool_size = self.processes.len(),
380            "Selected process from pool"
381        );
382        Ok(self.processes[idx].clone())
383    }
384
385    pub async fn send_prompt(&self, prompt: &str) -> Result<String> {
386        let process = self.get_process().await?;
387        process.send_prompt(prompt).await
388    }
389}