Skip to main content

octave_ffi/
lib.rs

1//! Spawns and drives one persistent `octave-cli` subprocess and calls user-supplied,
2//! Octave-compatible `.m` functions once per resolved block-graph step -- the Octave-hosted
3//! counterpart to `pyblock_ffi`'s stateless [`pyblock_ffi::PyFunctionInstance`] contract, for
4//! people with legacy Octave-compatible `.m` scripts. See `general-simulator`'s own
5//! `book/dev-guide/src/octave-blocks.md` for the full design writeup (licensing rationale,
6//! measured costs, protocol design); this module doc comment covers the mechanics.
7//!
8//! ## Why a subprocess, never a linked library
9//!
10//! GNU Octave is GPLv3-licensed. Linking Octave's embedding library (`liboctinterp`) directly
11//! into this project's own permissively-licensed binaries would risk pulling them under GPL.
12//! **This crate never links against any Octave C/C++ library, and has no Octave crate/library
13//! as a build-time dependency at all** -- the only integration is spawning the separately
14//! installed `octave-cli` *binary* as a subprocess ("mere aggregation" under GPL, not linking --
15//! the same reason tools routinely shell out to `ffmpeg`/`gs` without inheriting their license).
16//! Unlike `pyblock_ffi` (which needs `pyo3`+`libpython` at *build* time, and is gated behind an
17//! optional Cargo feature for exactly that reason), this crate builds unconditionally on every
18//! platform and only fails at *runtime* -- with a clear [`OctaveError::NotFound`] -- if
19//! `octave-cli` isn't on `PATH` when a `kind=octfunc` block is actually used.
20//!
21//! ## Stateful blocks (`kind=octblock`)
22//!
23//! [`OctaveSession::call`]/[`OctaveSession::add_path`] above are the whole surface `kind=octfunc`
24//! (stateless) needs. [`OctaveSession::call_start`], [`OctaveSession::call_stateful`],
25//! [`OctaveSession::call_readonly_stateful`], and [`OctaveSession::rk4_step_xc_stateful`] extend
26//! this session with the stateful counterpart, `kind=octblock` -- see
27//! `general-simulator`'s own `book/dev-guide/src/octave-blocks.md` for the full per-instance
28//! opaque-state design (one shared `__gs_state` global struct in the Octave session itself,
29//! keyed by instance name, never serialized back to Rust) and the file-per-function contract
30//! this protocol calls into.
31//!
32//! ## One shared, persistent process
33//!
34//! [`OctaveSession`] wraps exactly one `octave-cli` child process, meant to be shared by every
35//! `kind=octfunc` block instance in a single simulation run -- this is the stateless/`pyfunc`
36//! case (no per-instance state to isolate), so there's nothing that needs a *separate* process
37//! per instance, and every instance calling into the same process is what makes a single
38//! `octave-cli` startup pay for the whole run instead of once per block. Measured on this
39//! machine (`octave-cli` 11.1.0): a cold-started fresh process per call costs roughly
40//! 165-220 ms *every* call (infeasible for a transient run with more than a handful of steps);
41//! a single persistent process costs that startup cost exactly once (~158 ms), then roughly
42//! 0.044 ms per call afterward. [`OctaveSession::spawn`] pays the startup cost immediately --
43//! callers wanting the "don't start Octave at all unless a netlist actually uses `kind=octfunc`"
44//! property (this crate's own recommended default) should construct their `OctaveSession`
45//! lazily, on first use, rather than eagerly for every run.
46//!
47//! ## The call protocol
48//!
49//! [`OctaveSession::add_path`] must be called once per unique directory containing a `.m` file
50//! this session will call into -- Octave requires the file to be on its own path and the file
51//! name to match the function name:
52//!
53//! ```text
54//! addpath('<absolute-dir-containing-the-.m-file>');
55//! ```
56//!
57//! [`OctaveSession::call`] passes every input as a literal numeric argument, never assigned into
58//! a named workspace variable -- this is what makes multiple block instances safely share one
59//! process: since nothing is ever written to the shared workspace, there is no possible
60//! variable-name collision between instances.
61//!
62//! ```text
63//! try
64//!   [__o0, __o1, ...] = <function>(<arg0>, <arg1>, ...);
65//!   printf("%.17g\n", __o0);
66//!   printf("%.17g\n", __o1);
67//!   ...
68//!   printf("@@GS_OCT_<call_id>@@\n");
69//! catch __err
70//!   printf("ERROR: %s\n", __err.message);
71//!   printf("@@GS_OCT_<call_id>@@\n");
72//! end
73//! ```
74//!
75//! Stdout is read line by line until the marker line appears. If the first line is
76//! `ERROR: ...`, the call failed on the Octave side -- surfaced as [`OctaveError::Runtime`], not
77//! parsed as a numeric output and not a panic. `call_id` is a per-process-lifetime incrementing
78//! counter, embedded in the marker specifically so a desync (a stray leftover line from a prior
79//! malformed exchange) is detectable rather than silently misread as the next call's own output.
80//!
81//! `%.17g` on the Octave side, together with [`str::parse::<f64>`] on the Rust side, round-trips
82//! a real fractional double bit-for-bit -- confirmed empirically this session against a value
83//! with a genuine precision tail (`0.1 + 0.2` prints as `0.30000000000000004` and parses back to
84//! the exact same bits), not just round numbers.
85//!
86//! A runtime error caught by the `try`/`catch` (e.g. calling a function with the wrong arity)
87//! reports cleanly via the `ERROR:` line, and **the session survives and keeps working
88//! correctly for subsequent calls** -- confirmed empirically this session; there is no need to
89//! respawn the process after a caught Octave-side error, and this crate never does.
90//!
91//! ## Process death mid-run
92//!
93//! If the persistent process dies (crash, killed, `octave-cli` itself panics) partway through a
94//! run, a blocking read on its stdout would hang forever without special handling. Every read in
95//! this crate detects EOF/a broken pipe and returns [`OctaveError::ProcessExited`] (carrying any
96//! stderr the process produced before dying) instead of hanging -- see
97//! [`tests/session.rs`](https://github.com) `process_dies_mid_run_reports_clean_error` for a
98//! test that actually kills the child process and confirms this path works, not just a read of
99//! the code.
100
101use std::io::{BufRead, BufReader, Write};
102use std::path::Path;
103use std::process::{Child, ChildStdin, Command, Stdio};
104use std::sync::mpsc;
105use std::thread;
106
107/// Every way calling into an [`OctaveSession`] can fail -- three genuinely different cases a
108/// caller needs to handle differently: `octave-cli` isn't installed at all (an actionable "go
109/// install Octave" message), the process died out from under this session (a bug in the user's
110/// own `.m` file crashing Octave itself, or something killing the process externally), or an
111/// ordinary Octave-side runtime error caught by this crate's own `try`/`catch` wrapper (a
112/// perfectly normal outcome -- wrong arity, a typo'd function name, a `.m` file that raises on
113/// bad input -- and one the session survives).
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum OctaveError {
116    /// `octave-cli` could not be spawned -- almost always because it isn't on `PATH`. `message`
117    /// is the underlying [`std::io::Error`]'s own text.
118    NotFound { message: String },
119    /// The `octave-cli` child process is no longer alive (its stdin/stdout pipe closed) --
120    /// detected as EOF on a blocking read that expected more output. `stderr` is everything the
121    /// process wrote to its own stderr before dying, if any (empty string if none was
122    /// captured), included because it is very often the only clue why Octave itself crashed.
123    ProcessExited { stderr: String },
124    /// The Octave side raised inside the `try`/`catch` this crate wraps every call in --
125    /// `message` is `err.message` from Octave's own caught exception object. The session is
126    /// still alive and safe to keep using after this.
127    Runtime { message: String },
128    /// Writing to the child process's stdin failed for a reason other than the process having
129    /// already exited (e.g. some other I/O failure) -- `message` is the underlying
130    /// [`std::io::Error`]'s own text.
131    Io { message: String },
132}
133
134impl std::fmt::Display for OctaveError {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        match self {
137            OctaveError::NotFound { message } => {
138                write!(
139                    f,
140                    "could not start octave-cli (is it installed and on PATH?): {message}"
141                )
142            }
143            OctaveError::ProcessExited { stderr } => {
144                if stderr.is_empty() {
145                    write!(f, "the octave-cli process exited unexpectedly")
146                } else {
147                    write!(
148                        f,
149                        "the octave-cli process exited unexpectedly; stderr: {stderr}"
150                    )
151                }
152            }
153            OctaveError::Runtime { message } => write!(f, "Octave raised: {message}"),
154            OctaveError::Io { message } => write!(f, "I/O error talking to octave-cli: {message}"),
155        }
156    }
157}
158
159impl std::error::Error for OctaveError {}
160
161/// Formats `x` as an Octave numeric literal that round-trips back to the exact same bits --
162/// [`f64`]'s own [`std::fmt::Display`] already produces the shortest decimal string that
163/// round-trips (confirmed empirically this session: `0.1 + 0.2` formats as
164/// `0.30000000000000004`, matching the value `%.17g` reads back on the Octave side), which is
165/// already valid Octave syntax for every finite value. `inf`/`-inf`/`NaN` are formatted as
166/// Octave's own `Inf`/`-Inf`/`NaN` literals, which [`f64`]'s `Display` does not produce
167/// unmodified (`inf`/`NaN` lowercase-`inf`, not directly valid as a bare Octave token in every
168/// context) -- special-cased here rather than left to chance.
169fn format_octave_literal(x: f64) -> String {
170    if x.is_nan() {
171        "NaN".to_string()
172    } else if x.is_infinite() {
173        if x > 0.0 {
174            "Inf".to_string()
175        } else {
176            "-Inf".to_string()
177        }
178    } else {
179        format!("{x}")
180    }
181}
182
183/// Formats `xs` as an Octave row-vector literal (`[v0, v1, ...]`, `[]` when empty) -- used only
184/// for the solver-owned `xc` continuous-state vector ([`OctaveSession::call_stateful`]/
185/// [`OctaveSession::call_readonly_stateful`]'s own `xc` parameter), the one piece of state this
186/// crate ever passes explicitly rather than leaving inside an instance's own opaque
187/// `__gs_state` slot -- see the module doc comment's "Per-instance state" section.
188fn format_octave_vector(xs: &[f64]) -> String {
189    format!(
190        "[{}]",
191        xs.iter()
192            .map(|x| format_octave_literal(*x))
193            .collect::<Vec<_>>()
194            .join(", ")
195    )
196}
197
198/// Shared tail of every stateful/readonly-stateful call: checks for the `ERROR: ` line
199/// [`OctaveSession::call`] itself already checks for, then validates the returned line count
200/// against `num_outputs` and parses each as `f64` -- exactly [`OctaveSession::call`]'s own tail,
201/// factored out so [`OctaveSession::call_stateful`]/[`OctaveSession::call_readonly_stateful`]
202/// don't duplicate it a second and third time; `call` itself is left untouched; nothing about
203/// its own behavior changed by this helper existing.
204fn parse_output_lines(
205    function: &str,
206    lines: &[String],
207    num_outputs: usize,
208) -> Result<Vec<f64>, OctaveError> {
209    if let Some(first) = lines.first() {
210        if let Some(message) = first.strip_prefix("ERROR: ") {
211            return Err(OctaveError::Runtime {
212                message: message.to_string(),
213            });
214        }
215    }
216    if lines.len() != num_outputs {
217        return Err(OctaveError::Runtime {
218            message: format!(
219                "expected {num_outputs} output line(s) from `{function}`, got {} (call \
220                 desynchronized, or the function printed unexpected output): {lines:?}",
221                lines.len()
222            ),
223        });
224    }
225    lines
226        .iter()
227        .map(|l| {
228            l.parse::<f64>().map_err(|_| OctaveError::Runtime {
229                message: format!("could not parse `{l}` as a f64 output of `{function}`"),
230            })
231        })
232        .collect()
233}
234
235/// Escapes `s` for embedding inside a single-quoted Octave string literal (`'...'`) -- Octave's
236/// own escape convention for a literal single quote inside a single-quoted string is to double
237/// it (`''`), the same convention SQL and several other languages use.
238fn escape_octave_single_quoted(s: &str) -> String {
239    s.replace('\'', "''")
240}
241
242/// Reads stdout, line by line, until the `@@GS_OCT_<call_id>@@` marker line for `call_id`
243/// appears -- returning every line read before it. Detects EOF (the process died) partway
244/// through and reports [`OctaveError::ProcessExited`], never blocking forever.
245fn read_until_marker(
246    stdout: &mut BufReader<std::process::ChildStdout>,
247    call_id: u64,
248    stderr_rx: &mpsc::Receiver<String>,
249) -> Result<Vec<String>, OctaveError> {
250    let marker = format!("@@GS_OCT_{call_id}@@");
251    let mut lines = Vec::new();
252    loop {
253        let mut line = String::new();
254        let n = stdout.read_line(&mut line).map_err(|e| OctaveError::Io {
255            message: e.to_string(),
256        })?;
257        if n == 0 {
258            // EOF: the process's stdout pipe closed, i.e. it died.
259            return Err(OctaveError::ProcessExited {
260                stderr: drain_stderr(stderr_rx),
261            });
262        }
263        let line = line.trim_end_matches(['\n', '\r']).to_string();
264        if line == marker {
265            return Ok(lines);
266        }
267        lines.push(line);
268    }
269}
270
271/// Collects whatever the background stderr-reader thread has captured so far, without blocking
272/// (used only once a process is already known to have exited, so there is nothing further to
273/// wait for).
274fn drain_stderr(rx: &mpsc::Receiver<String>) -> String {
275    let mut out = String::new();
276    while let Ok(chunk) = rx.try_recv() {
277        out.push_str(&chunk);
278    }
279    out
280}
281
282/// One persistent `octave-cli` process, plus a per-process-lifetime call-id counter used to
283/// frame each call's own output (see the module doc comment, "The call protocol"). Construct
284/// with [`OctaveSession::spawn`], call [`Self::add_path`] once per unique directory a `.m` file
285/// lives in, then [`Self::call`] as many times as needed. Dropping this value kills the child
286/// process (see [`Drop`]).
287pub struct OctaveSession {
288    child: Child,
289    stdin: ChildStdin,
290    stdout: BufReader<std::process::ChildStdout>,
291    stderr_rx: mpsc::Receiver<String>,
292    next_call_id: u64,
293}
294
295impl std::fmt::Debug for OctaveSession {
296    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297        f.debug_struct("OctaveSession")
298            .field("pid", &self.child.id())
299            .field("next_call_id", &self.next_call_id)
300            .finish()
301    }
302}
303
304impl OctaveSession {
305    /// Spawns `octave-cli` (looked up on `PATH`, exactly the way a shell would) with
306    /// interactive/GUI/startup-file behavior suppressed, ready to accept commands on stdin. Pays
307    /// Octave's own real startup cost immediately (measured ~158 ms on this machine) -- callers
308    /// wanting to avoid that cost for a run that might never actually need `kind=octfunc` should
309    /// only call this once the first `octfunc` block is actually encountered, not eagerly for
310    /// every run (see the module doc comment).
311    pub fn spawn() -> Result<Self, OctaveError> {
312        Self::spawn_with_command(Path::new("octave-cli"))
313    }
314
315    /// The same as [`Self::spawn`], but with the executable name/path given explicitly rather
316    /// than hardcoded to `"octave-cli"` -- exists so this crate's own test suite can exercise
317    /// [`OctaveError::NotFound`] deterministically (spawning a name that is guaranteed not to
318    /// exist), without needing to actually tamper with `PATH`. Not expected to be useful outside
319    /// of tests; `octave-cli` on `PATH` (via [`Self::spawn`]) is the only supported way to reach
320    /// a real Octave.
321    pub fn spawn_with_command(command: &Path) -> Result<Self, OctaveError> {
322        let mut child = Command::new(command)
323            // --no-gui: never try to open a graphical window.
324            // --norc: don't read the user's own ~/.octaverc -- a session used by this crate
325            //   should behave identically regardless of whichever machine it runs on.
326            // --quiet: suppress the startup banner, which would otherwise show up as bogus
327            //   leading lines on stdout before any real call is even made.
328            //
329            // Deliberately *not* passing --interactive: confirmed empirically this session that
330            // with stdin as a genuine pipe (never a tty), plain `octave-cli` already reads and
331            // executes statements as they arrive without waiting for stdin to close, streaming
332            // fine across many sequential writes over the process's whole lifetime -- exactly
333            // the persistent-session behavior this crate needs. --interactive additionally
334            // prints an `octave:N>` prompt to stdout before each statement, which would corrupt
335            // this crate's own line-oriented protocol; there is no flag to keep --interactive's
336            // "never exit at EOF" behavior without also printing prompts, so it is simply not
337            // needed here at all.
338            .args(["--no-gui", "--norc", "--quiet"])
339            .stdin(Stdio::piped())
340            .stdout(Stdio::piped())
341            .stderr(Stdio::piped())
342            .spawn()
343            .map_err(|e| OctaveError::NotFound {
344                message: e.to_string(),
345            })?;
346
347        let stdin = child.stdin.take().expect("stdin was piped");
348        let stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
349        let stderr = child.stderr.take().expect("stderr was piped");
350
351        // Read stderr on a background thread: without this, a call that writes enough to
352        // stderr (a warning, a caught-but-verbose error) could fill the OS pipe buffer and
353        // deadlock this process against the child, since nothing else here ever reads stderr
354        // synchronously. The channel just accumulates chunks for `drain_stderr` to collect once
355        // (and only once) the process is known to have died.
356        let (tx, rx) = mpsc::channel();
357        thread::spawn(move || {
358            let mut reader = BufReader::new(stderr);
359            loop {
360                let mut line = String::new();
361                match reader.read_line(&mut line) {
362                    Ok(0) | Err(_) => break,
363                    Ok(_) => {
364                        if tx.send(line).is_err() {
365                            break;
366                        }
367                    }
368                }
369            }
370        });
371
372        Ok(OctaveSession {
373            child,
374            stdin,
375            stdout,
376            stderr_rx: rx,
377            next_call_id: 0,
378        })
379    }
380
381    /// Sends `addpath('<dir>')` to this session -- required once per unique directory containing
382    /// a `.m` file this session will call into (Octave requires the file to be on its own path).
383    /// Calling this more than once for the same directory is harmless (Octave's own `addpath`
384    /// is idempotent about duplicate entries); callers are not required to deduplicate
385    /// themselves.
386    pub fn add_path(&mut self, dir: &Path) -> Result<(), OctaveError> {
387        let call_id = self.next_call_id;
388        self.next_call_id += 1;
389        let escaped = escape_octave_single_quoted(&dir.to_string_lossy());
390        let script = format!(
391            "addpath('{escaped}');\nprintf(\"@@GS_OCT_{call_id}@@\\n\");\nfflush(stdout);\n"
392        );
393        self.write_and_flush(&script)?;
394        read_until_marker(&mut self.stdout, call_id, &self.stderr_rx)?;
395        Ok(())
396    }
397
398    /// Calls `function`, an Octave function already on this session's own path (see
399    /// [`Self::add_path`]), with `inputs` as literal positional numeric arguments (never
400    /// assigned into a named workspace variable -- see the module doc comment for why this is
401    /// what makes multiple block instances safely share one session), expecting exactly
402    /// `num_outputs` scalar return values. `Ok` on success; [`OctaveError::Runtime`] if the
403    /// call raised inside Octave's own `try`/`catch` (the session remains usable afterward);
404    /// [`OctaveError::ProcessExited`] if the process died during this call.
405    pub fn call(
406        &mut self,
407        function: &str,
408        inputs: &[f64],
409        num_outputs: usize,
410    ) -> Result<Vec<f64>, OctaveError> {
411        let call_id = self.next_call_id;
412        self.next_call_id += 1;
413
414        let args: Vec<String> = inputs.iter().map(|x| format_octave_literal(*x)).collect();
415        let out_vars: Vec<String> = (0..num_outputs).map(|i| format!("__o{i}")).collect();
416
417        let mut script = String::new();
418        script.push_str("try\n  ");
419        if num_outputs == 0 {
420            script.push_str(&format!("{function}({});\n", args.join(", ")));
421        } else if num_outputs == 1 {
422            script.push_str(&format!(
423                "{} = {function}({});\n",
424                out_vars[0],
425                args.join(", ")
426            ));
427        } else {
428            script.push_str(&format!(
429                "[{}] = {function}({});\n",
430                out_vars.join(", "),
431                args.join(", ")
432            ));
433        }
434        for v in &out_vars {
435            script.push_str(&format!("  printf(\"%.17g\\n\", {v});\n"));
436        }
437        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
438        script.push_str("catch __err\n");
439        script.push_str("  printf(\"ERROR: %s\\n\", __err.message);\n");
440        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
441        script.push_str("end\n");
442        script.push_str("fflush(stdout);\n");
443
444        self.write_and_flush(&script)?;
445        let lines = read_until_marker(&mut self.stdout, call_id, &self.stderr_rx)?;
446
447        if let Some(first) = lines.first() {
448            if let Some(message) = first.strip_prefix("ERROR: ") {
449                return Err(OctaveError::Runtime {
450                    message: message.to_string(),
451                });
452            }
453        }
454
455        if lines.len() != num_outputs {
456            // A desync: either the marker's own call_id protected us from misreading a *later*
457            // call's output as this one's, but here the *right* call's own output line count
458            // itself doesn't match what was asked for -- e.g. the function itself printed extra
459            // output, or genuinely returned fewer values than requested and Octave still didn't
460            // raise. Surfaced as a Runtime error rather than silently truncating/padding.
461            return Err(OctaveError::Runtime {
462                message: format!(
463                    "expected {num_outputs} output line(s) from `{function}`, got \
464                     {} (call desynchronized, or the function printed unexpected output): {lines:?}",
465                    lines.len()
466                ),
467            });
468        }
469
470        lines
471            .iter()
472            .map(|l| {
473                l.parse::<f64>().map_err(|_| OctaveError::Runtime {
474                    message: format!("could not parse `{l}` as a f64 output of `{function}`"),
475                })
476            })
477            .collect()
478    }
479
480    /// Initializes `instance`'s own opaque state slot in the shared `__gs_state` global struct
481    /// by calling `<function>_start()` (no arguments) and storing the result into
482    /// `__gs_state.('<instance>')` -- the stateful counterpart to [`Self::call`], and the first
483    /// call any `kind=octblock` instance must make before [`Self::call_stateful`]/
484    /// [`Self::call_readonly_stateful`] can read a meaningful slot for it. Per-instance
485    /// isolation is purely a property of `instance` being a distinct struct field name in one
486    /// shared global -- two instances calling the *same* `function` with different `instance`
487    /// names never see each other's state, confirmed empirically (see `tests/session.rs`'s own
488    /// `two_instances_of_same_stateful_function_do_not_contaminate_each_others_state`).
489    pub fn call_start(&mut self, function: &str, instance: &str) -> Result<(), OctaveError> {
490        let call_id = self.next_call_id;
491        self.next_call_id += 1;
492        let inst = escape_octave_single_quoted(instance);
493
494        let mut script = String::new();
495        script.push_str("global __gs_state;\n");
496        script.push_str("try\n");
497        script.push_str(&format!("  __gs_state.('{inst}') = {function}_start();\n"));
498        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
499        script.push_str("catch __err\n");
500        script.push_str("  printf(\"ERROR: %s\\n\", __err.message);\n");
501        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
502        script.push_str("end\n");
503        script.push_str("fflush(stdout);\n");
504
505        self.write_and_flush(&script)?;
506        let lines = read_until_marker(&mut self.stdout, call_id, &self.stderr_rx)?;
507        if let Some(first) = lines.first() {
508            if let Some(message) = first.strip_prefix("ERROR: ") {
509                return Err(OctaveError::Runtime {
510                    message: message.to_string(),
511                });
512            }
513        }
514        Ok(())
515    }
516
517    /// Calls `function(__gs_state.('<instance>'), <args...>[, <xc>])`, expecting `function` to
518    /// return `num_outputs + 1` values: the instance's own *new* state first, then
519    /// `num_outputs` plain numeric outputs -- `[new_state, y0, y1, ...] = function(state, ...)`,
520    /// exactly the shape the file-per-function contract's own `<function>`/`<function>_output_xc`/
521    /// `<function>_update` all share (see `book/dev-guide/src/octave-blocks.md`). `xc`, when
522    /// given, is appended as one literal Octave vector argument after `args` (e.g. `[1, 2, 3]`),
523    /// never flattened into separate scalar arguments -- this is the one piece of *solver*-owned
524    /// state that crosses the pipe explicitly rather than living in the instance's own opaque
525    /// slot.
526    ///
527    /// `__gs_state.('<instance>')` is only overwritten if `function` returns successfully --
528    /// Octave never performs a multi-value assignment's left-hand-side writes if evaluating the
529    /// right-hand side raises, so a caught error here leaves the instance's previous state slot
530    /// completely untouched (confirmed empirically; see `tests/session.rs`'s own
531    /// `stateful_call_that_errors_does_not_corrupt_instance_state`) -- no special-casing needed
532    /// on this crate's own side to get that guarantee.
533    pub fn call_stateful(
534        &mut self,
535        function: &str,
536        instance: &str,
537        args: &[f64],
538        xc: Option<&[f64]>,
539        num_outputs: usize,
540    ) -> Result<Vec<f64>, OctaveError> {
541        let call_id = self.next_call_id;
542        self.next_call_id += 1;
543        let inst = escape_octave_single_quoted(instance);
544
545        let mut call_args: Vec<String> = vec![format!("__gs_state.('{inst}')")];
546        call_args.extend(args.iter().map(|x| format_octave_literal(*x)));
547        if let Some(xc) = xc {
548            call_args.push(format_octave_vector(xc));
549        }
550
551        let out_vars: Vec<String> = (0..num_outputs).map(|i| format!("__o{i}")).collect();
552        let lhs = if out_vars.is_empty() {
553            format!("__gs_state.('{inst}')")
554        } else {
555            format!("[__gs_state.('{inst}'), {}]", out_vars.join(", "))
556        };
557
558        let mut script = String::new();
559        script.push_str("global __gs_state;\n");
560        script.push_str("try\n");
561        script.push_str(&format!(
562            "  {lhs} = {function}({});\n",
563            call_args.join(", ")
564        ));
565        for v in &out_vars {
566            script.push_str(&format!("  printf(\"%.17g\\n\", {v});\n"));
567        }
568        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
569        script.push_str("catch __err\n");
570        script.push_str("  printf(\"ERROR: %s\\n\", __err.message);\n");
571        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
572        script.push_str("end\n");
573        script.push_str("fflush(stdout);\n");
574
575        self.write_and_flush(&script)?;
576        let lines = read_until_marker(&mut self.stdout, call_id, &self.stderr_rx)?;
577        parse_output_lines(function, &lines, num_outputs)
578    }
579
580    /// Calls `function(__gs_state.('<instance>'), <args...>[, <xc>])`, expecting `function` to
581    /// return exactly `num_outputs` plain numeric values -- **the instance's own state slot is
582    /// read, but never reassigned** (there is no state variable on the left-hand side at all),
583    /// unlike [`Self::call_stateful`]. This is the shape `<function>_derivative` (pure -- must
584    /// not mutate state) and `<function>_next_sample_hit` both share.
585    pub fn call_readonly_stateful(
586        &mut self,
587        function: &str,
588        instance: &str,
589        args: &[f64],
590        xc: Option<&[f64]>,
591        num_outputs: usize,
592    ) -> Result<Vec<f64>, OctaveError> {
593        let call_id = self.next_call_id;
594        self.next_call_id += 1;
595        let inst = escape_octave_single_quoted(instance);
596
597        let mut call_args: Vec<String> = vec![format!("__gs_state.('{inst}')")];
598        call_args.extend(args.iter().map(|x| format_octave_literal(*x)));
599        if let Some(xc) = xc {
600            call_args.push(format_octave_vector(xc));
601        }
602
603        let out_vars: Vec<String> = (0..num_outputs).map(|i| format!("__o{i}")).collect();
604
605        let mut script = String::new();
606        script.push_str("global __gs_state;\n");
607        script.push_str("try\n  ");
608        if out_vars.is_empty() {
609            script.push_str(&format!("{function}({});\n", call_args.join(", ")));
610        } else if out_vars.len() == 1 {
611            script.push_str(&format!(
612                "{} = {function}({});\n",
613                out_vars[0],
614                call_args.join(", ")
615            ));
616        } else {
617            script.push_str(&format!(
618                "[{}] = {function}({});\n",
619                out_vars.join(", "),
620                call_args.join(", ")
621            ));
622        }
623        for v in &out_vars {
624            script.push_str(&format!("  printf(\"%.17g\\n\", {v});\n"));
625        }
626        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
627        script.push_str("catch __err\n");
628        script.push_str("  printf(\"ERROR: %s\\n\", __err.message);\n");
629        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
630        script.push_str("end\n");
631        script.push_str("fflush(stdout);\n");
632
633        self.write_and_flush(&script)?;
634        let lines = read_until_marker(&mut self.stdout, call_id, &self.stderr_rx)?;
635        parse_output_lines(function, &lines, num_outputs)
636    }
637
638    /// RK4-integrates `xc` forward by `dt`, holding `args` fixed across all four stages and
639    /// calling [`Self::call_readonly_stateful`] against `<function>_derivative` up to four
640    /// times (`k1..k4`) -- the direct Octave-hosted analog of
641    /// `cscript_ffi::CScriptInstance::rk4_step_xc`/`pyblock_ffi`'s own RK4 stepper, same
642    /// zero-order-hold convention (`args`, i.e. `t`/`dt`/inputs, held fixed across all four
643    /// stages). `derivative_function` is expected to already carry the `_derivative` suffix
644    /// (callers pass `"<function>_derivative"`, matching the file-per-function contract).
645    pub fn rk4_step_xc_stateful(
646        &mut self,
647        derivative_function: &str,
648        instance: &str,
649        xc: &[f64],
650        args: &[f64],
651        dt: f64,
652    ) -> Result<Vec<f64>, OctaveError> {
653        let add = |a: &[f64], b: &[f64], scale: f64| -> Vec<f64> {
654            a.iter().zip(b).map(|(ai, bi)| ai + scale * bi).collect()
655        };
656        let n = xc.len();
657        let k1 = self.call_readonly_stateful(derivative_function, instance, args, Some(xc), n)?;
658        let k2 = self.call_readonly_stateful(
659            derivative_function,
660            instance,
661            args,
662            Some(&add(xc, &k1, dt / 2.0)),
663            n,
664        )?;
665        let k3 = self.call_readonly_stateful(
666            derivative_function,
667            instance,
668            args,
669            Some(&add(xc, &k2, dt / 2.0)),
670            n,
671        )?;
672        let k4 = self.call_readonly_stateful(
673            derivative_function,
674            instance,
675            args,
676            Some(&add(xc, &k3, dt)),
677            n,
678        )?;
679        Ok((0..n)
680            .map(|i| xc[i] + (dt / 6.0) * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
681            .collect())
682    }
683
684    /// Serializes `instance`'s own `__gs_state.('<instance>')` slot to bytes, for a checkpoint:
685    /// the slot is copied into a scratch variable, written with Octave's own
686    /// `save('-binary', ...)` to a temporary file, and that file is read back here and deleted
687    /// -- the same call protocol every other method uses, so a failed `save` (an unset slot, a
688    /// value Octave's binary format cannot hold) surfaces as [`OctaveError::Runtime`] and the
689    /// session survives. Octave's binary format stores doubles as their exact bits, which is
690    /// what makes a resumed run bit-identical. No author-side opt-in is needed, unlike
691    /// `cscript`'s own state contract: whatever `<function>_start` returned is what gets saved.
692    ///
693    /// The temporary file lives in [`std::env::temp_dir`] under a name unique to this process
694    /// and call, and is removed before this returns -- on the error path too.
695    pub fn save_state(&mut self, instance: &str) -> Result<Vec<u8>, OctaveError> {
696        let call_id = self.next_call_id;
697        self.next_call_id += 1;
698        let path = self.state_temp_path(call_id);
699        let inst = escape_octave_single_quoted(instance);
700        let file = escape_octave_single_quoted(&path.to_string_lossy());
701
702        let mut script = String::new();
703        script.push_str("global __gs_state;\n");
704        script.push_str("try\n");
705        script.push_str(&format!("  __gs_ckpt = __gs_state.('{inst}');\n"));
706        script.push_str(&format!("  save('-binary', '{file}', '__gs_ckpt');\n"));
707        script.push_str("  clear __gs_ckpt;\n");
708        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
709        script.push_str("catch __err\n");
710        script.push_str("  printf(\"ERROR: %s\\n\", __err.message);\n");
711        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
712        script.push_str("end\n");
713        script.push_str("fflush(stdout);\n");
714
715        let result = self
716            .write_and_flush(&script)
717            .and_then(|()| read_until_marker(&mut self.stdout, call_id, &self.stderr_rx))
718            .and_then(|lines| {
719                if let Some(message) = lines.first().and_then(|l| l.strip_prefix("ERROR: ")) {
720                    return Err(OctaveError::Runtime {
721                        message: message.to_string(),
722                    });
723                }
724                std::fs::read(&path).map_err(|e| OctaveError::Io {
725                    message: format!(
726                        "could not read the state file Octave saved at {}: {e}",
727                        path.display()
728                    ),
729                })
730            });
731        let _ = std::fs::remove_file(&path);
732        result
733    }
734
735    /// The inverse of [`Self::save_state`]: writes `bytes` to a temporary file, `load`s it in
736    /// the session, and assigns the loaded value into `__gs_state.('<instance>')` -- replacing
737    /// whatever [`Self::call_start`] put there at construction. The file is removed before this
738    /// returns, on every path.
739    pub fn load_state(&mut self, instance: &str, bytes: &[u8]) -> Result<(), OctaveError> {
740        let call_id = self.next_call_id;
741        self.next_call_id += 1;
742        let path = self.state_temp_path(call_id);
743        std::fs::write(&path, bytes).map_err(|e| OctaveError::Io {
744            message: format!(
745                "could not write the state file for Octave at {}: {e}",
746                path.display()
747            ),
748        })?;
749        let inst = escape_octave_single_quoted(instance);
750        let file = escape_octave_single_quoted(&path.to_string_lossy());
751
752        let mut script = String::new();
753        script.push_str("global __gs_state;\n");
754        script.push_str("try\n");
755        script.push_str(&format!("  __gs_loaded = load('-binary', '{file}');\n"));
756        script.push_str(&format!(
757            "  __gs_state.('{inst}') = __gs_loaded.__gs_ckpt;\n"
758        ));
759        script.push_str("  clear __gs_loaded;\n");
760        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
761        script.push_str("catch __err\n");
762        script.push_str("  printf(\"ERROR: %s\\n\", __err.message);\n");
763        script.push_str(&format!("  printf(\"@@GS_OCT_{call_id}@@\\n\");\n"));
764        script.push_str("end\n");
765        script.push_str("fflush(stdout);\n");
766
767        let result = self
768            .write_and_flush(&script)
769            .and_then(|()| read_until_marker(&mut self.stdout, call_id, &self.stderr_rx))
770            .and_then(|lines| {
771                if let Some(message) = lines.first().and_then(|l| l.strip_prefix("ERROR: ")) {
772                    return Err(OctaveError::Runtime {
773                        message: message.to_string(),
774                    });
775                }
776                Ok(())
777            });
778        let _ = std::fs::remove_file(&path);
779        result
780    }
781
782    /// Where [`Self::save_state`]/[`Self::load_state`] put their one short-lived file: unique
783    /// per host process and per call, so two sessions (two test binaries, two runs) never
784    /// collide on the same name.
785    fn state_temp_path(&self, call_id: u64) -> std::path::PathBuf {
786        std::env::temp_dir().join(format!(
787            "gs-octblock-state-{}-{}-{call_id}.bin",
788            std::process::id(),
789            self.child.id()
790        ))
791    }
792
793    /// Kills the underlying `octave-cli` process immediately (`SIGKILL`, not a graceful
794    /// shutdown), simulating a crash for [`Self`]'s own EOF/broken-pipe handling to be tested
795    /// against. Exists purely so this crate's own test suite can exercise
796    /// [`OctaveError::ProcessExited`] by actually killing a live process (see
797    /// `tests/session.rs`'s own `process_dies_mid_run_reports_clean_error_instead_of_hanging`),
798    /// rather than only reviewing the read/EOF-handling code by eye. Not useful outside of
799    /// tests -- an ordinary caller wanting to stop a session should simply [`drop`] it.
800    pub fn kill_for_test(&mut self) {
801        let _ = self.child.kill();
802        let _ = self.child.wait();
803    }
804
805    fn write_and_flush(&mut self, script: &str) -> Result<(), OctaveError> {
806        self.stdin
807            .write_all(script.as_bytes())
808            .and_then(|()| self.stdin.flush())
809            .map_err(|e| {
810                // A closed pipe here means the process already died; report it the same way a
811                // failed read would, rather than as a generic Io error, so callers see one
812                // consistent case for "the process is gone" regardless of which direction of
813                // I/O first noticed it.
814                if e.kind() == std::io::ErrorKind::BrokenPipe {
815                    OctaveError::ProcessExited {
816                        stderr: drain_stderr(&self.stderr_rx),
817                    }
818                } else {
819                    OctaveError::Io {
820                        message: e.to_string(),
821                    }
822                }
823            })
824    }
825}
826
827impl Drop for OctaveSession {
828    fn drop(&mut self) {
829        // Best-effort: ask nicely first (closing stdin makes an interactive octave-cli exit on
830        // its own), then make sure it's actually gone. Errors here are deliberately swallowed --
831        // there is nothing a caller could usefully do with a failure to tear down a process
832        // that's going away regardless.
833        let _ = self.child.kill();
834        let _ = self.child.wait();
835    }
836}