Skip to main content

arb/
actor.rs

1//! Actor system — Akka-style message-passing concurrency for arb.
2//!
3//! An `actor NAME(state) { on MSG(p…) { … } }` declaration compiles to an
4//! [`ActorDef`]: a named, single-`state` scalar behavior with one handler per
5//! message. Handlers run arb expressions (lowered to fusevm, same core as
6//! `map`/`where`/`calc`) over `state`, the message parameters, and any locals
7//! they assign; a `reply EXPR` sends a value back to an `ask`/`via` caller.
8//!
9//! The runtime is real OS threads with `mpsc` mailboxes — one thread per spawned
10//! actor, blocking on its receiver:
11//!   * [`ActorSystem::spawn`] starts an actor; its [`ActorRef`] holds the sender.
12//!   * [`ActorRef::send`] is *tell* (fire-and-forget).
13//!   * [`ActorRef::ask`] is *ask* (posts a one-shot reply channel, blocks for it).
14//!   * [`ActorSystem::pool`] is a supervised round-robin pool; a worker whose
15//!     mailbox has died (thread gone) is respawned on the next dispatch.
16//!
17//! [`run_via`] is the pipeline-facing consumer: it fans a stream of scalars
18//! across a pool in parallel (`source .out { in; via NAME * 8 }`), each line
19//! becoming a `job(x)` ask whose reply is the output line, order preserved.
20
21use std::collections::HashMap;
22use std::sync::mpsc::{self, Receiver, Sender};
23use std::sync::{Arc, Mutex};
24use std::thread::JoinHandle;
25
26use crate::expr::{self, Expr};
27
28/// One statement in a handler body: assign a variable, or reply to the caller.
29#[derive(Debug, Clone)]
30pub enum Stmt {
31    /// `var = EXPR` — set `state`, a parameter, or a local to the value of EXPR.
32    Assign(String, Expr),
33    /// `reply EXPR` — send EXPR's value back on the message's reply channel.
34    Reply(Expr),
35}
36
37/// A message handler: `on MSG(p1, p2) { body }`.
38#[derive(Debug, Clone)]
39pub struct Handler {
40    pub msg: String,
41    pub params: Vec<String>,
42    pub body: Vec<Stmt>,
43}
44
45/// A compiled actor behavior. `state_param` is the single scalar carried across
46/// messages (initialized by `spawn`, default 0). Handlers are matched by message
47/// name; the first handler is the default target for `via`.
48#[derive(Debug, Clone)]
49pub struct ActorDef {
50    pub name: String,
51    pub state_param: Option<String>,
52    pub handlers: Vec<Handler>,
53}
54
55impl ActorDef {
56    /// Find the handler for message `msg`.
57    fn handler(&self, msg: &str) -> Option<&Handler> {
58        self.handlers.iter().find(|h| h.msg == msg)
59    }
60}
61
62// ---- parsing (from the command tree) --------------------------------------
63
64/// Parse an `actor NAME(state) { on … }` command into an [`ActorDef`].
65///
66/// `args[0]` is the header word `NAME(state)` / `NAME`; `args[1]` is the handler
67/// block. Each inner command is `on MSG(params) { body }`.
68pub fn parse_actor(args: &[crate::ast::Arg]) -> Result<ActorDef, String> {
69    use crate::ast::Arg;
70    let header = args
71        .first()
72        .and_then(Arg::as_str)
73        .ok_or("actor: expected `actor NAME(state) { … }`")?;
74    let (name, state_param) = split_header(header)?;
75    if name.is_empty() {
76        return Err("actor: missing name".into());
77    }
78    let block = match args.get(1) {
79        Some(Arg::Block(cmds)) => cmds,
80        _ => return Err("actor: expected `{ on MSG { … } }` handler block".into()),
81    };
82    let mut handlers = Vec::new();
83    for c in block {
84        if c.name != "on" {
85            return Err(format!(
86                "actor: expected `on MSG {{ … }}`, got `{}`",
87                c.name
88            ));
89        }
90        let sig = c
91            .args
92            .first()
93            .and_then(Arg::as_str)
94            .ok_or("actor: `on` needs a message name")?;
95        let (msg, params) = split_call(sig);
96        let body_cmds = match c.args.get(1) {
97            Some(Arg::Block(b)) => b,
98            _ => return Err(format!("actor: `on {msg}` needs a `{{ … }}` body")),
99        };
100        // Extra args after the body mean two handlers ran together on one line
101        // (block tokens don't end a command) — flag it rather than silently
102        // dropping the rest.
103        if c.args.len() > 2 {
104            return Err(format!(
105                "actor: `on {msg}` has trailing tokens — separate handlers by a newline or `;`"
106            ));
107        }
108        handlers.push(Handler {
109            msg,
110            params,
111            body: parse_body(body_cmds)?,
112        });
113    }
114    if handlers.is_empty() {
115        return Err("actor: needs at least one `on MSG { … }` handler".into());
116    }
117    Ok(ActorDef {
118        name,
119        state_param,
120        handlers,
121    })
122}
123
124/// Split `NAME(state)` / `NAME()` / `NAME` into (name, optional state param).
125fn split_header(h: &str) -> Result<(String, Option<String>), String> {
126    let (name, params) = split_call(h);
127    match params.len() {
128        0 => Ok((name, None)),
129        1 => Ok((name, Some(params.into_iter().next().unwrap()))),
130        _ => Err(format!("actor: `{name}` takes a single state parameter")),
131    }
132}
133
134/// Split `NAME(a, b, c)` into ("NAME", ["a","b","c"]); `NAME` -> ("NAME", []).
135fn split_call(s: &str) -> (String, Vec<String>) {
136    let s = s.trim();
137    match s.find('(') {
138        None => (s.to_string(), Vec::new()),
139        Some(i) => {
140            let name = s[..i].trim().to_string();
141            let inner = s[i + 1..].trim_end_matches(')');
142            let params = inner
143                .split(',')
144                .map(str::trim)
145                .filter(|p| !p.is_empty())
146                .map(str::to_string)
147                .collect();
148            (name, params)
149        }
150    }
151}
152
153/// Parse a handler body: each command is `reply EXPR` or `var = EXPR`.
154fn parse_body(cmds: &[crate::ast::Command]) -> Result<Vec<Stmt>, String> {
155    let mut out = Vec::with_capacity(cmds.len());
156    for c in cmds {
157        if c.name == "reply" {
158            out.push(Stmt::Reply(parse_expr_args(&c.args)?));
159        } else if c.args.first().and_then(crate::ast::Arg::as_str) == Some("=") {
160            // Spaced `var = EXPR`: the verb is the target, `=` its first arg.
161            out.push(Stmt::Assign(c.name.clone(), parse_expr_args(&c.args[1..])?));
162        } else if let Some((lhs, rhs)) = c.name.split_once('=') {
163            // Unspaced `var=EXPR` / `var=EXPR...`: the lexer keeps `var=...` as one
164            // word. Split at the first `=`; the RHS continues with any later args.
165            let var = lhs.trim();
166            if var.is_empty() || !var.chars().all(|ch| ch.is_alphanumeric() || ch == '_') {
167                return Err(format!(
168                    "actor: `{}` is not a valid assignment target",
169                    c.name
170                ));
171            }
172            let mut expr = rhs.trim().to_string();
173            for a in &c.args {
174                let s = a
175                    .as_str()
176                    .ok_or("actor: a `{ … }` block is not an expression")?;
177                expr.push(' ');
178                expr.push_str(s);
179            }
180            out.push(Stmt::Assign(var.to_string(), expr::parse(expr.trim())?));
181        } else {
182            return Err(format!(
183                "actor: handler statement must be `reply EXPR` or `var = EXPR`, got `{}`",
184                c.name
185            ));
186        }
187    }
188    Ok(out)
189}
190
191/// Reconstruct an expression string from word args and parse it via [`expr`].
192fn parse_expr_args(args: &[crate::ast::Arg]) -> Result<Expr, String> {
193    let mut parts = Vec::with_capacity(args.len());
194    for a in args {
195        match a.as_str() {
196            Some(s) => parts.push(s),
197            None => return Err("actor: a `{ … }` block is not an expression".into()),
198        }
199    }
200    if parts.is_empty() {
201        return Err("actor: empty expression".into());
202    }
203    expr::parse(&parts.join(" "))
204}
205
206// ---- handler evaluation ----------------------------------------------------
207
208/// Evaluate a handler against its bound environment, returning the last `reply`
209/// value if any. `env` starts with `state` + parameters bound; assignments
210/// mutate it (so `state` persists across the caller's uses).
211fn run_handler(h: &Handler, env: &mut HashMap<String, f64>) -> Option<f64> {
212    let mut reply = None;
213    for st in &h.body {
214        match st {
215            Stmt::Assign(name, e) => {
216                let v = eval_env(e, env);
217                env.insert(name.clone(), v);
218            }
219            Stmt::Reply(e) => reply = Some(eval_env(e, env)),
220        }
221    }
222    reply
223}
224
225/// Evaluate `e` with barewords resolved from `env` (unknown -> 0). `x`
226/// (`Expr::Var`) reads the variable literally named `x`, so `on job(x)` binds it.
227fn eval_env(e: &Expr, env: &HashMap<String, f64>) -> f64 {
228    let x = env.get("x").copied().unwrap_or(0.0);
229    let resolve = |name: &str| env.get(name).copied().unwrap_or(0.0);
230    expr::eval_ctx(e, x, &resolve).unwrap_or(f64::NAN)
231}
232
233// ---- runtime: mailboxes, spawn/send/ask -----------------------------------
234
235/// A message posted to an actor: a name, positional scalar args, and an optional
236/// one-shot reply channel (present for `ask`, absent for `send`).
237struct Message {
238    name: String,
239    args: Vec<f64>,
240    reply: Option<Sender<f64>>,
241}
242
243/// A handle to a running actor: the sending half of its mailbox. Cloning shares
244/// one mailbox (every clone posts to the same thread).
245#[derive(Clone)]
246pub struct ActorRef {
247    tx: Sender<Message>,
248}
249
250impl ActorRef {
251    /// *Tell*: post a message, fire-and-forget. Returns `false` if the actor is
252    /// already gone.
253    pub fn send(&self, msg: &str, args: Vec<f64>) -> bool {
254        self.tx
255            .send(Message {
256                name: msg.to_string(),
257                args,
258                reply: None,
259            })
260            .is_ok()
261    }
262
263    /// *Ask*: post a message with a reply channel and block for the handler's
264    /// `reply`. `None` if the actor died or the handler produced no reply.
265    pub fn ask(&self, msg: &str, args: Vec<f64>) -> Option<f64> {
266        let (rtx, rrx) = mpsc::channel();
267        self.tx
268            .send(Message {
269                name: msg.to_string(),
270                args,
271                reply: Some(rtx),
272            })
273            .ok()?;
274        rrx.recv().ok()
275    }
276}
277
278/// Owns spawned actor threads and joins them on drop.
279#[derive(Default)]
280pub struct ActorSystem {
281    handles: Vec<JoinHandle<()>>,
282}
283
284impl ActorSystem {
285    pub fn new() -> Self {
286        Self::default()
287    }
288
289    /// Spawn `def` with initial state `init`, returning a ref to its mailbox.
290    /// One OS thread blocks on the mailbox and dispatches each message to the
291    /// matching handler, carrying `state` across messages.
292    pub fn spawn(&mut self, def: Arc<ActorDef>, init: f64) -> ActorRef {
293        let (tx, rx) = mpsc::channel::<Message>();
294        let handle = std::thread::spawn(move || actor_loop(&def, init, rx));
295        self.handles.push(handle);
296        ActorRef { tx }
297    }
298
299    /// A supervised round-robin pool of `n` copies of `def`. Dispatch (`ask`)
300    /// rotates across workers; a worker whose thread has died is respawned.
301    pub fn pool(&mut self, def: Arc<ActorDef>, n: usize, init: f64) -> Pool {
302        let n = n.max(1);
303        let refs = (0..n).map(|_| self.spawn(def.clone(), init)).collect();
304        Pool {
305            def,
306            init,
307            refs: Mutex::new(refs),
308            next: Mutex::new(0),
309        }
310    }
311}
312
313impl Drop for ActorSystem {
314    fn drop(&mut self) {
315        // Threads own their receivers; when every ActorRef is dropped the sender
316        // side closes and `recv` returns Err, ending the loop. Join to be tidy.
317        for h in self.handles.drain(..) {
318            let _ = h.join();
319        }
320    }
321}
322
323/// The per-actor dispatch loop. `catch_unwind` around each handler means a
324/// panicking message resets the actor's state (supervision: restart) instead of
325/// killing the thread and orphaning the mailbox.
326fn actor_loop(def: &ActorDef, init: f64, rx: Receiver<Message>) {
327    let mut state = init;
328    while let Ok(msg) = rx.recv() {
329        let Some(h) = def.handler(&msg.name) else {
330            // Unknown message: reply with the current state so an `ask` never hangs.
331            if let Some(r) = msg.reply {
332                let _ = r.send(state);
333            }
334            continue;
335        };
336        let mut env_map: HashMap<String, f64> = HashMap::new();
337        if let Some(sp) = &def.state_param {
338            env_map.insert(sp.clone(), state);
339        }
340        for (p, v) in h.params.iter().zip(msg.args.iter()) {
341            env_map.insert(p.clone(), *v);
342        }
343        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
344            run_handler(h, &mut env_map)
345        }));
346        match result {
347            Ok(reply) => {
348                // Persist the (possibly reassigned) state for the next message.
349                if let Some(sp) = &def.state_param {
350                    if let Some(v) = env_map.get(sp) {
351                        state = *v;
352                    }
353                }
354                if let Some(r) = msg.reply {
355                    // No explicit reply -> hand back the current state.
356                    let _ = r.send(reply.unwrap_or(state));
357                }
358            }
359            Err(_) => {
360                // Handler panicked: restart — reset state, answer with it so the
361                // caller is not left blocked.
362                state = init;
363                if let Some(r) = msg.reply {
364                    let _ = r.send(state);
365                }
366            }
367        }
368    }
369}
370
371/// A supervised round-robin actor pool.
372pub struct Pool {
373    def: Arc<ActorDef>,
374    init: f64,
375    refs: Mutex<Vec<ActorRef>>,
376    next: Mutex<usize>,
377}
378
379impl Pool {
380    /// Number of workers.
381    pub fn size(&self) -> usize {
382        self.refs.lock().unwrap().len()
383    }
384
385    /// Ask the next worker in rotation; respawn-and-retry once if it is dead.
386    /// Requires the owning [`ActorSystem`] so a respawned worker's thread is
387    /// tracked and joined like the rest.
388    pub fn ask(&self, sys: &Mutex<ActorSystem>, msg: &str, args: Vec<f64>) -> Option<f64> {
389        // Pick a worker and clone its cheap sender handle out from under the lock,
390        // so the blocking `ask` runs without serializing the whole pool.
391        let (idx, worker) = {
392            let refs = self.refs.lock().unwrap();
393            let len = refs.len().max(1);
394            let mut n = self.next.lock().unwrap();
395            let i = *n % len;
396            *n = i + 1;
397            (i, refs.get(i).cloned())
398        };
399        if let Some(w) = worker {
400            if let Some(v) = w.ask(msg, args.clone()) {
401                return Some(v);
402            }
403        }
404        // Dead worker: respawn its slot and retry.
405        let fresh = sys.lock().unwrap().spawn(self.def.clone(), self.init);
406        let v = fresh.ask(msg, args);
407        if let Some(slot) = self.refs.lock().unwrap().get_mut(idx) {
408            *slot = fresh;
409        }
410        v
411    }
412}
413
414// ---- pipeline fan-out: `via NAME [* N]` ------------------------------------
415
416/// Default `via` pool width when unspecified — one worker per hardware thread.
417fn default_workers() -> usize {
418    std::thread::available_parallelism()
419        .map(|n| n.get())
420        .unwrap_or(4)
421}
422
423/// Fan `lines` across a pool of `def` and collect the replies, order preserved.
424///
425/// Each line's scalar (`crate::spec::parse_scalar`) is asked as the first
426/// handler's message, binding parameter 0; the reply formats to the output line.
427/// A pure-map handler (`reply x * 2`) is deterministic regardless of pool width;
428/// a stateful handler is partitioned across workers (documented in SPEC §15).
429pub fn run_via(def: &Arc<ActorDef>, workers: usize, lines: &[String]) -> Vec<String> {
430    if lines.is_empty() {
431        return Vec::new();
432    }
433    let n = if workers == 0 {
434        default_workers()
435    } else {
436        workers
437    }
438    .min(lines.len().max(1));
439    let msg = def.handlers[0].msg.clone();
440    let reply = |l: &String, v: Option<f64>| match v {
441        Some(v) => crate::query::fmt_scalar(v),
442        None => l.clone(),
443    };
444
445    // A single worker is a *sequential* actor: dispatch in input order so its
446    // `state` accumulates deterministically (`via NAME * 1` = one mailbox, one
447    // ordered stream). Concurrent dispatch would let messages arrive out of
448    // order, so only the multi-worker map path fans out in parallel.
449    let mut sys = ActorSystem::new();
450    if n == 1 {
451        let r = sys.spawn(def.clone(), 0.0);
452        return lines
453            .iter()
454            .map(|l| reply(l, r.ask(&msg, vec![crate::spec::parse_scalar(l)])))
455            .collect();
456    }
457
458    // Multi-worker pool: each line is asked concurrently (rayon), the pool's
459    // round-robin spreads asks across workers, and `par_iter().collect()` keeps
460    // output order matching the input. A pure-map handler is deterministic; a
461    // stateful handler is partitioned across workers (SPEC §15).
462    let sys = Mutex::new(sys);
463    let pool = {
464        let mut s = sys.lock().unwrap();
465        s.pool(def.clone(), n, 0.0)
466    };
467    use rayon::prelude::*;
468    lines
469        .par_iter()
470        .map(|l| reply(l, pool.ask(&sys, &msg, vec![crate::spec::parse_scalar(l)])))
471        .collect()
472}
473
474// ---- imperative session: spawn / pool / tell / ask / supervise -------------
475
476/// A top-level actor binding: `spawn NAME = ACTOR(init)` or
477/// `pool NAME = ACTOR * N`, optionally re-tuned by `supervise NAME { … }`.
478#[derive(Debug, Clone)]
479pub struct RefDecl {
480    /// The binding name used by `tell`/`ask` (`w`, `p`).
481    pub name: String,
482    /// The `actor NAME(state) { … }` this ref runs.
483    pub actor: String,
484    /// Initial `state`, evaluated at build time (`spawn w = worker(3)` -> 3).
485    pub init: f64,
486    /// `Some(N)` for a `pool … * N`; `None` for a single actor.
487    pub pool: Option<usize>,
488    /// Supervision policy: respawn a dead worker (default), or fail-stop when a
489    /// `supervise NAME { on crash { stop } }` clause turned it off.
490    pub restart: bool,
491}
492
493/// A named ref inside a live [`Session`]: one actor, or a supervised pool.
494enum Target {
495    One(ActorRef),
496    Pool {
497        workers: Vec<ActorRef>,
498        next: usize,
499        def: Arc<ActorDef>,
500        init: f64,
501        restart: bool,
502    },
503}
504
505/// The interactive actor runtime for a spec: owns the [`ActorSystem`] and every
506/// `spawn`/`pool` binding, so `tell`/`ask` bind actions can drive them across the
507/// session (SPEC §15). Single-threaded access from the TUI loop (`&mut self`).
508#[derive(Default)]
509pub struct Session {
510    // Field order is load-bearing: `refs` (which holds the mailbox senders) MUST
511    // drop before `sys` (whose Drop joins the threads). Struct fields drop in
512    // declaration order, so refs first closes the senders, letting each `recv`
513    // return Err and the thread exit — otherwise `sys`'s join would hang forever.
514    refs: HashMap<String, Target>,
515    sys: ActorSystem,
516}
517
518impl Session {
519    /// Spawn every declared ref against the actor registry. A ref naming an
520    /// unknown actor is an error (surfaced at build, not silently dropped).
521    pub fn build(
522        defs: &std::collections::BTreeMap<String, Arc<ActorDef>>,
523        decls: &[RefDecl],
524    ) -> Result<Session, String> {
525        let mut s = Session::default();
526        for d in decls {
527            let def = defs
528                .get(&d.actor)
529                .ok_or_else(|| format!("spawn: no actor named `{}`", d.actor))?
530                .clone();
531            let target = match d.pool {
532                Some(n) => {
533                    let n = n.max(1);
534                    Target::Pool {
535                        workers: (0..n).map(|_| s.sys.spawn(def.clone(), d.init)).collect(),
536                        next: 0,
537                        def,
538                        init: d.init,
539                        restart: d.restart,
540                    }
541                }
542                None => Target::One(s.sys.spawn(def, d.init)),
543            };
544            s.refs.insert(d.name.clone(), target);
545        }
546        Ok(s)
547    }
548
549    /// Whether the session has any refs (an all-`via` spec has none).
550    pub fn is_empty(&self) -> bool {
551        self.refs.is_empty()
552    }
553
554    /// Pick the next live worker for a ref, respawning a dead one when the ref is
555    /// supervised. Returns a cloned mailbox handle (cheap) to send on.
556    fn worker(&mut self, name: &str) -> Option<ActorRef> {
557        match self.refs.get_mut(name)? {
558            Target::One(r) => Some(r.clone()),
559            Target::Pool {
560                workers,
561                next,
562                def,
563                init,
564                restart,
565            } => {
566                if workers.is_empty() {
567                    return None;
568                }
569                let i = *next % workers.len();
570                *next = i + 1;
571                // A supervised pool respawns a worker whose thread has died before
572                // dispatching to it; an unsupervised (fail-stop) pool does not.
573                if *restart {
574                    let probe = mpsc::channel::<f64>().0;
575                    let dead = workers[i]
576                        .tx
577                        .send(Message {
578                            name: String::new(),
579                            args: Vec::new(),
580                            reply: Some(probe),
581                        })
582                        .is_err();
583                    if dead {
584                        workers[i] = self.sys.spawn(def.clone(), *init);
585                    }
586                }
587                Some(workers[i].clone())
588            }
589        }
590    }
591
592    /// *Tell* a ref (fire-and-forget). Unknown ref -> ignored.
593    pub fn tell(&mut self, name: &str, msg: &str, args: Vec<f64>) {
594        if let Some(w) = self.worker(name) {
595            w.send(msg, args);
596        }
597    }
598
599    /// *Ask* a ref and block for the reply. Unknown/dead ref -> `None`.
600    pub fn ask(&mut self, name: &str, msg: &str, args: Vec<f64>) -> Option<f64> {
601        self.worker(name).and_then(|w| w.ask(msg, args))
602    }
603}
604
605/// Parse a message call `MSG(a, b, …)` (or bare `MSG`) into its name and the
606/// argument expressions. Commas split only at paren depth 0, so an arithmetic
607/// arg like `(a + b) * 2` stays intact.
608pub fn parse_call(s: &str) -> Result<(String, Vec<Expr>), String> {
609    let s = s.trim();
610    let open = match s.find('(') {
611        None => return Ok((s.to_string(), Vec::new())),
612        Some(i) => i,
613    };
614    let name = s[..open].trim().to_string();
615    if name.is_empty() {
616        return Err("message call: missing name".into());
617    }
618    let inner = s
619        .strip_suffix(')')
620        .and_then(|s| s.get(open + 1..))
621        .ok_or("message call: unbalanced `()`")?;
622    let mut args = Vec::new();
623    let (mut depth, mut start) = (0isize, 0usize);
624    for (i, ch) in inner.char_indices() {
625        match ch {
626            '(' => depth += 1,
627            ')' => depth -= 1,
628            ',' if depth == 0 => {
629                push_arg(&inner[start..i], &mut args)?;
630                start = i + 1;
631            }
632            _ => {}
633        }
634    }
635    if !inner.trim().is_empty() {
636        push_arg(&inner[start..], &mut args)?;
637    }
638    Ok((name, args))
639}
640
641fn push_arg(raw: &str, out: &mut Vec<Expr>) -> Result<(), String> {
642    let t = raw.trim();
643    if t.is_empty() {
644        return Err("message call: empty argument".into());
645    }
646    out.push(expr::parse(t)?);
647    Ok(())
648}
649
650/// Evaluate a message call's argument expressions against live control values —
651/// a `.name` control resolves to its current numeric input (unset -> NaN).
652pub fn eval_args(exprs: &[Expr], inputs: &HashMap<String, String>) -> Vec<f64> {
653    let num = |n: &str| -> Option<f64> { inputs.get(n).and_then(|v| v.trim().parse::<f64>().ok()) };
654    let strv = |n: &str| -> Option<String> { inputs.get(n).cloned() };
655    exprs
656        .iter()
657        .map(|e| {
658            let sub = expr::substitute_controls(e, &num, &strv);
659            expr::eval(&sub, 0.0).unwrap_or(f64::NAN)
660        })
661        .collect()
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667    use crate::parser::parse;
668
669    fn def(src: &str) -> Arc<ActorDef> {
670        let cmds = parse(src).unwrap();
671        Arc::new(parse_actor(&cmds[0].args).unwrap())
672    }
673
674    #[test]
675    fn parses_header_and_handlers() {
676        // Handlers are separated like every other verb — by newline or `;`.
677        let d =
678            def("actor worker(state) {\n on job(x) { reply x * 2 }\n on reset { state = 0 }\n }");
679        assert_eq!(d.name, "worker");
680        assert_eq!(d.state_param.as_deref(), Some("state"));
681        assert_eq!(d.handlers.len(), 2);
682        assert_eq!(d.handlers[0].msg, "job");
683        assert_eq!(d.handlers[0].params, vec!["x".to_string()]);
684        assert_eq!(d.handlers[1].msg, "reset");
685        assert!(d.handlers[1].params.is_empty());
686    }
687
688    #[test]
689    fn unspaced_assignment_is_accepted() {
690        // The lexer keeps `state=state+1` as one word; parse_body splits it.
691        let d = def("actor c(state) { on tick { state=state+1; reply state } }");
692        let mut sys = ActorSystem::new();
693        let r = sys.spawn(d, 0.0);
694        assert_eq!(r.ask("tick", vec![]), Some(1.0));
695        assert_eq!(r.ask("tick", vec![]), Some(2.0));
696    }
697
698    #[test]
699    fn header_without_state_is_allowed() {
700        let d = def("actor doubler { on job(x) { reply x + x } }");
701        assert!(d.state_param.is_none());
702    }
703
704    #[test]
705    fn spawn_send_ask_roundtrip() {
706        let d = def("actor w(state) { on job(x) { reply x * 3 } }");
707        let mut sys = ActorSystem::new();
708        let r = sys.spawn(d, 0.0);
709        assert_eq!(r.ask("job", vec![7.0]), Some(21.0));
710    }
711
712    #[test]
713    fn state_persists_across_messages() {
714        // `add(n)` accumulates into state and replies the running total.
715        let d = def("actor acc(state) { on add(n) { state = state + n; reply state } }");
716        let mut sys = ActorSystem::new();
717        let r = sys.spawn(d, 0.0);
718        assert_eq!(r.ask("add", vec![10.0]), Some(10.0));
719        assert_eq!(r.ask("add", vec![5.0]), Some(15.0));
720        assert_eq!(r.ask("add", vec![100.0]), Some(115.0));
721    }
722
723    #[test]
724    fn tell_is_fire_and_forget() {
725        let d = def("actor sink(state) { on set(v) { state = v; reply state } }");
726        let mut sys = ActorSystem::new();
727        let r = sys.spawn(d, 0.0);
728        assert!(r.send("set", vec![42.0]));
729        // A following ask observes the tell's state mutation (same mailbox order).
730        assert_eq!(r.ask("set", vec![9.0]), Some(9.0));
731    }
732
733    #[test]
734    fn unknown_message_replies_state_not_hang() {
735        let d = def("actor w(state) { on job(x) { reply x } }");
736        let mut sys = ActorSystem::new();
737        let r = sys.spawn(d, 3.0);
738        assert_eq!(r.ask("nope", vec![]), Some(3.0));
739    }
740
741    #[test]
742    fn via_is_a_deterministic_parallel_map() {
743        let d = def("actor sq(state) { on job(x) { reply x * x } }");
744        let lines: Vec<String> = (1..=6).map(|i| i.to_string()).collect();
745        let out = run_via(&d, 4, &lines);
746        assert_eq!(out, vec!["1", "4", "9", "16", "25", "36"]);
747    }
748
749    #[test]
750    fn via_preserves_order_with_single_worker() {
751        let d = def("actor inc(state) { on job(x) { reply x + 1 } }");
752        let lines: Vec<String> = vec!["10".into(), "20".into(), "30".into()];
753        assert_eq!(run_via(&d, 1, &lines), vec!["11", "21", "31"]);
754    }
755
756    #[test]
757    fn via_single_worker_is_a_sequential_accumulator() {
758        // `via NAME * 1` dispatches in input order, so state accumulates
759        // deterministically — a running total, not a per-worker partition.
760        let d = def("actor acc(state) { on job(x) { state = state + x; reply state } }");
761        let lines: Vec<String> = vec!["10".into(), "5".into(), "100".into()];
762        assert_eq!(run_via(&d, 1, &lines), vec!["10", "15", "115"]);
763    }
764
765    fn reg(src: &str) -> std::collections::BTreeMap<String, Arc<ActorDef>> {
766        let mut m = std::collections::BTreeMap::new();
767        let d = def(src);
768        m.insert(d.name.clone(), d);
769        m
770    }
771
772    #[test]
773    fn session_spawn_tell_ask() {
774        let defs = reg("actor acc(state) { on add(n) { state = state + n; reply state } }");
775        let decls = vec![RefDecl {
776            name: "w".into(),
777            actor: "acc".into(),
778            init: 100.0,
779            pool: None,
780            restart: true,
781        }];
782        let mut s = Session::build(&defs, &decls).unwrap();
783        s.tell("w", "add", vec![5.0]); // fire-and-forget: state 100 -> 105
784        assert_eq!(s.ask("w", "add", vec![10.0]), Some(115.0));
785        // Unknown ref is a no-op / None, never a panic.
786        s.tell("ghost", "add", vec![1.0]);
787        assert_eq!(s.ask("ghost", "add", vec![1.0]), None);
788    }
789
790    #[test]
791    fn session_pool_round_robins() {
792        // Each worker starts at its own base; two asks hit two distinct workers.
793        let defs = reg("actor id(state) { on get { reply state } }");
794        let decls = vec![RefDecl {
795            name: "p".into(),
796            actor: "id".into(),
797            init: 7.0,
798            pool: Some(3),
799            restart: true,
800        }];
801        let mut s = Session::build(&defs, &decls).unwrap();
802        assert_eq!(s.ask("p", "get", vec![]), Some(7.0));
803        assert_eq!(s.ask("p", "get", vec![]), Some(7.0));
804    }
805
806    #[test]
807    fn supervised_pool_respawns_but_failstop_does_not() {
808        let defs = reg("actor w(state) { on job(x) { reply x + 1 } }");
809        // A one-worker supervised pool: kill the worker, ask -> respawned answer.
810        let mut sup = Session::build(
811            &defs,
812            &[RefDecl {
813                name: "p".into(),
814                actor: "w".into(),
815                init: 0.0,
816                pool: Some(1),
817                restart: true,
818            }],
819        )
820        .unwrap();
821        kill_pool_worker(&mut sup, "p");
822        assert_eq!(sup.ask("p", "job", vec![41.0]), Some(42.0));
823
824        // A fail-stop pool (restart=false): a dead worker is not respawned.
825        let mut fs = Session::build(
826            &defs,
827            &[RefDecl {
828                name: "p".into(),
829                actor: "w".into(),
830                init: 0.0,
831                pool: Some(1),
832                restart: false,
833            }],
834        )
835        .unwrap();
836        kill_pool_worker(&mut fs, "p");
837        assert_eq!(fs.ask("p", "job", vec![41.0]), None);
838    }
839
840    /// Replace a pool's single worker with a dead mailbox (dropped receiver).
841    fn kill_pool_worker(s: &mut Session, name: &str) {
842        if let Some(Target::Pool { workers, .. }) = s.refs.get_mut(name) {
843            let (tx, rx) = mpsc::channel();
844            drop(rx);
845            workers[0] = ActorRef { tx };
846        }
847    }
848
849    #[test]
850    fn spec_build_parses_refs_actions_and_supervise() {
851        use crate::spec::{self, BindAction};
852        let src = "\
853actor worker(state) { on job(x) { reply x * 2 } }\n\
854spawn w = worker(3)\n\
855pool p = worker * 4\n\
856supervise p { on crash { stop } }\n\
857bind C-t tell w job(5)\n\
858bind C-a ask .out p job(.th)\n";
859        let sp = spec::build(&parse(src).unwrap()).unwrap();
860        assert_eq!(sp.actor_refs.len(), 2);
861        let w = &sp.actor_refs[0];
862        assert_eq!(
863            (w.name.as_str(), w.actor.as_str(), w.init, w.pool),
864            ("w", "worker", 3.0, None)
865        );
866        let p = &sp.actor_refs[1];
867        assert_eq!((p.name.as_str(), p.pool, p.restart), ("p", Some(4), false)); // stop policy
868                                                                                 // The two binds carry the actor actions.
869        let tell = sp.binds.iter().find_map(|b| match &b.action {
870            BindAction::ActorTell { refname, call } => Some((refname.clone(), call.clone())),
871            _ => None,
872        });
873        assert_eq!(tell, Some(("w".to_string(), "job(5)".to_string())));
874        let ask = sp.binds.iter().find_map(|b| match &b.action {
875            BindAction::ActorAsk {
876                ctrl,
877                refname,
878                call,
879            } => Some((ctrl.clone(), refname.clone(), call.clone())),
880            _ => None,
881        });
882        assert_eq!(
883            ask,
884            Some(("out".to_string(), "p".to_string(), "job(.th)".to_string()))
885        );
886    }
887
888    #[test]
889    fn parse_call_splits_args_at_depth_zero() {
890        let (msg, args) = parse_call("job(5, (1 + 2) * 3)").unwrap();
891        assert_eq!(msg, "job");
892        assert_eq!(args.len(), 2);
893        let inputs = HashMap::new();
894        assert_eq!(eval_args(&args, &inputs), vec![5.0, 9.0]);
895    }
896
897    #[test]
898    fn eval_args_resolves_controls() {
899        let (_msg, args) = parse_call("job(.th * 2)").unwrap();
900        let mut inputs = HashMap::new();
901        inputs.insert("th".to_string(), "21".to_string());
902        assert_eq!(eval_args(&args, &inputs), vec![42.0]);
903    }
904
905    #[test]
906    fn pool_respawns_a_dead_worker() {
907        let d = def("actor w(state) { on job(x) { reply x + 1 } }");
908        let sys = Mutex::new(ActorSystem::new());
909        let pool = sys.lock().unwrap().pool(d.clone(), 2, 0.0);
910        // Kill one slot by replacing its ref with a dropped-receiver sender.
911        {
912            let (tx, rx) = mpsc::channel();
913            drop(rx);
914            pool.refs.lock().unwrap()[0] = ActorRef { tx };
915        }
916        // Two asks rotate across both slots; the dead one is respawned and answers.
917        assert_eq!(pool.ask(&sys, "job", vec![1.0]), Some(2.0));
918        assert_eq!(pool.ask(&sys, "job", vec![41.0]), Some(42.0));
919        assert_eq!(pool.size(), 2);
920    }
921}