Skip to main content

rightkit_qa/
engine.rs

1//! Black-box driving of an app's engine binary: one-shot CLI words and the
2//! framed stdio sidecar protocol (newline-delimited JSON through
3//! `rightkit-sidecar`). Nothing mocks the engine.
4use crate::process::{run_owned, RunOptions, Tracker};
5use crate::util::{err, Error, Result};
6use rightkit_child_process::{OwnedChild, OwnedCommand};
7use rightkit_sidecar::{read_json_line, write_json_line, FrameError};
8use serde_json::{json, Value};
9use std::io::{BufReader, Write};
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::mpsc::{channel, Receiver, RecvTimeoutError};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15
16pub const FRAME_LIMIT: usize = 16 * 1024 * 1024;
17
18/// Start of the error a `Sidecar` request returns when no frame arrives in time.
19const TIMEOUT_PREFIX: &str = "sidecar timeout after";
20/// Frames [`Sidecar::events`] keeps unless [`Sidecar::set_event_limit`] changes it.
21const DEFAULT_EVENT_LIMIT: usize = 2_048;
22/// Bytes of engine stderr kept unless [`Sidecar::set_stderr_limit`] changes it.
23const DEFAULT_STDERR_LIMIT: usize = 256 * 1024;
24
25/// An engine binary and how to launch it without touching real user data.
26///
27/// Every launch (`cli`, `run`, `start_sidecar`) must name an isolated data directory, or it is
28/// refused before the process starts with a [`crate::userdata::UserDataViolation`] (rule
29/// `no-isolated-data-dir`). A directory is named when the caller's `CliOptions::data_dir` reaches
30/// the engine through `data_dir_env`, or `data_dir_env` is set in the launch environment, or
31/// `data_dir_arg` appears in the arguments, and the directory passes
32/// [`crate::userdata::check_engine_dirs`]. A `data_dir` on a target that declares neither is not
33/// named: the engine would never see it.
34#[derive(Debug, Clone)]
35pub struct EngineTarget {
36    pub binary: PathBuf,
37    /// Env applied to every engine process (e.g. `GENRIGHT_NO_KEYCHAIN=1`).
38    pub env: Vec<(String, String)>,
39    /// Env var that receives the per-scenario data dir (e.g. `GENRIGHT_APP_DATA`).
40    pub data_dir_env: Option<String>,
41    /// Flag the engine takes its data dir under (e.g. `--data-dir`). Declaring it lets a caller
42    /// name the isolated directory in the launch arguments; the harness only judges the value.
43    pub data_dir_arg: Option<String>,
44    /// Flags that select the real library (e.g. `--use-user-library`). A launch whose arguments
45    /// contain one, as `flag` or `flag=value`, is refused. Empty by default; the product declares
46    /// its own, this crate hard-codes none.
47    pub forbidden_args: Vec<String>,
48    /// Set by [`EngineTarget::allow_no_data_dir_for_refusal_probe`]; read it as a warning label.
49    pub allow_no_data_dir_for_refusal_probe: bool,
50}
51
52#[derive(Debug, Clone, Default)]
53pub struct CliOptions {
54    pub data_dir: Option<PathBuf>,
55    pub env: Vec<(String, String)>,
56    /// Appended as `--input <json>` the way the engine CLI contract expects.
57    pub input: Option<Value>,
58    pub timeout: Option<Duration>,
59}
60
61#[derive(Debug, Clone)]
62pub struct CliResult {
63    pub code: Option<i32>,
64    pub json: Value,
65    pub stdout: String,
66    pub stderr: String,
67    /// Every JSON object line the engine wrote to stderr (progress events etc.).
68    pub events: Vec<Value>,
69    pub timed_out: bool,
70}
71
72impl CliResult {
73    pub fn to_value(&self) -> Value {
74        json!({"code": self.code, "json": self.json, "stdout": self.stdout, "stderr": self.stderr, "events": self.events, "timed_out": self.timed_out})
75    }
76}
77
78impl EngineTarget {
79    /// A target with no environment, no data-dir variable or flag, and no deny list. Such a target
80    /// cannot be launched until it declares `data_dir_env` or `data_dir_arg` (or the probe
81    /// opt-out is used).
82    pub fn new(binary: impl Into<PathBuf>) -> Self {
83        Self {
84            binary: binary.into(),
85            env: Vec::new(),
86            data_dir_env: None,
87            data_dir_arg: None,
88            forbidden_args: Vec::new(),
89            allow_no_data_dir_for_refusal_probe: false,
90        }
91    }
92
93    /// Env var that receives the data dir (e.g. `GENRIGHT_APP_DATA`).
94    pub fn with_data_dir_env(mut self, var: &str) -> Self {
95        self.data_dir_env = Some(var.into());
96        self
97    }
98
99    /// Flag the engine takes its data dir under (e.g. `--data-dir`).
100    pub fn with_data_dir_arg(mut self, flag: &str) -> Self {
101        self.data_dir_arg = Some(flag.into());
102        self
103    }
104
105    /// Flags that select the real library; a launch carrying one is refused.
106    pub fn forbid_args(mut self, flags: &[&str]) -> Self {
107        self.forbidden_args = flags.iter().map(|f| (*f).to_owned()).collect();
108        self
109    }
110
111    /// Let launches of this target name no data directory, ONLY to assert the engine's own
112    /// refusal to run without one. Use it on a dedicated clone of the target, never on the target
113    /// that runs real scenarios. A second barrier is still required: on Unix the launch
114    /// environment (`CliOptions::env` or the target's `env`) must redirect `HOME` into a QA
115    /// directory, and `XDG_DATA_HOME` / `XDG_CONFIG_HOME` too wherever they are set or inherited;
116    /// on Windows the Known Folder API ignores the environment, so the launch is refused
117    /// whatever the caller passes. See [`crate::userdata::check_engine_launch`].
118    pub fn allow_no_data_dir_for_refusal_probe(mut self) -> Self {
119        self.allow_no_data_dir_for_refusal_probe = true;
120        self
121    }
122
123    /// The guard every launch path runs before it spawns anything.
124    fn check_launch(&self, args: &[String], opts: &CliOptions) -> Result<()> {
125        let env = self.env_for(opts.data_dir.as_deref(), &opts.env);
126        crate::userdata::check_engine_launch(&crate::userdata::EngineLaunch {
127            binary: &self.binary,
128            args,
129            data_dir: opts.data_dir.as_deref(),
130            data_dir_env: self.data_dir_env.as_deref(),
131            data_dir_arg: self.data_dir_arg.as_deref(),
132            forbidden_args: &self.forbidden_args,
133            env: &env,
134            refusal_probe: self.allow_no_data_dir_for_refusal_probe,
135        })?;
136        Ok(())
137    }
138
139    fn env_for(
140        &self,
141        data_dir: Option<&Path>,
142        extra: &[(String, String)],
143    ) -> Vec<(String, String)> {
144        let mut env = self.env.clone();
145        if let (Some(var), Some(dir)) = (&self.data_dir_env, data_dir) {
146            env.push((var.clone(), dir.to_string_lossy().into()));
147        }
148        env.extend(extra.iter().cloned());
149        env
150    }
151
152    pub fn cli(&self, args: &[String], opts: &CliOptions, tracker: &Tracker) -> Result<CliResult> {
153        if !self.binary.exists() {
154            return err(format!(
155                "engine binary not found: {}",
156                self.binary.display()
157            ));
158        }
159        self.check_launch(args, opts)?;
160        let mut argv = args.to_vec();
161        if let Some(input) = &opts.input {
162            argv.push("--input".into());
163            argv.push(input.to_string());
164        }
165        let out = run_owned(
166            &self.binary.to_string_lossy(),
167            &argv,
168            &RunOptions {
169                env: self.env_for(opts.data_dir.as_deref(), &opts.env),
170                timeout: opts.timeout,
171                label: format!("engine {}", args.join(" ")),
172                ..Default::default()
173            },
174            tracker,
175        )?;
176        let json = serde_json::from_str(out.stdout.trim()).unwrap_or(Value::Null);
177        let events = out
178            .stderr
179            .lines()
180            .map(str::trim)
181            .filter(|l| l.starts_with('{'))
182            .filter_map(|l| serde_json::from_str(l).ok())
183            .collect();
184        Ok(CliResult {
185            code: out.code,
186            json,
187            stdout: out.stdout,
188            stderr: out.stderr,
189            events,
190            timed_out: out.timed_out,
191        })
192    }
193
194    /// `engine run('job status', input)`: words split, non-zero exit or `json.error` fails.
195    pub fn run(
196        &self,
197        words: &str,
198        input: Value,
199        opts: &CliOptions,
200        tracker: &Tracker,
201    ) -> Result<Value> {
202        let args: Vec<String> = words.split_whitespace().map(String::from).collect();
203        let r = self.cli(
204            &args,
205            &CliOptions {
206                input: Some(input),
207                ..opts.clone()
208            },
209            tracker,
210        )?;
211        if r.code != Some(0) || r.json.get("error").map(|e| !e.is_null()).unwrap_or(false) {
212            return err(format!(
213                "engine command failed ({:?}): {words}\nstdout: {}\nstderr: {}",
214                r.code,
215                r.stdout,
216                crate::util::tail(&r.stderr, 2000)
217            ));
218        }
219        Ok(r.json)
220    }
221
222    pub fn start_sidecar(&self, opts: &CliOptions, tracker: &Tracker) -> Result<Sidecar> {
223        Sidecar::start(self, opts, tracker)
224    }
225}
226
227/// A running `--stdio` sidecar speaking
228/// `{"type":"request","id":N,"method":{"method":"command","params":{"name","input"}}}`
229/// and answering `{"type":"response","status":"ok|err","id":N,"result|error":...}`.
230pub struct Sidecar {
231    child: Option<OwnedChild>,
232    stdin: Option<Box<dyn Write + Send>>,
233    rx: Receiver<Value>,
234    seq: u64,
235    pub hello: Value,
236    pub pid: u32,
237    stderr: Arc<Mutex<StderrBuf>>,
238    /// Frames that were neither hello nor the awaited response (events), oldest first. Once the
239    /// list reaches twice the event limit (default 2,048, see [`Sidecar::set_event_limit`]) the
240    /// oldest are trimmed back to the limit; [`SidecarStatus::events_dropped`] counts them.
241    pub events: Vec<Value>,
242    /// Frames trimmed from `events` since the sidecar started.
243    events_dropped: u64,
244    event_limit: usize,
245    /// Id of the request being awaited, and whether a frame carrying that id has arrived. Set only
246    /// while `request` waits; `push_event` updates it as each frame comes in.
247    watch: Option<(u64, bool)>,
248    /// Forces the old GenRight `status` frames for every command when true. `false` does not
249    /// force jobs frames: the shape then comes from the hello (see [`Sidecar::set_frame_shape`]
250    /// to pin the jobs contract against a legacy hello).
251    pub legacy_status_frames: bool,
252    /// Shape the hello announced (see [`detect_legacy_frames`]); `None` when it names neither.
253    detected_legacy: Option<bool>,
254    /// Sidecar-level pin set by `set_frame_shape`; beats `legacy_status_frames` and the hello.
255    frame_shape: Option<bool>,
256    tracker: Tracker,
257}
258
259/// Runtime figures of a running sidecar, computed on call by [`Sidecar::status`].
260#[derive(Debug, Clone, Copy, PartialEq)]
261pub struct SidecarStatus {
262    pub pid: u32,
263    /// Requests sent so far (the frame sequence).
264    pub requests_sent: u64,
265    /// Frames held in [`Sidecar::events`] (neither hello nor an awaited response). Bounded: at most
266    /// twice the event limit, default 2,048 frames.
267    pub events_buffered: usize,
268    /// Frames trimmed from [`Sidecar::events`] since the sidecar started.
269    pub events_dropped: u64,
270    /// Bytes of engine stderr kept in memory: the last stderr limit's worth (default 256 KiB).
271    pub stderr_bytes: usize,
272    /// Bytes of engine stderr trimmed from memory since the sidecar started.
273    pub stderr_dropped_bytes: u64,
274    /// Resident memory, CPU time and I/O counters of the harness process (the sidecar's reader
275    /// threads run in it; the engine child is a separate process), or `None` when the host cannot
276    /// report them. See `rightkit_child_process::ProcessUsage`.
277    pub process: Option<rightkit_child_process::ProcessUsage>,
278}
279
280/// Frame shape a sidecar's hello announces. rightkit-job-queue' `Dispatcher::hello()` always carries
281/// `contract_version`; GenRight's engine hello (`genright-protocol`, `EngineFrame::Hello`) carries
282/// `rpc_version` and never `contract_version`. `Some(false)` is the rightkit-job-queue contract,
283/// `Some(true)` the legacy GenRight frames, `None` when the hello has neither field.
284pub(crate) fn detect_legacy_frames(hello: &Value) -> Option<bool> {
285    if hello.get("contract_version").is_some() {
286        Some(false)
287    } else if hello.get("rpc_version").is_some() {
288        Some(true)
289    } else {
290        None
291    }
292}
293
294fn command_frame(name: &str, input: Value, legacy: bool) -> Value {
295    if legacy {
296        json!({"type": "request", "method": {"method": "command", "params": {"name": name, "input": input}}})
297    } else {
298        json!({"type": "request", "method": name, "params": input})
299    }
300}
301
302fn command_outcome(f: &Value, legacy: bool) -> Result<Value> {
303    let failed = if legacy {
304        f["status"] == "err"
305    } else {
306        f["ok"] != json!(true)
307    };
308    if failed {
309        return err(format!(
310            "{}: {}",
311            f["error"]["code"].as_str().unwrap_or("error"),
312            f["error"]["message"].as_str().unwrap_or("")
313        ));
314    }
315    Ok(f["result"].clone())
316}
317
318/// Where the frame shape of a command came from.
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320enum ShapeSource {
321    /// A per-command `Option`, `set_frame_shape`, or `legacy_status_frames = true`.
322    Explicit,
323    /// The hello announced it.
324    Detected,
325    /// The hello named neither shape, so the jobs contract was used by default.
326    Fallback,
327}
328
329/// A request that got no response: the error, its id, and whether any frame carried that id.
330struct Exchange {
331    error: Error,
332    id: u64,
333    answered: bool,
334}
335
336/// Engine stderr, kept to its last `limit` bytes. Bytes before `start` were dropped; they stay in
337/// `text` until that dead prefix reaches the limit, so each byte moves O(1) times on average and
338/// `text` never holds more than about twice the limit.
339struct StderrBuf {
340    text: String,
341    start: usize,
342    limit: usize,
343    /// Bytes dropped from the front since the sidecar started.
344    dropped: u64,
345}
346
347impl StderrBuf {
348    fn new(limit: usize) -> Self {
349        Self {
350            text: String::new(),
351            start: 0,
352            limit,
353            dropped: 0,
354        }
355    }
356
357    fn push(&mut self, chunk: &str) {
358        self.text.push_str(chunk);
359        self.trim();
360    }
361
362    fn set_limit(&mut self, limit: usize) {
363        self.limit = limit;
364        self.trim();
365    }
366
367    /// Drops the oldest bytes beyond the limit. The cut moves forward to just after a newline when
368    /// one sits within an eighth of the limit, so a kept line is whole where possible.
369    fn trim(&mut self) {
370        if self.text.len() - self.start > self.limit {
371            let mut cut = self.text.len() - self.limit;
372            while !self.text.is_char_boundary(cut) {
373                cut += 1;
374            }
375            let window_end = (cut + self.limit / 8).min(self.text.len());
376            if let Some(p) = self.text.as_bytes()[cut..window_end]
377                .iter()
378                .position(|&b| b == b'\n')
379            {
380                cut += p + 1;
381            }
382            self.dropped += (cut - self.start) as u64;
383            self.start = cut;
384        }
385        if self.start >= self.limit {
386            self.text.drain(..self.start);
387            self.start = 0;
388        }
389    }
390
391    fn retained(&self) -> &str {
392        &self.text[self.start..]
393    }
394
395    fn bytes(&self) -> usize {
396        self.text.len() - self.start
397    }
398
399    /// The last `max` retained bytes, preceded by a marker when earlier output was dropped.
400    fn tail(&self, max: usize) -> String {
401        let tail = crate::util::tail(self.retained(), max);
402        if self.dropped == 0 {
403            tail
404        } else {
405            format!("[{} bytes of earlier stderr dropped]\n{tail}", self.dropped)
406        }
407    }
408}
409
410impl Sidecar {
411    fn start(engine: &EngineTarget, opts: &CliOptions, tracker: &Tracker) -> Result<Self> {
412        engine.check_launch(&["--stdio".to_string()], opts)?;
413        let mut cmd = Command::new(&engine.binary);
414        cmd.arg("--stdio")
415            .stdin(Stdio::piped())
416            .stdout(Stdio::piped())
417            .stderr(Stdio::piped());
418        for (k, v) in engine.env_for(opts.data_dir.as_deref(), &opts.env) {
419            cmd.env(k, v);
420        }
421        let mut owned = OwnedCommand::from_command(cmd);
422        owned.windows_hide();
423        let mut child = owned.spawn().map_err(|e| {
424            Error(format!(
425                "failed to start sidecar {}: {e}",
426                engine.binary.display()
427            ))
428        })?;
429        let pid = child.id();
430        tracker.register(pid, "engine --stdio");
431        let stdin = child.take_stdin();
432        let stdout = child
433            .take_stdout()
434            .ok_or_else(|| Error("sidecar stdout unavailable".into()))?;
435        let mut stderr_pipe = child.take_stderr();
436        let stderr = Arc::new(Mutex::new(StderrBuf::new(DEFAULT_STDERR_LIMIT)));
437        let sink = stderr.clone();
438        std::thread::spawn(move || {
439            use std::io::Read;
440            let mut buf = [0u8; 4096];
441            if let Some(p) = stderr_pipe.as_mut() {
442                while let Ok(n) = p.read(&mut buf) {
443                    if n == 0 {
444                        break;
445                    }
446                    sink.lock()
447                        .unwrap()
448                        .push(&String::from_utf8_lossy(&buf[..n]));
449                }
450            }
451        });
452        let (tx, rx) = channel();
453        std::thread::spawn(move || {
454            let mut reader = BufReader::new(stdout);
455            let mut buf = Vec::new();
456            loop {
457                match read_json_line::<_, Value>(&mut reader, &mut buf, FRAME_LIMIT) {
458                    Ok(Some(v)) => {
459                        if tx.send(v).is_err() {
460                            break;
461                        }
462                    }
463                    Ok(None) => break,
464                    Err(FrameError::Io(_)) => break,
465                    Err(_) => continue, // non-JSON line (log noise): skip, stay on the frame boundary
466                }
467            }
468        });
469        Self {
470            child: Some(child),
471            stdin: stdin.map(|s| Box::new(s) as Box<dyn Write + Send>),
472            rx,
473            seq: 0,
474            hello: Value::Null,
475            pid,
476            stderr,
477            events: vec![],
478            events_dropped: 0,
479            event_limit: DEFAULT_EVENT_LIMIT,
480            watch: None,
481            legacy_status_frames: false,
482            detected_legacy: None,
483            frame_shape: None,
484            tracker: tracker.clone(),
485        }
486        .finish_start()
487    }
488
489    /// Reads the hello and records the frame shape it announces.
490    fn finish_start(mut self) -> Result<Self> {
491        self.hello = self.await_frame(Duration::from_secs(30), |f| f["type"] == "hello")?;
492        self.detected_legacy = detect_legacy_frames(&self.hello);
493        Ok(self)
494    }
495
496    fn await_frame(
497        &mut self,
498        timeout: Duration,
499        mut want: impl FnMut(&Value) -> bool,
500    ) -> Result<Value> {
501        let deadline = Instant::now() + timeout;
502        loop {
503            let left = deadline.saturating_duration_since(Instant::now());
504            match self.rx.recv_timeout(left.max(Duration::from_millis(1))) {
505                Ok(f) if want(&f) => return Ok(f),
506                Ok(f) => self.push_event(f),
507                Err(RecvTimeoutError::Timeout) => {
508                    return err(format!(
509                        "{} {}ms; stderr tail: {}",
510                        TIMEOUT_PREFIX,
511                        timeout.as_millis(),
512                        self.stderr_tail()
513                    ))
514                }
515                Err(RecvTimeoutError::Disconnected) => {
516                    return err(format!(
517                        "sidecar closed its stdout; stderr tail: {}",
518                        self.stderr_tail()
519                    ))
520                }
521            }
522        }
523    }
524
525    /// Buffer counts and process resource usage, read now. No polling thread runs for this.
526    pub fn status(&self) -> SidecarStatus {
527        let (stderr_bytes, stderr_dropped_bytes) = self
528            .stderr
529            .lock()
530            .map_or((0, 0), |s| (s.bytes(), s.dropped));
531        SidecarStatus {
532            pid: self.pid,
533            requests_sent: self.seq,
534            events_buffered: self.events.len(),
535            events_dropped: self.events_dropped,
536            stderr_bytes,
537            stderr_dropped_bytes,
538            process: rightkit_child_process::process_usage().ok(),
539        }
540    }
541
542    /// Keeps the most recent `limit` frames in [`Sidecar::events`] (default 2,048). Frames beyond
543    /// the new limit are trimmed now, and the list is trimmed again once it reaches twice the limit.
544    pub fn set_event_limit(&mut self, limit: usize) {
545        self.event_limit = limit;
546        self.drop_oldest_events(limit);
547    }
548
549    /// Keeps the last `bytes` of engine stderr in memory (default 256 KiB).
550    pub fn set_stderr_limit(&mut self, bytes: usize) {
551        if let Ok(mut buf) = self.stderr.lock() {
552            buf.set_limit(bytes);
553        }
554    }
555
556    pub fn stderr_tail(&self) -> String {
557        self.stderr.lock().unwrap().tail(1500)
558    }
559
560    /// Buffers a frame that is neither the hello nor an awaited response. A request waiting on
561    /// its id is told about the frame here, as it arrives, so trimming never hides it.
562    fn push_event(&mut self, frame: Value) {
563        if let Some((id, seen)) = self.watch.as_mut() {
564            if frame["id"] == json!(*id) {
565                *seen = true;
566            }
567        }
568        self.events.push(frame);
569        if self.events.len() >= self.event_limit.saturating_mul(2).max(1) {
570            self.drop_oldest_events(self.event_limit);
571        }
572    }
573
574    /// Trims `events` to its most recent `keep` frames, counting what was removed.
575    fn drop_oldest_events(&mut self, keep: usize) {
576        if self.events.len() > keep {
577            let excess = self.events.len() - keep;
578            self.events.drain(..excess);
579            self.events_dropped += excess as u64;
580        }
581    }
582
583    /// Send an arbitrary frame and return the response with the same id.
584    pub fn raw(&mut self, frame: Value, timeout: Duration) -> Result<Value> {
585        self.request(frame, timeout).map_err(|x| x.error)
586    }
587
588    /// Writes `frame` with a fresh id and waits for the response with that id. A failure says
589    /// whether any frame carrying that id arrived, so a silent engine can be told apart.
590    fn request(
591        &mut self,
592        mut frame: Value,
593        timeout: Duration,
594    ) -> std::result::Result<Value, Exchange> {
595        self.seq += 1;
596        let id = self.seq;
597        frame["id"] = json!(id);
598        let written = match self.stdin.as_mut() {
599            Some(stdin) => write_json_line(stdin, &frame, FRAME_LIMIT)
600                .map_err(|e| Error(e.to_string()))
601                .and_then(|()| stdin.flush().map_err(|e| Error(e.to_string()))),
602            None => Err(Error("sidecar stdin closed".into())),
603        };
604        if let Err(error) = written {
605            return Err(Exchange {
606                error,
607                id,
608                answered: false,
609            });
610        }
611        self.watch = Some((id, false));
612        let waited = self.await_frame(timeout, |f| f["type"] == "response" && f["id"] == json!(id));
613        let answered = self.watch.take().is_some_and(|(_, seen)| seen);
614        waited.map_err(|error| Exchange {
615            error,
616            id,
617            answered,
618        })
619    }
620
621    /// The shape a command is sent in: a per-command `Option`, then the sidecar pin, then the
622    /// `legacy_status_frames` field, then what the hello announced, then the jobs contract.
623    fn resolve_shape(&self, per_command: Option<bool>) -> (bool, ShapeSource) {
624        if let Some(legacy) = per_command.or(self.frame_shape) {
625            return (legacy, ShapeSource::Explicit);
626        }
627        if self.legacy_status_frames {
628            return (true, ShapeSource::Explicit);
629        }
630        match self.detected_legacy {
631            Some(legacy) => (legacy, ShapeSource::Detected),
632            None => (false, ShapeSource::Fallback),
633        }
634    }
635
636    /// A command. Default is the rightkit-job-queue contract: `{type:"request", id, method: name,
637    /// params: input}` answered by `{type:"response", id, ok, result | error:{code,message}}`.
638    /// With `legacy_status_frames` the old GenRight shape is used (`method:{method:"command",
639    /// params:{name,input}}`, answered with `status: ok|err`). The shape a hello announces is
640    /// used when nothing is set; see [`Sidecar::resolve_shape`].
641    pub fn command(&mut self, name: &str, input: Value, timeout: Duration) -> Result<Value> {
642        self.command_with(name, input, timeout, None)
643    }
644
645    pub fn command_with(
646        &mut self,
647        name: &str,
648        input: Value,
649        timeout: Duration,
650        legacy_status_frames: Option<bool>,
651    ) -> Result<Value> {
652        let (legacy, source) = self.resolve_shape(legacy_status_frames);
653        match self.request(command_frame(name, input, legacy), timeout) {
654            Ok(f) => command_outcome(&f, legacy),
655            Err(x)
656                if source == ShapeSource::Fallback
657                    && !x.answered
658                    && x.error.0.starts_with(TIMEOUT_PREFIX) =>
659            {
660                err(format!(
661                    "engine did not answer the frame shape that was sent for `{name}`: sent the \
662                     rightkit-job-queue contract {{type:\"request\", id, method, params}} and no frame \
663                     came back for request id {} within {}ms. The hello carried neither \
664                     contract_version nor rpc_version, so the shape was not detected. If this engine \
665                     speaks GenRight's legacy frames ({{type:\"request\", id, \
666                     method:{{method:\"command\", params:{{name, input}}}}}} answered by status: \
667                     ok|err), set legacy_status_frames = true on sidecar_start or on this \
668                     sidecar_command. stderr tail: {}",
669                    x.id,
670                    timeout.as_millis(),
671                    self.stderr_tail()
672                ))
673            }
674            Err(x) => Err(x.error),
675        }
676    }
677
678    /// Pins the frame shape for every command on this sidecar: `Some(true)` the legacy GenRight
679    /// frames, `Some(false)` the rightkit-job-queue contract, `None` clears the pin. A per-command
680    /// `Option` still wins over the pin.
681    pub fn set_frame_shape(&mut self, legacy: Option<bool>) {
682        self.frame_shape = legacy;
683    }
684
685    pub fn shutdown(&mut self) {
686        self.seq += 1;
687        if let Some(stdin) = self.stdin.as_mut() {
688            let _ = write_json_line(
689                stdin,
690                &json!({"type":"request","id":self.seq,"method":{"method":"shutdown"}}),
691                FRAME_LIMIT,
692            );
693        }
694    }
695
696    /// Close stdin, give the engine a moment to exit, then kill the owned tree.
697    /// Returns the exit code if it exited on its own.
698    pub fn close(&mut self) -> Option<i32> {
699        self.stdin.take();
700        let mut code = None;
701        if let Some(mut child) = self.child.take() {
702            match child.wait_timeout(Duration::from_secs(5)) {
703                Ok(Some(s)) => code = s.code(),
704                _ => {
705                    let _ = child.terminate_tree();
706                }
707            }
708        }
709        self.tracker.forget(self.pid);
710        code
711    }
712}
713
714impl Drop for Sidecar {
715    fn drop(&mut self) {
716        let _ = self.close();
717    }
718}
719
720/// Build the engine through the managed wrapper and return the executable it
721/// produced (from cargo's `compiler-artifact` message), never a stale copy.
722pub fn build_engine(
723    cwd: &Path,
724    command: &[String],
725    package: &str,
726    env: &[(String, String)],
727    tracker: &Tracker,
728) -> Result<PathBuf> {
729    let Some((program, rest)) = command.split_first() else {
730        return err("engine.build is empty");
731    };
732    let mut args = rest.to_vec();
733    if !args.iter().any(|a| a.starts_with("--message-format")) {
734        args.push("--message-format=json-render-diagnostics".into());
735    }
736    let out = run_owned(
737        program,
738        &args,
739        &RunOptions {
740            cwd: Some(cwd.to_path_buf()),
741            env: env.to_vec(),
742            timeout: Some(Duration::from_secs(45 * 60)),
743            label: "engine build".into(),
744            ..Default::default()
745        },
746        tracker,
747    )?;
748    if out.code != Some(0) {
749        return err(format!(
750            "engine build failed ({:?}):\n{}",
751            out.code,
752            crate::util::tail(&out.stderr, 4000)
753        ));
754    }
755    out.stdout
756        .lines()
757        .filter(|l| l.starts_with('{'))
758        .filter_map(|l| serde_json::from_str::<Value>(l).ok())
759        .filter(|m| m["reason"] == "compiler-artifact" && m["target"]["name"] == package)
760        .filter_map(|m| m["executable"].as_str().map(PathBuf::from))
761        .next_back()
762        .ok_or_else(|| {
763            Error(format!(
764                "build produced no executable for package {package}"
765            ))
766        })
767}
768
769#[cfg(test)]
770mod command_shape_tests {
771    use super::*;
772
773    #[test]
774    fn jobs_contract_is_the_default_frame() {
775        let f = command_frame("scan", json!({"a": 1}), false);
776        assert_eq!(
777            f,
778            json!({"type":"request","method":"scan","params":{"a":1}})
779        );
780        let ok = json!({"type":"response","id":1,"ok":true,"result":{"n":2}});
781        assert_eq!(command_outcome(&ok, false).unwrap(), json!({"n":2}));
782        let bad =
783            json!({"type":"response","id":1,"ok":false,"error":{"code":"nope","message":"m"}});
784        assert_eq!(command_outcome(&bad, false).unwrap_err().0, "nope: m");
785        // A response with no `ok` is not success.
786        assert!(command_outcome(&json!({"type":"response","id":1}), false).is_err());
787    }
788
789    #[test]
790    fn legacy_status_frames_keep_the_old_shape() {
791        let f = command_frame("scan", json!({"a": 1}), true);
792        assert_eq!(
793            f,
794            json!({"type":"request","method":{"method":"command","params":{"name":"scan","input":{"a":1}}}})
795        );
796        let ok = json!({"type":"response","id":1,"status":"ok","result":{"n":2}});
797        assert_eq!(command_outcome(&ok, true).unwrap(), json!({"n":2}));
798        let bad =
799            json!({"type":"response","id":1,"status":"err","error":{"code":"c","message":"m"}});
800        assert_eq!(command_outcome(&bad, true).unwrap_err().0, "c: m");
801    }
802}
803
804#[cfg(test)]
805mod frame_shape_tests {
806    use super::*;
807    use std::sync::mpsc::Sender;
808
809    /// Bytes the sidecar wrote to its stdin, shared with the test.
810    #[derive(Clone, Default)]
811    struct Wire(Arc<Mutex<Vec<u8>>>);
812
813    impl Write for Wire {
814        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
815            self.0.lock().unwrap().extend_from_slice(buf);
816            Ok(buf.len())
817        }
818        fn flush(&mut self) -> std::io::Result<()> {
819            Ok(())
820        }
821    }
822
823    impl Wire {
824        fn sent(&self) -> Vec<Value> {
825            let bytes = self.0.lock().unwrap().clone();
826            String::from_utf8(bytes)
827                .unwrap()
828                .lines()
829                .map(|l| serde_json::from_str(l).unwrap())
830                .collect()
831        }
832    }
833
834    /// An in-memory sidecar. `frames` are the engine's output in order: the hello first, then
835    /// any answers. The returned sender keeps the reader open, so silence is a timeout, not a
836    /// closed stream.
837    fn sidecar(frames: Vec<Value>) -> (Sidecar, Wire, Sender<Value>) {
838        let (tx, rx) = channel();
839        for f in frames {
840            tx.send(f).unwrap();
841        }
842        let wire = Wire::default();
843        let s = Sidecar {
844            child: None,
845            stdin: Some(Box::new(wire.clone())),
846            rx,
847            seq: 0,
848            hello: Value::Null,
849            pid: 0,
850            stderr: Arc::new(Mutex::new(StderrBuf::new(DEFAULT_STDERR_LIMIT))),
851            events: vec![],
852            events_dropped: 0,
853            event_limit: DEFAULT_EVENT_LIMIT,
854            watch: None,
855            legacy_status_frames: false,
856            detected_legacy: None,
857            frame_shape: None,
858            tracker: Tracker::new(),
859        }
860        .finish_start()
861        .unwrap();
862        (s, wire, tx)
863    }
864
865    fn legacy_hello() -> Value {
866        json!({"type": "hello", "rpc_version": 1, "build": "0.1.0", "pid": 7})
867    }
868    fn jobs_hello() -> Value {
869        json!({"type": "hello", "engine": "demo", "version": "1.0.0", "contract_version": 1})
870    }
871    /// A hello that names neither field.
872    fn bare_hello() -> Value {
873        json!({"type": "hello", "engine": "demo"})
874    }
875    fn legacy_ok(id: u64) -> Value {
876        json!({"type": "response", "status": "ok", "id": id, "result": {"n": 2}})
877    }
878    fn jobs_ok(id: u64) -> Value {
879        json!({"type": "response", "id": id, "ok": true, "result": {"n": 2}})
880    }
881    fn input() -> Value {
882        json!({"a": 1})
883    }
884    fn legacy_frame(id: u64) -> Value {
885        json!({"type": "request", "id": id,
886               "method": {"method": "command", "params": {"name": "scan", "input": {"a": 1}}}})
887    }
888    fn jobs_frame(id: u64) -> Value {
889        json!({"type": "request", "id": id, "method": "scan", "params": {"a": 1}})
890    }
891    const WAIT: Duration = Duration::from_secs(5);
892    const SILENT: Duration = Duration::from_millis(50);
893
894    #[test]
895    fn detection_reads_the_hello_fields() {
896        assert_eq!(detect_legacy_frames(&legacy_hello()), Some(true));
897        assert_eq!(detect_legacy_frames(&jobs_hello()), Some(false));
898        assert_eq!(detect_legacy_frames(&bare_hello()), None);
899    }
900
901    #[test]
902    fn legacy_hello_selects_legacy_frames_without_a_flag() {
903        let (mut s, wire, _tx) = sidecar(vec![legacy_hello(), legacy_ok(1)]);
904        assert_eq!(s.command("scan", input(), WAIT).unwrap(), json!({"n": 2}));
905        assert_eq!(wire.sent(), vec![legacy_frame(1)]);
906    }
907
908    #[test]
909    fn jobs_hello_selects_contract_frames() {
910        let (mut s, wire, _tx) = sidecar(vec![jobs_hello(), jobs_ok(1)]);
911        assert_eq!(s.command("scan", input(), WAIT).unwrap(), json!({"n": 2}));
912        assert_eq!(wire.sent(), vec![jobs_frame(1)]);
913    }
914
915    #[test]
916    fn per_command_flag_beats_a_jobs_hello_both_ways() {
917        let (mut s, wire, _tx) = sidecar(vec![jobs_hello(), legacy_ok(1), jobs_ok(2)]);
918        s.command_with("scan", input(), WAIT, Some(true)).unwrap();
919        s.command_with("scan", input(), WAIT, Some(false)).unwrap();
920        assert_eq!(wire.sent(), vec![legacy_frame(1), jobs_frame(2)]);
921    }
922
923    #[test]
924    fn per_command_flag_beats_a_legacy_hello() {
925        let (mut s, wire, _tx) = sidecar(vec![legacy_hello(), jobs_ok(1)]);
926        s.command_with("scan", input(), WAIT, Some(false)).unwrap();
927        assert_eq!(wire.sent(), vec![jobs_frame(1)]);
928    }
929
930    #[test]
931    fn sidecar_field_and_pin_beat_the_hello() {
932        let (mut s, wire, _tx) = sidecar(vec![jobs_hello(), legacy_ok(1), jobs_ok(2)]);
933        s.legacy_status_frames = true;
934        s.command("scan", input(), WAIT).unwrap();
935        s.set_frame_shape(Some(false));
936        s.command("scan", input(), WAIT).unwrap();
937        assert_eq!(wire.sent(), vec![legacy_frame(1), jobs_frame(2)]);
938    }
939
940    #[test]
941    fn sidecar_pin_beats_a_legacy_hello() {
942        let (mut s, wire, _tx) = sidecar(vec![legacy_hello(), jobs_ok(1)]);
943        s.set_frame_shape(Some(false));
944        s.command("scan", input(), WAIT).unwrap();
945        assert_eq!(wire.sent(), vec![jobs_frame(1)]);
946    }
947
948    #[test]
949    fn ambiguous_hello_and_silence_names_the_shape_and_the_switch() {
950        let (mut s, wire, _tx) = sidecar(vec![bare_hello()]);
951        let e = s.command("scan", input(), SILENT).unwrap_err().0;
952        assert!(
953            e.contains("did not answer the frame shape that was sent"),
954            "{e}"
955        );
956        assert!(e.contains("{type:\"request\", id, method, params}"), "{e}");
957        assert!(e.contains("legacy_status_frames"), "{e}");
958        assert!(e.contains("`scan`"), "{e}");
959        assert_eq!(wire.sent(), vec![jobs_frame(1)]);
960    }
961
962    #[test]
963    fn ambiguous_hello_with_a_frame_for_the_id_keeps_the_plain_timeout() {
964        let event = json!({"type": "event", "id": 1, "event": "progress"});
965        let (mut s, _wire, _tx) = sidecar(vec![bare_hello(), event]);
966        let e = s.command("scan", input(), SILENT).unwrap_err().0;
967        assert!(e.starts_with("sidecar timeout"), "{e}");
968        assert!(!e.contains("did not answer"), "{e}");
969    }
970
971    #[test]
972    fn explicit_shape_and_silence_keep_the_plain_timeout() {
973        let (mut s, _wire, _tx) = sidecar(vec![bare_hello()]);
974        let e = s
975            .command_with("scan", input(), SILENT, Some(false))
976            .unwrap_err()
977            .0;
978        assert!(e.starts_with("sidecar timeout"), "{e}");
979        assert!(!e.contains("did not answer"), "{e}");
980    }
981
982    /// `count` event frames; none answers request 1.
983    fn events(count: usize) -> Vec<Value> {
984        (0..count)
985            .map(|n| json!({"type": "event", "id": 0, "n": n}))
986            .collect()
987    }
988
989    #[test]
990    fn a_full_ring_keeps_the_newest_events_and_the_waiter_still_gets_its_answer() {
991        let mut frames = vec![bare_hello()];
992        frames.extend(events(10_000));
993        frames.push(jobs_ok(1));
994        let (mut s, _wire, _tx) = sidecar(frames);
995        let result = s.command("scan", input(), WAIT).unwrap();
996        assert_eq!(result, json!({"n": 2}));
997        let status = s.status();
998        // Every event is either held or counted as dropped.
999        assert_eq!(s.events.len() as u64 + status.events_dropped, 10_000);
1000        assert!(
1001            (DEFAULT_EVENT_LIMIT..2 * DEFAULT_EVENT_LIMIT).contains(&s.events.len()),
1002            "held {}",
1003            s.events.len()
1004        );
1005        assert_eq!(s.events.last().unwrap()["n"], json!(9_999));
1006        assert_eq!(status.events_buffered, s.events.len());
1007    }
1008
1009    #[test]
1010    fn the_event_limit_is_configurable_and_trims_at_once() {
1011        let mut frames = vec![bare_hello()];
1012        frames.extend(events(50));
1013        let (mut s, _wire, _tx) = sidecar(frames);
1014        assert!(s.command("scan", input(), SILENT).is_err());
1015        assert_eq!(s.events.len(), 50);
1016        s.set_event_limit(5);
1017        assert_eq!(s.events.len(), 5);
1018        assert_eq!(s.events[0]["n"], json!(45));
1019        assert_eq!(s.status().events_dropped, 45);
1020    }
1021
1022    #[test]
1023    fn an_answer_seen_before_the_ring_trimmed_it_is_still_reported_as_answered() {
1024        let early = json!({"type": "event", "id": 1, "event": "progress"});
1025        let mut frames = vec![bare_hello(), early];
1026        frames.extend(events(3 * DEFAULT_EVENT_LIMIT));
1027        let (mut s, _wire, _tx) = sidecar(frames);
1028        let brief = Duration::from_millis(500);
1029        let e = s.command("scan", input(), brief).unwrap_err().0;
1030        assert!(e.starts_with("sidecar timeout"), "{e}");
1031        assert!(!e.contains("did not answer"), "{e}");
1032        assert!(s.status().events_dropped > 0);
1033        assert!(s.events.iter().all(|f| f["id"] != json!(1)));
1034    }
1035
1036    #[test]
1037    fn stderr_keeps_its_last_bytes_on_a_line_boundary_and_says_what_it_dropped() {
1038        let mut buf = StderrBuf::new(21);
1039        buf.push(&format!("{}\n{}", "a".repeat(10), "b".repeat(20)));
1040        // The cut lands inside the first line; the newline just after it moves the cut past that line.
1041        assert_eq!(buf.retained(), "b".repeat(20));
1042        assert_eq!(buf.dropped, 11);
1043        assert_eq!(buf.bytes(), 20);
1044        assert!(buf
1045            .tail(1500)
1046            .starts_with("[11 bytes of earlier stderr dropped]\n"));
1047    }
1048
1049    #[test]
1050    fn stderr_stays_within_its_limit_however_much_is_written() {
1051        const LIMIT: usize = 4096;
1052        let mut buf = StderrBuf::new(LIMIT);
1053        let mut written = 0u64;
1054        for n in 0..20_000 {
1055            let line = format!("progress {n:08}\n");
1056            written += line.len() as u64;
1057            buf.push(&line);
1058            assert!(buf.bytes() <= LIMIT);
1059            assert!(buf.text.len() < 2 * LIMIT, "dead prefix was not compacted");
1060        }
1061        assert_eq!(buf.dropped + buf.bytes() as u64, written);
1062        assert!(buf.retained().starts_with("progress "));
1063        assert!(buf.retained().ends_with("progress 00019999\n"));
1064    }
1065
1066    #[test]
1067    fn stderr_cuts_never_split_a_character() {
1068        let mut buf = StderrBuf::new(7);
1069        buf.push(&"é".repeat(40));
1070        assert!(buf.retained().chars().all(|c| c == 'é'));
1071        assert!(buf.bytes() <= 7);
1072    }
1073}
1074
1075#[cfg(test)]
1076mod launch_guard_tests {
1077    use super::*;
1078    use crate::userdata::Rule;
1079
1080    fn target() -> EngineTarget {
1081        EngineTarget::new("/nonexistent/engine")
1082            .with_data_dir_env("APP_DATA")
1083            .forbid_args(&["--use-user-library"])
1084    }
1085
1086    fn refusal(r: Result<()>) -> String {
1087        r.unwrap_err().0
1088    }
1089
1090    #[test]
1091    fn a_launch_without_a_data_dir_is_refused_for_cli_and_sidecar_alike() {
1092        let t = target();
1093        let words = vec!["doctor".to_string()];
1094        let e = refusal(t.check_launch(&words, &CliOptions::default()));
1095        assert!(e.contains(&Rule::NoIsolatedDataDir.to_string()), "{e}");
1096        assert!(e.contains("/nonexistent/engine"), "{e}");
1097        let e = refusal(t.check_launch(&["--stdio".to_string()], &CliOptions::default()));
1098        assert!(e.contains(&Rule::NoIsolatedDataDir.to_string()), "{e}");
1099    }
1100
1101    #[test]
1102    fn a_data_dir_reaches_the_engine_only_through_a_declared_variable() {
1103        let dir = crate::storage::app_temp_dir().join("rkqa-engine-guard-never-created");
1104        let opts = CliOptions {
1105            data_dir: Some(dir),
1106            ..Default::default()
1107        };
1108        let words = vec!["doctor".to_string()];
1109        target().check_launch(&words, &opts).unwrap();
1110        let mut undeclared = target();
1111        undeclared.data_dir_env = None;
1112        let e = refusal(undeclared.check_launch(&words, &opts));
1113        assert!(e.contains(&Rule::NoIsolatedDataDir.to_string()), "{e}");
1114    }
1115
1116    #[test]
1117    fn a_forbidden_flag_is_refused_whatever_the_data_dir() {
1118        let dir = crate::storage::app_temp_dir().join("rkqa-engine-guard-never-created");
1119        let opts = CliOptions {
1120            data_dir: Some(dir),
1121            ..Default::default()
1122        };
1123        let words = vec!["doctor".to_string(), "--use-user-library".to_string()];
1124        let e = refusal(target().check_launch(&words, &opts));
1125        assert!(e.contains(&Rule::ForbiddenArgument.to_string()), "{e}");
1126        // The target's deny list is its own: a bare target forbids nothing.
1127        let mut bare = target();
1128        bare.forbidden_args.clear();
1129        bare.check_launch(&words, &opts).unwrap();
1130    }
1131
1132    #[test]
1133    fn the_probe_label_alone_never_opens_a_launch() {
1134        let t = target().allow_no_data_dir_for_refusal_probe();
1135        assert!(t.allow_no_data_dir_for_refusal_probe);
1136        // No HOME redirect in the launch environment: still refused (on Windows always).
1137        let e = refusal(t.check_launch(&["doctor".to_string()], &CliOptions::default()));
1138        assert!(e.contains(&Rule::ProbeUnavailable.to_string()), "{e}");
1139    }
1140}