Skip to main content

adk_code/
rust_executor.rs

1//! Rust-specific executor with a check → build → execute pipeline.
2//!
3//! [`RustExecutor`] compiles Rust code through a two-step pipeline (check + build)
4//! and delegates execution to a configured [`SandboxBackend`] from `adk-sandbox`.
5//! It wraps user code in the same harness template as the legacy
6//! [`RustSandboxExecutor`](crate::RustSandboxExecutor).
7//!
8//! # Pipeline
9//!
10//! 1. **Check**: `rustc --edition 2021 --error-format=json` → parse diagnostics → halt on errors
11//! 2. **Build**: `rustc --edition 2021 -o binary` → compile to binary using harness template
12//! 3. **Execute**: delegate to [`SandboxBackend`] with [`Language::Command`] and the binary path
13//!
14//! See [`RustExecutor`] for where each step runs and what environment it sees.
15//!
16//! # Example
17//!
18//! ```rust,ignore
19//! use adk_code::{RustExecutor, RustExecutorConfig};
20//! use adk_sandbox::{ProcessBackend, SandboxBackend};
21//! use std::sync::Arc;
22//!
23//! let backend: Arc<dyn SandboxBackend> = Arc::new(ProcessBackend::default());
24//! let executor = RustExecutor::new(backend, RustExecutorConfig::default());
25//! ```
26
27use std::collections::HashMap;
28use std::ffi::OsString;
29use std::path::{Path, PathBuf};
30use std::process::Stdio;
31use std::sync::Arc;
32use std::time::Duration;
33
34use adk_sandbox::{
35    ExecRequest, ExecResult, Language, ProcessBackend, SandboxBackend, SandboxError,
36};
37use tracing::{debug, info, instrument};
38
39use crate::diagnostics::{RustDiagnostic, parse_diagnostics};
40use crate::error::CodeError;
41use crate::harness::{HARNESS_TEMPLATE, extract_structured_output, validate_rust_source};
42use crate::host_process;
43
44/// Configuration for the [`RustExecutor`] pipeline.
45///
46/// # Example
47///
48/// ```rust
49/// use adk_code::RustExecutorConfig;
50///
51/// let config = RustExecutorConfig::default();
52/// assert_eq!(config.rustc_path, "rustc");
53/// ```
54#[derive(Debug, Clone)]
55pub struct RustExecutorConfig {
56    /// Path to the `rustc` compiler binary.
57    pub rustc_path: String,
58    /// Explicit path to the `serde_json` rlib. If `None`, the executor
59    /// attempts automatic discovery via `cargo metadata`.
60    pub serde_json_path: Option<PathBuf>,
61    /// Extra flags passed to `rustc` during compilation.
62    pub rustc_flags: Vec<String>,
63}
64
65impl Default for RustExecutorConfig {
66    fn default() -> Self {
67        Self { rustc_path: "rustc".to_string(), serde_json_path: None, rustc_flags: vec![] }
68    }
69}
70
71/// Output of one `rustc` invocation.
72struct RustcOutput {
73    success: bool,
74    stderr: String,
75}
76
77/// Result of a successful [`RustExecutor::execute`] call.
78///
79/// Contains the sandbox execution result plus any compiler diagnostics
80/// (warnings) that were emitted during the check step.
81#[derive(Debug, Clone)]
82pub struct CodeResult {
83    /// The sandbox execution result (stdout, stderr, exit_code, duration).
84    pub exec_result: ExecResult,
85    /// Compiler diagnostics from the check step (warnings only — errors halt execution).
86    pub diagnostics: Vec<RustDiagnostic>,
87    /// Structured JSON output extracted from the last stdout line, if any.
88    pub output: Option<serde_json::Value>,
89    /// Display stdout (everything before the structured output line).
90    pub display_stdout: String,
91}
92
93/// Rust-specific executor that compiles code through a check → build → execute pipeline
94/// and delegates execution to a [`SandboxBackend`].
95///
96/// # Isolation
97///
98/// | Step | Where it runs | Environment |
99/// |---|---|---|
100/// | Check, build | Inside the backend when it confines filesystem reads and accepts [`Language::Command`] (Unix only); otherwise on the host | Cleared, plus the toolchain allowlist from [`ProcessBackend::toolchain_env`] |
101/// | Execute | Inside the backend | Whatever the backend exposes; [`ProcessBackend`] clears it |
102///
103/// With the environment cleared, `env!` and `option_env!` in user code cannot
104/// embed host credentials into the binary. Compile-time file access such as
105/// `include_str!` reads with the permissions of wherever `rustc` runs: inside a
106/// read-confining backend it is confined like the binary, and on the host it
107/// reaches no file the binary could not also read at run time, because `rustc`
108/// runs on the host only when the backend does not confine reads. On Windows,
109/// `rustc` always runs on the host.
110///
111/// # Example
112///
113/// ```rust,no_run
114/// use adk_code::{RustExecutor, RustExecutorConfig};
115/// use adk_sandbox::ProcessBackend;
116/// use std::sync::Arc;
117/// use std::time::Duration;
118///
119/// # async fn example() -> Result<(), adk_code::CodeError> {
120/// let backend = Arc::new(ProcessBackend::default());
121/// let executor = RustExecutor::new(backend, RustExecutorConfig::default());
122/// let code = "fn run(input: serde_json::Value) -> serde_json::Value { input }";
123/// let result = executor.execute(code, None, Duration::from_secs(30)).await?;
124/// # Ok(())
125/// # }
126/// ```
127pub struct RustExecutor {
128    backend: Arc<dyn SandboxBackend>,
129    config: RustExecutorConfig,
130}
131
132impl RustExecutor {
133    /// Create a new executor with the given sandbox backend and configuration.
134    pub fn new(backend: Arc<dyn SandboxBackend>, config: RustExecutorConfig) -> Self {
135        Self { backend, config }
136    }
137
138    /// Execute Rust code through the check → build → execute pipeline.
139    ///
140    /// The `input` parameter is optional JSON that will be serialized to stdin
141    /// for the harness `run()` function.
142    ///
143    /// # Errors
144    ///
145    /// - [`CodeError::InvalidCode`] if the source fails pre-compilation validation
146    /// - [`CodeError::CompileError`] if the check step finds error-level diagnostics
147    /// - [`CodeError::DependencyNotFound`] if `serde_json` cannot be located
148    /// - [`CodeError::Sandbox`] if the backend fails during execution
149    #[instrument(skip_all, fields(backend = %self.backend.name()))]
150    pub async fn execute(
151        &self,
152        code: &str,
153        input: Option<&serde_json::Value>,
154        timeout: Duration,
155    ) -> Result<CodeResult, CodeError> {
156        // Pre-compilation validation.
157        validate_rust_source(code).map_err(|e| CodeError::InvalidCode(e.to_string()))?;
158
159        // Create temp directory for compilation artifacts.
160        let tmp_dir = tempfile::tempdir()
161            .map_err(|e| CodeError::InvalidCode(format!("failed to create temp directory: {e}")))?;
162
163        let source_path = tmp_dir.path().join("main.rs");
164        // The backend runs the binary as a shell command, and `cmd.exe` does not
165        // try `.exe` for a path that already names a directory, so the output file
166        // carries the platform suffix rustc would otherwise add on its own.
167        let binary_path = tmp_dir.path().join(format!("main{}", std::env::consts::EXE_SUFFIX));
168
169        // Write harnessed source.
170        let harnessed_source = HARNESS_TEMPLATE.replace("{user_code}", code);
171        tokio::fs::write(&source_path, &harnessed_source)
172            .await
173            .map_err(|e| CodeError::InvalidCode(format!("failed to write source file: {e}")))?;
174
175        debug!(source_path = %source_path.display(), "wrote harnessed source");
176
177        // Locate serde_json dependency.
178        let serde_json_path = self.find_serde_json_dep().await?;
179
180        // Step 1: Check — compile with --error-format=json, parse diagnostics.
181        let diagnostics = self.check(&source_path, &serde_json_path, timeout).await?;
182
183        // Step 2: Build — compile to binary.
184        self.build(&source_path, &binary_path, &serde_json_path, timeout).await?;
185
186        info!("compilation succeeded, delegating execution to sandbox backend");
187
188        // Step 3: Execute — delegate to SandboxBackend.
189        let stdin = input.map(|v| serde_json::to_string(v).unwrap_or_default());
190        let exec_request = ExecRequest {
191            language: Language::Command,
192            code: binary_path.to_string_lossy().to_string(),
193            stdin,
194            timeout,
195            memory_limit_mb: None,
196            env: HashMap::new(),
197        };
198
199        let exec_result = self.backend.execute(exec_request).await?;
200
201        // Extract structured output from stdout.
202        let (output, display_stdout) = extract_structured_output(&exec_result.stdout);
203
204        debug!(
205            exit_code = exec_result.exit_code,
206            duration_ms = exec_result.duration.as_millis() as u64,
207            has_output = output.is_some(),
208            "execution completed"
209        );
210
211        Ok(CodeResult { exec_result, diagnostics, output, display_stdout })
212    }
213
214    /// Check step: compile with `--error-format=json` and `--emit=metadata`
215    /// to parse diagnostics without producing a binary.
216    ///
217    /// Returns warnings (errors halt with [`CodeError::CompileError`]).
218    async fn check(
219        &self,
220        source_path: &Path,
221        serde_json_path: &Option<PathBuf>,
222        timeout: Duration,
223    ) -> Result<Vec<RustDiagnostic>, CodeError> {
224        // Use a temp directory for metadata output to avoid /dev/null issues on macOS.
225        let check_dir = tempfile::tempdir().map_err(|e| {
226            CodeError::InvalidCode(format!("failed to create check temp directory: {e}"))
227        })?;
228        let metadata_out = check_dir.path().join("check_output");
229
230        let mut args: Vec<OsString> = vec![
231            source_path.into(),
232            "--edition".into(),
233            "2021".into(),
234            "--error-format=json".into(),
235            "--color".into(),
236            "never".into(),
237            "--emit=metadata".into(),
238            "-o".into(),
239            metadata_out.into(),
240        ];
241        args.extend(self.dependency_args(serde_json_path));
242
243        let RustcOutput { stderr, .. } = self.run_rustc(args, timeout, "check").await?;
244        let diagnostics = parse_diagnostics(&stderr);
245
246        let has_errors = diagnostics.iter().any(|d| d.level == "error");
247        if has_errors {
248            debug!(
249                error_count = diagnostics.iter().filter(|d| d.level == "error").count(),
250                "check step found errors"
251            );
252            return Err(CodeError::CompileError { diagnostics, stderr });
253        }
254
255        let warning_count = diagnostics.iter().filter(|d| d.level == "warning").count();
256        if warning_count > 0 {
257            debug!(warning_count, "check step found warnings");
258        }
259
260        Ok(diagnostics)
261    }
262
263    /// Build step: compile to a binary.
264    async fn build(
265        &self,
266        source_path: &Path,
267        binary_path: &Path,
268        serde_json_path: &Option<PathBuf>,
269        timeout: Duration,
270    ) -> Result<(), CodeError> {
271        let mut args: Vec<OsString> = vec![
272            source_path.into(),
273            "-o".into(),
274            binary_path.into(),
275            "--edition".into(),
276            "2021".into(),
277        ];
278        args.extend(self.dependency_args(serde_json_path));
279
280        let output = self.run_rustc(args, timeout, "build").await?;
281        if !output.success {
282            let diagnostics = parse_diagnostics(&output.stderr);
283            return Err(CodeError::CompileError { diagnostics, stderr: output.stderr });
284        }
285
286        Ok(())
287    }
288
289    /// The `--extern serde_json=...` and `-L dependency=...` flags, followed by
290    /// the extra flags from config.
291    fn dependency_args(&self, serde_json_path: &Option<PathBuf>) -> Vec<OsString> {
292        let mut args = Vec::new();
293        if let Some(dep_path) = serde_json_path {
294            args.push("--extern".into());
295            args.push(format!("serde_json={}", dep_path.display()).into());
296
297            if let Some(parent) = dep_path.parent() {
298                args.push("-L".into());
299                args.push(format!("dependency={}", parent.display()).into());
300            }
301        }
302        args.extend(self.config.rustc_flags.iter().map(OsString::from));
303        args
304    }
305
306    /// Runs `rustc` with `args` under `timeout`, from a cleared environment plus
307    /// the toolchain allowlist.
308    ///
309    /// When the backend confines filesystem reads, `rustc` runs through it as a
310    /// shell command, so compile-time file access (`include_str!`,
311    /// `include_bytes!`) is confined like the binary. Otherwise it runs on the
312    /// host, where it can read nothing the unconfined binary could not.
313    async fn run_rustc(
314        &self,
315        args: Vec<OsString>,
316        timeout: Duration,
317        step: &str,
318    ) -> Result<RustcOutput, CodeError> {
319        let capabilities = self.backend.capabilities();
320        // The command is quoted for a POSIX shell, so only Unix backends receive it.
321        let compile_in_backend = cfg!(unix)
322            && capabilities.enforced_limits.filesystem_read_isolation
323            && capabilities.supported_languages.contains(&Language::Command);
324
325        if compile_in_backend {
326            let code = std::iter::once(OsString::from(&self.config.rustc_path))
327                .chain(args)
328                .map(|arg| format!("'{}'", arg.to_string_lossy().replace('\'', r"'\''")))
329                .collect::<Vec<_>>()
330                .join(" ");
331            let env = ProcessBackend::toolchain_env()
332                .into_iter()
333                .filter_map(|(key, value)| value.into_string().ok().map(|value| (key, value)))
334                .collect();
335            debug!(step, "running rustc inside the sandbox backend");
336
337            let request = ExecRequest {
338                language: Language::Command,
339                code,
340                stdin: None,
341                timeout,
342                memory_limit_mb: None,
343                env,
344            };
345            return match self.backend.execute(request).await {
346                Ok(result) => {
347                    Ok(RustcOutput { success: result.exit_code == 0, stderr: result.stderr })
348                }
349                Err(SandboxError::Timeout { .. }) => {
350                    Err(CodeError::InvalidCode(format!("{step} step timed out")))
351                }
352                Err(error) => Err(error.into()),
353            };
354        }
355
356        let mut cmd = host_process::rustc_command(&self.config.rustc_path);
357        cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
358
359        match tokio::time::timeout(timeout, cmd.output()).await {
360            Ok(Ok(output)) => Ok(RustcOutput {
361                success: output.status.success(),
362                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
363            }),
364            Ok(Err(e)) => {
365                Err(CodeError::InvalidCode(format!("failed to invoke rustc for {step}: {e}")))
366            }
367            // `kill_on_drop` terminated rustc when the timed-out future was dropped.
368            Err(_) => Err(CodeError::InvalidCode(format!("{step} step timed out"))),
369        }
370    }
371
372    /// Locate the `serde_json` rlib using the fallback chain:
373    /// 1. Explicit config path → use if exists
374    /// 2. `cargo metadata` → find rlib in target/debug/deps
375    /// 3. Return [`CodeError::DependencyNotFound`] with instructions
376    async fn find_serde_json_dep(&self) -> Result<Option<PathBuf>, CodeError> {
377        let mut searched = Vec::new();
378
379        // 1. Explicit config path.
380        if let Some(ref path) = self.config.serde_json_path {
381            if path.exists() {
382                debug!(path = %path.display(), "using configured serde_json path");
383                return Ok(Some(path.clone()));
384            }
385            searched.push(format!("config: {}", path.display()));
386        }
387
388        // 2. cargo metadata scan.
389        let output = tokio::process::Command::new("cargo")
390            .args(["metadata", "--format-version=1", "--no-deps"])
391            .stdout(std::process::Stdio::piped())
392            .stderr(std::process::Stdio::null())
393            .output()
394            .await;
395
396        if let Ok(output) = output
397            && output.status.success()
398            && let Ok(metadata) = serde_json::from_slice::<serde_json::Value>(&output.stdout)
399            && let Some(target_dir) = metadata["target_directory"].as_str()
400        {
401            let deps_dir = PathBuf::from(target_dir).join("debug").join("deps");
402            searched.push(format!("cargo metadata: {}", deps_dir.display()));
403            if let Some(rlib) = find_rlib_in_dir(&deps_dir, "serde_json").await {
404                debug!(path = %rlib.display(), "found serde_json via cargo metadata");
405                return Ok(Some(rlib));
406            }
407        } else {
408            searched.push("cargo metadata: command failed".to_string());
409        }
410
411        // 3. Descriptive error.
412        Err(CodeError::DependencyNotFound { name: "serde_json".to_string(), searched })
413    }
414}
415
416/// Find an rlib file matching the given crate name in a directory.
417async fn find_rlib_in_dir(dir: &Path, crate_name: &str) -> Option<PathBuf> {
418    let prefix = format!("lib{crate_name}-");
419    let mut entries = match tokio::fs::read_dir(dir).await {
420        Ok(entries) => entries,
421        Err(_) => return None,
422    };
423
424    while let Ok(Some(entry)) = entries.next_entry().await {
425        let name = entry.file_name();
426        let name_str = name.to_string_lossy();
427        if name_str.starts_with(&prefix) && name_str.ends_with(".rlib") {
428            return Some(entry.path());
429        }
430    }
431    None
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use adk_sandbox::{BackendCapabilities, EnforcedLimits, SandboxError};
438    use async_trait::async_trait;
439    use std::sync::Mutex;
440
441    /// A mock sandbox backend for unit testing.
442    struct MockBackend {
443        /// Captured requests for assertion.
444        captured: Mutex<Vec<ExecRequest>>,
445        /// Canned response to return.
446        response: Mutex<Option<Result<ExecResult, SandboxError>>>,
447    }
448
449    impl MockBackend {
450        fn new(response: Result<ExecResult, SandboxError>) -> Self {
451            Self { captured: Mutex::new(Vec::new()), response: Mutex::new(Some(response)) }
452        }
453
454        fn success(stdout: &str) -> Self {
455            Self::new(Ok(ExecResult {
456                stdout: stdout.to_string(),
457                stderr: String::new(),
458                exit_code: 0,
459                duration: Duration::from_millis(10),
460            }))
461        }
462    }
463
464    #[async_trait]
465    impl SandboxBackend for MockBackend {
466        fn name(&self) -> &str {
467            "mock"
468        }
469
470        fn capabilities(&self) -> BackendCapabilities {
471            BackendCapabilities {
472                supported_languages: vec![Language::Command],
473                isolation_class: "mock".to_string(),
474                enforced_limits: EnforcedLimits {
475                    timeout: true,
476                    memory: false,
477                    network_isolation: false,
478                    filesystem_write_isolation: false,
479                    filesystem_read_isolation: false,
480                    environment_isolation: false,
481                },
482            }
483        }
484
485        async fn execute(&self, request: ExecRequest) -> Result<ExecResult, SandboxError> {
486            self.captured.lock().unwrap().push(request);
487            self.response
488                .lock()
489                .unwrap()
490                .take()
491                .unwrap_or(Err(SandboxError::ExecutionFailed("no canned response".to_string())))
492        }
493    }
494
495    /// A backend that confines filesystem reads and records every request.
496    struct ReadConfiningBackend {
497        captured: Mutex<Vec<ExecRequest>>,
498    }
499
500    #[async_trait]
501    impl SandboxBackend for ReadConfiningBackend {
502        fn name(&self) -> &str {
503            "read-confining"
504        }
505
506        fn capabilities(&self) -> BackendCapabilities {
507            BackendCapabilities {
508                supported_languages: vec![Language::Command],
509                isolation_class: "mock".to_string(),
510                enforced_limits: EnforcedLimits {
511                    timeout: true,
512                    memory: false,
513                    network_isolation: true,
514                    filesystem_write_isolation: true,
515                    filesystem_read_isolation: true,
516                    environment_isolation: true,
517                },
518            }
519        }
520
521        async fn execute(&self, request: ExecRequest) -> Result<ExecResult, SandboxError> {
522            self.captured.lock().unwrap().push(request);
523            Ok(ExecResult {
524                stdout: r#"{"ok":true}"#.to_string(),
525                stderr: String::new(),
526                exit_code: 0,
527                duration: Duration::from_millis(1),
528            })
529        }
530    }
531
532    /// Compilation must not escape a backend that confines filesystem reads,
533    /// otherwise `include_str!` reads host files the binary itself cannot.
534    #[cfg(unix)]
535    #[tokio::test]
536    async fn compilation_runs_inside_a_read_confining_backend() {
537        let tmp_dir = tempfile::tempdir().unwrap();
538        let fake_rlib = tmp_dir.path().join("libserde_json-abc123.rlib");
539        tokio::fs::write(&fake_rlib, b"fake rlib").await.unwrap();
540
541        let backend = Arc::new(ReadConfiningBackend { captured: Mutex::new(Vec::new()) });
542        let config = RustExecutorConfig {
543            rustc_path: "/nonexistent/rustc-must-not-run-on-host".to_string(),
544            serde_json_path: Some(fake_rlib),
545            ..Default::default()
546        };
547        let executor = RustExecutor::new(backend.clone(), config);
548
549        let code = "fn run(input: serde_json::Value) -> serde_json::Value { input }";
550        let result = executor.execute(code, None, Duration::from_secs(5)).await.unwrap();
551        assert_eq!(result.output, Some(serde_json::json!({ "ok": true })));
552
553        let captured = backend.captured.lock().unwrap();
554        assert_eq!(captured.len(), 3, "check, build, and execute all go through the backend");
555
556        let toolchain: Vec<String> =
557            ProcessBackend::toolchain_env().into_iter().map(|(key, _)| key).collect();
558        for (request, step_flag) in captured[..2].iter().zip(["'--error-format=json'", "'-o'"]) {
559            assert_eq!(request.language, Language::Command);
560            assert!(
561                request.code.starts_with("'/nonexistent/rustc-must-not-run-on-host' "),
562                "{}",
563                request.code
564            );
565            assert!(request.code.contains(step_flag), "{}", request.code);
566            assert!(
567                request.env.keys().all(|key| toolchain.contains(key)),
568                "compile environment must be the toolchain allowlist: {:?}",
569                request.env.keys()
570            );
571        }
572        assert!(captured[2].env.is_empty());
573    }
574
575    #[test]
576    fn default_config() {
577        let config = RustExecutorConfig::default();
578        assert_eq!(config.rustc_path, "rustc");
579        assert!(config.serde_json_path.is_none());
580        assert!(config.rustc_flags.is_empty());
581    }
582
583    #[tokio::test]
584    async fn check_valid_code_produces_no_errors() {
585        let backend = Arc::new(MockBackend::success(r#"{"result":42}"#));
586        let executor = RustExecutor::new(backend, RustExecutorConfig::default());
587
588        let tmp_dir = tempfile::tempdir().unwrap();
589        let source_path = tmp_dir.path().join("valid.rs");
590        let code = r#"
591fn run(input: serde_json::Value) -> serde_json::Value {
592    input
593}
594"#;
595        let harnessed = HARNESS_TEMPLATE.replace("{user_code}", code);
596        tokio::fs::write(&source_path, &harnessed).await.unwrap();
597
598        // The check step may fail if serde_json is not available, but it should
599        // NOT fail with CodeError::InvalidCode for valid source.
600        let result = executor.check(&source_path, &None, Duration::from_secs(30)).await;
601
602        // If serde_json is not found, rustc will produce an error about the
603        // missing extern crate — that's a compile error, not invalid code.
604        match result {
605            Ok(diagnostics) => {
606                // No error-level diagnostics.
607                assert!(
608                    !diagnostics.iter().any(|d| d.level == "error"),
609                    "expected no error diagnostics for valid code"
610                );
611            }
612            Err(CodeError::CompileError { diagnostics, .. }) => {
613                // Acceptable: serde_json not linked, so rustc reports an error.
614                assert!(
615                    diagnostics.iter().any(|d| d.level == "error"),
616                    "expected error diagnostics when serde_json is missing"
617                );
618            }
619            Err(other) => panic!("unexpected error: {other}"),
620        }
621    }
622
623    #[tokio::test]
624    async fn check_invalid_code_returns_compile_error() {
625        let backend = Arc::new(MockBackend::success(""));
626        let executor = RustExecutor::new(backend, RustExecutorConfig::default());
627
628        let tmp_dir = tempfile::tempdir().unwrap();
629        let source_path = tmp_dir.path().join("invalid.rs");
630        // Deliberately broken Rust code.
631        let code = "fn broken( { }";
632        tokio::fs::write(&source_path, code).await.unwrap();
633
634        let result = executor.check(&source_path, &None, Duration::from_secs(30)).await;
635
636        match result {
637            Err(CodeError::CompileError { diagnostics, stderr }) => {
638                assert!(
639                    diagnostics.iter().any(|d| d.level == "error"),
640                    "expected at least one error diagnostic"
641                );
642                assert!(!stderr.is_empty(), "expected non-empty stderr");
643            }
644            other => panic!("expected CompileError, got: {other:?}"),
645        }
646    }
647
648    #[tokio::test]
649    async fn check_warnings_are_returned_without_halting() {
650        let backend = Arc::new(MockBackend::success(""));
651        let executor = RustExecutor::new(backend, RustExecutorConfig::default());
652
653        let tmp_dir = tempfile::tempdir().unwrap();
654        let source_path = tmp_dir.path().join("warnings.rs");
655        // Code with an unused variable warning.
656        let code = "fn main() { let x = 42; }";
657        tokio::fs::write(&source_path, code).await.unwrap();
658
659        let result = executor.check(&source_path, &None, Duration::from_secs(30)).await;
660
661        match result {
662            Ok(diagnostics) => {
663                // Should have at least one warning about unused variable.
664                assert!(
665                    diagnostics.iter().any(|d| d.level == "warning"),
666                    "expected at least one warning diagnostic, got: {diagnostics:?}"
667                );
668            }
669            Err(CodeError::CompileError { diagnostics, .. }) => {
670                // If there are errors too, that's unexpected for this code.
671                panic!("unexpected compile errors: {diagnostics:?}");
672            }
673            Err(other) => panic!("unexpected error: {other}"),
674        }
675    }
676
677    #[tokio::test]
678    async fn serde_json_discovery_config_path_exists() {
679        let tmp_dir = tempfile::tempdir().unwrap();
680        let fake_rlib = tmp_dir.path().join("libserde_json-abc123.rlib");
681        tokio::fs::write(&fake_rlib, b"fake rlib").await.unwrap();
682
683        let config =
684            RustExecutorConfig { serde_json_path: Some(fake_rlib.clone()), ..Default::default() };
685        let backend = Arc::new(MockBackend::success(""));
686        let executor = RustExecutor::new(backend, config);
687
688        let result = executor.find_serde_json_dep().await.unwrap();
689        assert_eq!(result, Some(fake_rlib));
690    }
691
692    #[tokio::test]
693    async fn serde_json_discovery_config_path_missing() {
694        let config = RustExecutorConfig {
695            serde_json_path: Some(PathBuf::from("/nonexistent/libserde_json.rlib")),
696            ..Default::default()
697        };
698        let backend = Arc::new(MockBackend::success(""));
699        let executor = RustExecutor::new(backend, config);
700
701        // With a non-existent config path and no cargo metadata fallback,
702        // this should try cargo metadata and then fail with DependencyNotFound.
703        let result = executor.find_serde_json_dep().await;
704        match result {
705            Err(CodeError::DependencyNotFound { name, searched }) => {
706                assert_eq!(name, "serde_json");
707                assert!(
708                    searched.iter().any(|s| s.contains("/nonexistent/")),
709                    "expected searched to include the config path, got: {searched:?}"
710                );
711            }
712            // If cargo metadata happens to find it, that's also acceptable.
713            Ok(Some(_)) => {}
714            other => panic!("unexpected result: {other:?}"),
715        }
716    }
717
718    #[test]
719    fn code_error_from_sandbox_error() {
720        let sandbox_err = SandboxError::Timeout { timeout: Duration::from_secs(5) };
721        let code_err: CodeError = sandbox_err.into();
722        assert!(matches!(code_err, CodeError::Sandbox(_)));
723        assert!(code_err.to_string().contains("sandbox error"));
724    }
725
726    #[test]
727    fn validate_rejects_fn_main() {
728        let code = "fn main() { }";
729        let result = validate_rust_source(code);
730        assert!(result.is_err());
731    }
732
733    #[test]
734    fn validate_accepts_valid_run() {
735        let code = r#"
736fn run(input: serde_json::Value) -> serde_json::Value {
737    input
738}
739"#;
740        assert!(validate_rust_source(code).is_ok());
741    }
742}