Skip to main content

Crate octave_ffi

Crate octave_ffi 

Source
Expand description

Spawns and drives one persistent octave-cli subprocess and calls user-supplied, Octave-compatible .m functions once per resolved block-graph step – the Octave-hosted counterpart to pyblock_ffi’s stateless [pyblock_ffi::PyFunctionInstance] contract, for people with legacy Octave-compatible .m scripts. See general-simulator’s own book/dev-guide/src/octave-blocks.md for the full design writeup (licensing rationale, measured costs, protocol design); this module doc comment covers the mechanics.

§Why a subprocess, never a linked library

GNU Octave is GPLv3-licensed. Linking Octave’s embedding library (liboctinterp) directly into this project’s own permissively-licensed binaries would risk pulling them under GPL. This crate never links against any Octave C/C++ library, and has no Octave crate/library as a build-time dependency at all – the only integration is spawning the separately installed octave-cli binary as a subprocess (“mere aggregation” under GPL, not linking – the same reason tools routinely shell out to ffmpeg/gs without inheriting their license). Unlike pyblock_ffi (which needs pyo3+libpython at build time, and is gated behind an optional Cargo feature for exactly that reason), this crate builds unconditionally on every platform and only fails at runtime – with a clear OctaveError::NotFound – if octave-cli isn’t on PATH when a kind=octfunc block is actually used.

§Stateful blocks (kind=octblock)

OctaveSession::call/OctaveSession::add_path above are the whole surface kind=octfunc (stateless) needs. OctaveSession::call_start, OctaveSession::call_stateful, OctaveSession::call_readonly_stateful, and OctaveSession::rk4_step_xc_stateful extend this session with the stateful counterpart, kind=octblock – see general-simulator’s own book/dev-guide/src/octave-blocks.md for the full per-instance opaque-state design (one shared __gs_state global struct in the Octave session itself, keyed by instance name, never serialized back to Rust) and the file-per-function contract this protocol calls into.

§One shared, persistent process

OctaveSession wraps exactly one octave-cli child process, meant to be shared by every kind=octfunc block instance in a single simulation run – this is the stateless/pyfunc case (no per-instance state to isolate), so there’s nothing that needs a separate process per instance, and every instance calling into the same process is what makes a single octave-cli startup pay for the whole run instead of once per block. Measured on this machine (octave-cli 11.1.0): a cold-started fresh process per call costs roughly 165-220 ms every call (infeasible for a transient run with more than a handful of steps); a single persistent process costs that startup cost exactly once (~158 ms), then roughly 0.044 ms per call afterward. OctaveSession::spawn pays the startup cost immediately – callers wanting the “don’t start Octave at all unless a netlist actually uses kind=octfunc” property (this crate’s own recommended default) should construct their OctaveSession lazily, on first use, rather than eagerly for every run.

§The call protocol

OctaveSession::add_path must be called once per unique directory containing a .m file this session will call into – Octave requires the file to be on its own path and the file name to match the function name:

addpath('<absolute-dir-containing-the-.m-file>');

OctaveSession::call passes every input as a literal numeric argument, never assigned into a named workspace variable – this is what makes multiple block instances safely share one process: since nothing is ever written to the shared workspace, there is no possible variable-name collision between instances.

try
  [__o0, __o1, ...] = <function>(<arg0>, <arg1>, ...);
  printf("%.17g\n", __o0);
  printf("%.17g\n", __o1);
  ...
  printf("@@GS_OCT_<call_id>@@\n");
catch __err
  printf("ERROR: %s\n", __err.message);
  printf("@@GS_OCT_<call_id>@@\n");
end

Stdout is read line by line until the marker line appears. If the first line is ERROR: ..., the call failed on the Octave side – surfaced as OctaveError::Runtime, not parsed as a numeric output and not a panic. call_id is a per-process-lifetime incrementing counter, embedded in the marker specifically so a desync (a stray leftover line from a prior malformed exchange) is detectable rather than silently misread as the next call’s own output.

%.17g on the Octave side, together with str::parse::<f64> on the Rust side, round-trips a real fractional double bit-for-bit – confirmed empirically this session against a value with a genuine precision tail (0.1 + 0.2 prints as 0.30000000000000004 and parses back to the exact same bits), not just round numbers.

A runtime error caught by the try/catch (e.g. calling a function with the wrong arity) reports cleanly via the ERROR: line, and the session survives and keeps working correctly for subsequent calls – confirmed empirically this session; there is no need to respawn the process after a caught Octave-side error, and this crate never does.

§Process death mid-run

If the persistent process dies (crash, killed, octave-cli itself panics) partway through a run, a blocking read on its stdout would hang forever without special handling. Every read in this crate detects EOF/a broken pipe and returns OctaveError::ProcessExited (carrying any stderr the process produced before dying) instead of hanging – see tests/session.rs process_dies_mid_run_reports_clean_error for a test that actually kills the child process and confirms this path works, not just a read of the code.

Structs§

OctaveSession
One persistent octave-cli process, plus a per-process-lifetime call-id counter used to frame each call’s own output (see the module doc comment, “The call protocol”). Construct with OctaveSession::spawn, call Self::add_path once per unique directory a .m file lives in, then Self::call as many times as needed. Dropping this value kills the child process (see Drop).

Enums§

OctaveError
Every way calling into an OctaveSession can fail – three genuinely different cases a caller needs to handle differently: octave-cli isn’t installed at all (an actionable “go install Octave” message), the process died out from under this session (a bug in the user’s own .m file crashing Octave itself, or something killing the process externally), or an ordinary Octave-side runtime error caught by this crate’s own try/catch wrapper (a perfectly normal outcome – wrong arity, a typo’d function name, a .m file that raises on bad input – and one the session survives).