Skip to main content

tpt_telos_router/
lib.rs

1//! Context router for tpt-telos.
2//!
3//! Decides, from `@boundary(...)` architectural metadata, whether a module or
4//! function should be compiled to the Rust backend (CPU-bound, zero-allocation,
5//! cryptographic paths) or the Go backend (network I/O, high-concurrency,
6//! distributed paths).
7//!
8//! In Phase 2 only the Rust backend is generated; the router nonetheless
9//! records the intended target so the dual-backend work (Phase 3) can consume
10//! it without further parsing changes.
11
12use tpt_telos_parser::ast::{Arg, Attribute};
13
14/// The compilation backend a module or function is routed to.
15///
16/// Determined by `@boundary(...)` architectural metadata.
17/// Defaults to [`Target::Rust`] when no recognised flags are present.
18///
19/// # Examples
20///
21/// ```
22/// use tpt_telos_router::{route, Target};
23/// use tpt_telos_parser::ast::{Arg, Attribute};
24///
25/// let attr = Attribute {
26///     name: "boundary".to_string(),
27///     args: vec![Arg::Flag("network_io".to_string())],
28/// };
29/// let r = route(&[attr]);
30/// assert_eq!(r.target, Target::Go);
31/// ```
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Target {
34    Rust,
35    Go,
36    /// Python (with optional JAX/NumPy annotations) for ML/PINN workloads.
37    /// Triggered by `@boundary(ml_training)`, `@boundary(python)`, or
38    /// `@boundary(jax)`.
39    Python,
40}
41
42impl Target {
43    /// Returns the target as a lowercase string.
44    ///
45    /// # Examples
46    ///
47    /// ```
48    /// use tpt_telos_router::Target;
49    ///
50    /// assert_eq!(Target::Rust.as_str(), "rust");
51    /// assert_eq!(Target::Go.as_str(), "go");
52    /// assert_eq!(Target::Python.as_str(), "python");
53    /// ```
54    pub fn as_str(&self) -> &'static str {
55        match self {
56            Target::Rust => "rust",
57            Target::Go => "go",
58            Target::Python => "python",
59        }
60    }
61}
62
63/// A routing warning emitted when architectural flags imply a potentially
64/// unsafe target combination.
65#[derive(Debug, Clone)]
66pub struct RoutingDiagnostic {
67    pub kind: DiagnosticKind,
68    pub module: String,
69    pub message: String,
70}
71
72/// The kind of routing conflict detected.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum DiagnosticKind {
75    /// A `real_time` module was routed to Go, whose GC is non-deterministic.
76    /// FADEC / PREEMPT_RT targets must stay on the Rust backend.
77    RealTimeGoConflict,
78    /// A `zero_allocation` module was routed to Go, which allocates via GC.
79    ZeroAllocGoConflict,
80    /// A `real_time` module was routed to Python (GC + interpreter).
81    RealTimePythonConflict,
82    /// A `zero_allocation` module was routed to Python (GC + interpreter).
83    ZeroAllocPythonConflict,
84    /// An `@state(...)` attribute contained an unrecognized value (possible typo).
85    UnrecognizedStateValue,
86    /// An `@boundary(...)` attribute contained an unrecognized flag (possible typo),
87    /// so it was ignored and the module defaulted to Rust.
88    UnrecognizedBoundaryFlag,
89}
90
91/// The storage class for a module's data structures, derived from
92/// `@state(persistent)` or `@state(ephemeral)`.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
94pub enum StorageClass {
95    /// Database-backed / serializable structs. `persistent` modules emit
96    /// `#[derive(Serialize, Deserialize)]` (Rust) and JSON tags (Go).
97    Persistent,
98    /// Stack-only / transient structs (default). No serialization support.
99    #[default]
100    Ephemeral,
101}
102
103/// The routing decision for a module or function.
104///
105/// Contains the chosen [`Target`] backend and a human-readable `reason`
106/// string for transparency in CLI output.
107#[derive(Debug, Clone)]
108pub struct Route {
109    pub target: Target,
110    /// The storage class derived from `@state(...)`.
111    pub storage: StorageClass,
112    /// Human-readable justification, surfaced by the CLI for transparency.
113    pub reason: String,
114}
115
116impl Route {
117    /// Returns `true` when the target is [`Target::Rust`].
118    ///
119    /// # Examples
120    ///
121    /// ```
122    /// use tpt_telos_router::{route, Target};
123    /// use tpt_telos_parser::ast::{Arg, Attribute};
124    ///
125    /// let cpu_attr = Attribute {
126    ///     name: "boundary".to_string(),
127    ///     args: vec![Arg::Flag("cpu_bound".to_string())],
128    /// };
129    /// let r = route(&[cpu_attr]);
130    /// assert!(r.is_rust());
131    /// assert_eq!(r.target, Target::Rust);
132    /// ```
133    pub fn is_rust(&self) -> bool {
134        self.target == Target::Rust
135    }
136}
137
138/// Boundary flags that imply a Rust target.
139const RUST_FLAGS: &[&str] = &["cpu_bound", "zero_allocation", "crypto", "real_time"];
140
141/// Boundary flags that imply a Go target.
142const GO_FLAGS: &[&str] = &[
143    "network_io",
144    "high_concurrency",
145    "distributed",
146    "high_latency",
147];
148
149/// Boundary flags that imply a Python target (ML/JAX workloads).
150const PYTHON_FLAGS: &[&str] = &["ml_training", "python", "jax"];
151
152fn boundary_flags(attrs: &[Attribute]) -> Vec<String> {
153    let mut flags = Vec::new();
154    for attr in attrs {
155        if attr.name != "boundary" {
156            continue;
157        }
158        for arg in &attr.args {
159            if let Arg::Flag(f) = arg {
160                flags.push(f.clone());
161            }
162        }
163    }
164    flags
165}
166
167/// Parse `@state(persistent)` or `@state(ephemeral)` from module attributes.
168/// Returns `(StorageClass, Option<unrecognized_value>)`. The second element is
169/// `Some(value)` when a `@state(...)` attribute was present but the value was
170/// not a recognized keyword (possible typo), so callers can emit a diagnostic.
171fn parse_storage_class(attrs: &[Attribute]) -> (StorageClass, Option<String>) {
172    for attr in attrs {
173        if attr.name != "state" {
174            continue;
175        }
176        for arg in &attr.args {
177            if let Arg::Flag(f) = arg {
178                match f.as_str() {
179                    "persistent" => return (StorageClass::Persistent, None),
180                    "ephemeral" => return (StorageClass::Ephemeral, None),
181                    other => return (StorageClass::default(), Some(other.to_string())),
182                }
183            }
184            if let Arg::Kv(k, tpt_telos_parser::ast::Literal::Ident(v)) = arg {
185                if k == "class" {
186                    match v.as_str() {
187                        "persistent" => return (StorageClass::Persistent, None),
188                        "ephemeral" => return (StorageClass::Ephemeral, None),
189                        other => return (StorageClass::default(), Some(other.to_string())),
190                    }
191                }
192            }
193        }
194    }
195    (StorageClass::default(), None)
196}
197
198/// Route a module from its `@boundary` attributes and emit diagnostics for
199/// potentially unsafe target combinations.
200///
201/// Diagnostics are non-fatal warnings; the caller decides whether to surface
202/// them as errors (e.g. with `--strict-rt`).
203///
204/// # Examples
205///
206/// ```
207/// use tpt_telos_router::{route_checked, Target, DiagnosticKind};
208/// use tpt_telos_parser::ast::{Arg, Attribute};
209///
210/// let attr = Attribute {
211///     name: "boundary".to_string(),
212///     args: vec![
213///         Arg::Flag("real_time".to_string()),
214///         Arg::Flag("network_io".to_string()),
215///     ],
216/// };
217/// let (r, diags) = route_checked(&[attr], "ControlLoop");
218/// assert_eq!(r.target, Target::Go);
219/// assert!(diags.iter().any(|d| d.kind == DiagnosticKind::RealTimeGoConflict));
220/// ```
221pub fn route_checked(attrs: &[Attribute], module_name: &str) -> (Route, Vec<RoutingDiagnostic>) {
222    let flags = boundary_flags(attrs);
223
224    // Parse @state(...) for storage class.
225    let (storage, unrecognized_state) = parse_storage_class(attrs);
226
227    let mut go_hits = Vec::new();
228    let mut rust_hits = Vec::new();
229    let mut python_hits = Vec::new();
230    let mut unrecognized_flags = Vec::new();
231    for f in &flags {
232        if PYTHON_FLAGS.contains(&f.as_str()) {
233            python_hits.push(f.clone());
234        } else if GO_FLAGS.contains(&f.as_str()) {
235            go_hits.push(f.clone());
236        } else if RUST_FLAGS.contains(&f.as_str()) {
237            rust_hits.push(f.clone());
238        } else {
239            unrecognized_flags.push(f.clone());
240        }
241    }
242
243    // Python beats everything else (ML workloads are explicit opt-in).
244    let route = if !python_hits.is_empty() {
245        Route {
246            target: Target::Python,
247            storage,
248            reason: format!("boundary flags {:?} routed to Python backend", python_hits),
249        }
250    } else if !go_hits.is_empty() {
251        Route {
252            target: Target::Go,
253            storage,
254            reason: format!("boundary flags {:?} routed to Go backend", go_hits),
255        }
256    } else if !rust_hits.is_empty() {
257        Route {
258            target: Target::Rust,
259            storage,
260            reason: format!("boundary flags {:?} routed to Rust backend", rust_hits),
261        }
262    } else {
263        Route {
264            target: Target::Rust,
265            storage,
266            reason: "no explicit boundary flags; defaulting to Rust compute backend".to_string(),
267        }
268    };
269
270    let mut diagnostics = Vec::new();
271
272    if let Some(ref bad_val) = unrecognized_state {
273        diagnostics.push(RoutingDiagnostic {
274            kind: DiagnosticKind::UnrecognizedStateValue,
275            module: module_name.to_string(),
276            message: format!(
277                "module `{}` has unrecognized `@state({})` value; \
278                 valid values are `persistent` and `ephemeral` (defaulting to ephemeral)",
279                module_name, bad_val
280            ),
281        });
282    }
283
284    for bad_flag in &unrecognized_flags {
285        diagnostics.push(RoutingDiagnostic {
286            kind: DiagnosticKind::UnrecognizedBoundaryFlag,
287            module: module_name.to_string(),
288            message: format!(
289                "module `{}` has unrecognized `@boundary({})` flag; \
290                 valid flags are cpu_bound, zero_allocation, crypto, real_time, \
291                 network_io, high_concurrency, distributed, high_latency, \
292                 ml_training, python, jax (ignored; defaulting to Rust backend)",
293                module_name, bad_flag
294            ),
295        });
296    }
297
298    if route.target == Target::Go {
299        if rust_hits.iter().any(|f| f == "real_time") {
300            diagnostics.push(RoutingDiagnostic {
301                kind: DiagnosticKind::RealTimeGoConflict,
302                module: module_name.to_string(),
303                message: format!(
304                    "module `{}` has `real_time` flag but is routed to Go (GC is \
305                     non-deterministic; FADEC/PREEMPT_RT targets must use Rust; \
306                     see ARCHITECTURE.md § Go GC Determinism)",
307                    module_name
308                ),
309            });
310        }
311        if rust_hits.iter().any(|f| f == "zero_allocation") {
312            diagnostics.push(RoutingDiagnostic {
313                kind: DiagnosticKind::ZeroAllocGoConflict,
314                module: module_name.to_string(),
315                message: format!(
316                    "module `{}` has `zero_allocation` flag but is routed to Go \
317                     (Go allocates via GC; zero-allocation guarantees cannot be upheld; \
318                     see ARCHITECTURE.md § Go GC Determinism)",
319                    module_name
320                ),
321            });
322        }
323    }
324
325    if route.target == Target::Python {
326        if rust_hits.iter().any(|f| f == "real_time") {
327            diagnostics.push(RoutingDiagnostic {
328                kind: DiagnosticKind::RealTimePythonConflict,
329                module: module_name.to_string(),
330                message: format!(
331                    "module `{}` has `real_time` flag but is routed to Python \
332                     (Python is GC-based with non-deterministic latency; \
333                     hard real-time targets must use Rust)",
334                    module_name
335                ),
336            });
337        }
338        if rust_hits.iter().any(|f| f == "zero_allocation") {
339            diagnostics.push(RoutingDiagnostic {
340                kind: DiagnosticKind::ZeroAllocPythonConflict,
341                module: module_name.to_string(),
342                message: format!(
343                    "module `{}` has `zero_allocation` flag but is routed to Python \
344                     (Python allocates via GC; zero-allocation guarantees cannot be upheld)",
345                    module_name
346                ),
347            });
348        }
349    }
350
351    (route, diagnostics)
352}
353
354/// Route a module from its own `@boundary` attributes (and any inherited
355/// function-level attributes if supplied). Thin wrapper around
356/// [`route_checked`] that discards diagnostics for callers that do not need
357/// them.
358///
359/// # Examples
360///
361/// ```
362/// use tpt_telos_router::{route, Target};
363/// use tpt_telos_parser::ast::{Arg, Attribute};
364///
365/// // No boundary flags → Rust (default).
366/// assert_eq!(route(&[]).target, Target::Rust);
367///
368/// // cpu_bound → Rust.
369/// let rust_attr = Attribute {
370///     name: "boundary".to_string(),
371///     args: vec![Arg::Flag("cpu_bound".to_string())],
372/// };
373/// assert_eq!(route(&[rust_attr]).target, Target::Rust);
374///
375/// // network_io → Go.
376/// let go_attr = Attribute {
377///     name: "boundary".to_string(),
378///     args: vec![Arg::Flag("network_io".to_string())],
379/// };
380/// let r = route(&[go_attr]);
381/// assert_eq!(r.target, Target::Go);
382/// assert!(!r.is_rust());
383/// assert!(r.reason.contains("network_io"));
384///
385/// // ml_training → Python.
386/// let py_attr = Attribute {
387///     name: "boundary".to_string(),
388///     args: vec![Arg::Flag("ml_training".to_string())],
389/// };
390/// assert_eq!(route(&[py_attr]).target, Target::Python);
391/// ```
392pub fn route(attrs: &[Attribute]) -> Route {
393    route_checked(attrs, "").0
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use tpt_telos_parser::ast::{Arg, Attribute};
400
401    fn attr(flags: &[&str]) -> Attribute {
402        Attribute {
403            name: "boundary".to_string(),
404            args: flags.iter().map(|f| Arg::Flag(f.to_string())).collect(),
405        }
406    }
407
408    #[test]
409    fn network_io_routes_to_go() {
410        let r = route(&[attr(&["network_io"])]);
411        assert_eq!(r.target, Target::Go);
412    }
413
414    #[test]
415    fn cpu_bound_routes_to_rust() {
416        let r = route(&[attr(&["cpu_bound"])]);
417        assert_eq!(r.target, Target::Rust);
418    }
419
420    #[test]
421    fn no_flags_default_rust() {
422        let r = route(&[]);
423        assert_eq!(r.target, Target::Rust);
424    }
425
426    // ---- every Rust-bound boundary flag ----
427
428    #[test]
429    fn zero_allocation_routes_to_rust() {
430        let r = route(&[attr(&["zero_allocation"])]);
431        assert_eq!(r.target, Target::Rust);
432    }
433
434    #[test]
435    fn crypto_routes_to_rust() {
436        let r = route(&[attr(&["crypto"])]);
437        assert_eq!(r.target, Target::Rust);
438    }
439
440    #[test]
441    fn real_time_routes_to_rust() {
442        let r = route(&[attr(&["real_time"])]);
443        assert_eq!(r.target, Target::Rust);
444    }
445
446    // ---- every Go-bound boundary flag ----
447
448    #[test]
449    fn high_concurrency_routes_to_go() {
450        let r = route(&[attr(&["high_concurrency"])]);
451        assert_eq!(r.target, Target::Go);
452    }
453
454    #[test]
455    fn distributed_routes_to_go() {
456        let r = route(&[attr(&["distributed"])]);
457        assert_eq!(r.target, Target::Go);
458    }
459
460    #[test]
461    fn high_latency_routes_to_go() {
462        let r = route(&[attr(&["high_latency"])]);
463        assert_eq!(r.target, Target::Go);
464    }
465
466    // ---- combinations ----
467
468    #[test]
469    fn multiple_rust_flags_still_rust() {
470        let r = route(&[attr(&["cpu_bound", "zero_allocation", "crypto"])]);
471        assert_eq!(r.target, Target::Rust);
472    }
473
474    #[test]
475    fn multiple_go_flags_still_go() {
476        let r = route(&[attr(&["network_io", "high_concurrency"])]);
477        assert_eq!(r.target, Target::Go);
478    }
479
480    #[test]
481    fn go_flag_wins_over_rust_flag() {
482        // A mixed annotation is treated as a Go (distributed/network) target.
483        let r = route(&[attr(&["cpu_bound", "network_io"])]);
484        assert_eq!(r.target, Target::Go);
485    }
486
487    #[test]
488    fn unrecognised_flag_defaults_to_rust() {
489        // Unknown flags contribute nothing; the default compute backend applies.
490        let r = route(&[attr(&["some_future_flag"])]);
491        assert_eq!(r.target, Target::Rust);
492    }
493
494    #[test]
495    fn unrecognised_boundary_flag_emits_diagnostic() {
496        let (r, diags) = route_checked(&[attr(&["some_future_flag"])], "MyModule");
497        assert_eq!(r.target, Target::Rust);
498        assert!(diags
499            .iter()
500            .any(|d| d.kind == DiagnosticKind::UnrecognizedBoundaryFlag));
501    }
502
503    #[test]
504    fn route_records_justification() {
505        let r = route(&[attr(&["network_io"])]);
506        assert!(r.reason.contains("network_io"));
507        assert!(r.is_rust() == (r.target == Target::Rust));
508    }
509
510    // ---- Python target ----
511
512    #[test]
513    fn ml_training_routes_to_python() {
514        let r = route(&[attr(&["ml_training"])]);
515        assert_eq!(r.target, Target::Python);
516    }
517
518    #[test]
519    fn python_flag_routes_to_python() {
520        let r = route(&[attr(&["python"])]);
521        assert_eq!(r.target, Target::Python);
522    }
523
524    #[test]
525    fn jax_flag_routes_to_python() {
526        let r = route(&[attr(&["jax"])]);
527        assert_eq!(r.target, Target::Python);
528    }
529
530    #[test]
531    fn python_beats_go_flag() {
532        // ml_training takes priority over network_io.
533        let r = route(&[attr(&["ml_training", "network_io"])]);
534        assert_eq!(r.target, Target::Python);
535    }
536
537    // ---- Real-time conflict diagnostics ----
538
539    #[test]
540    fn real_time_go_conflict_emits_diagnostic() {
541        let (r, diags) = route_checked(&[attr(&["real_time", "network_io"])], "ControlLoop");
542        assert_eq!(r.target, Target::Go);
543        assert!(diags
544            .iter()
545            .any(|d| d.kind == DiagnosticKind::RealTimeGoConflict));
546    }
547
548    #[test]
549    fn zero_alloc_go_conflict_emits_diagnostic() {
550        let (r, diags) = route_checked(&[attr(&["zero_allocation", "high_concurrency"])], "Buffer");
551        assert_eq!(r.target, Target::Go);
552        assert!(diags
553            .iter()
554            .any(|d| d.kind == DiagnosticKind::ZeroAllocGoConflict));
555    }
556
557    #[test]
558    fn real_time_alone_has_no_diagnostics() {
559        let (r, diags) = route_checked(&[attr(&["real_time"])], "FADEC");
560        assert_eq!(r.target, Target::Rust);
561        assert!(diags.is_empty());
562    }
563
564    #[test]
565    fn python_target_has_no_diagnostics() {
566        let (r, diags) = route_checked(&[attr(&["ml_training"])], "TrainLayer");
567        assert_eq!(r.target, Target::Python);
568        assert!(diags.is_empty());
569    }
570
571    // ---- Storage class ----
572
573    fn state_attr(class: &str) -> Attribute {
574        Attribute {
575            name: "state".to_string(),
576            args: vec![Arg::Flag(class.to_string())],
577        }
578    }
579
580    #[test]
581    fn state_persistent_sets_storage_class() {
582        let r = route(&[state_attr("persistent")]);
583        assert_eq!(r.storage, StorageClass::Persistent);
584    }
585
586    #[test]
587    fn state_ephemeral_sets_storage_class() {
588        let r = route(&[state_attr("ephemeral")]);
589        assert_eq!(r.storage, StorageClass::Ephemeral);
590    }
591
592    #[test]
593    fn no_state_defaults_to_ephemeral() {
594        let r = route(&[]);
595        assert_eq!(r.storage, StorageClass::Ephemeral);
596    }
597
598    #[test]
599    fn state_with_boundary_combines() {
600        let boundary = attr(&["network_io"]);
601        let state = state_attr("persistent");
602        let r = route(&[boundary, state]);
603        assert_eq!(r.target, Target::Go);
604        assert_eq!(r.storage, StorageClass::Persistent);
605    }
606}