operonx 0.7.1

High-performance Rust execution backend for Operon workflows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Op type enum, op-bound enum, and the **serialized op configuration** types.
//!
//! Mirrors Python's `op_config.py` + the flat dict emitted by
//! `BaseOp.serialize()` / `GraphOp.serialize()`. Instead of a per-variant Rust
//! enum (which would fight serde's tag/untagged modes when upstream JSON is a
//! single flat dict), we use one flat [`OpConfig`] struct that carries every
//! possible field. Dispatch happens at runtime on the `kind` tag — matches how
//! Python writes its configs.
//!
//! # Phase 4 scope
//! - [`OpType`] / [`OpBound`] — already existed; preserved.
//! - [`OpConfig`] — new. Covers base-op metadata + the `FuncOp` flags
//!   (`func_name`, `is_async`, `is_generator`) + the `GraphOp` extras
//!   (`ops`, `edges`, `entries`, `exits`, `initial_ready_count`,
//!   `compiled_adj`, `stream_initial_ready`, `loop_config`,
//!   `max_stream_concurrent`).
//! - [`CompiledLink`] — `[dst, soft]` tuple encoding emitted by Python.
//! - [`LoopConfig`] — `until: Option<String>` + `max_iterations`. Loop vars are
//!   *not* a dedicated field — they ride on normal `inputs`. See §4b.2.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::edge_config::EdgeConfig;
use crate::core::ops::cache::CacheConfig;
use crate::core::states::ref_::RefConfig;
use crate::core::utils::common::Param;

/// One condition → target case in a [`BranchOp`](OpType::Branch).
///
/// Python emits this as `{"condition": <RefConfig>, "target": "name"}`.
/// The condition is a Ref whose chain of `transforms` evaluates to a
/// truthy value when this case should fire.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BranchCase {
    pub condition: RefConfig,
    pub target: String,
}

/// All op types supported in a workflow graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OpType {
    // Data
    #[serde(rename = "data")]
    Data,

    // AI / ML
    #[serde(rename = "llm")]
    Llm,
    #[serde(rename = "embedding")]
    Embedding,
    #[serde(rename = "rerank")]
    Rerank,

    // Control flow
    #[serde(rename = "branch")]
    Branch,
    #[serde(rename = "for")]
    ForLoop,
    #[serde(rename = "while")]
    WhileLoop,
    #[serde(rename = "stream")]
    Stream,

    // Processing
    #[serde(rename = "code")]
    Code,
    #[serde(rename = "lambda")]
    Lambda,
    #[serde(rename = "parser")]
    Parser,
    #[serde(rename = "prompt")]
    Prompt,
    #[serde(rename = "doc-processor")]
    DocProcessor,

    // Database / storage
    #[serde(rename = "milvus")]
    Milvus,
    #[serde(rename = "mongo")]
    Mongo,
    #[serde(rename = "s3")]
    S3,

    // Special
    #[serde(rename = "graph")]
    Graph,
    #[serde(rename = "default")]
    Default,
    #[serde(rename = "dummy")]
    Dummy,
    #[serde(rename = "tool-executor")]
    ToolExecutor,
    #[serde(rename = "mcp")]
    Mcp,

    /// Triton Inference Server. **Not in Python's `Literal[...]` declaration**
    /// but set at runtime by [`TritonOp`](../../providers/ops/triton). The
    /// discrepancy is a known inconsistency on the Python side — Rust
    /// mirrors runtime behavior.
    #[serde(rename = "triton")]
    Triton,

    /// ONNX inference. Same Python-side inconsistency as `Triton` — set at
    /// runtime by [`OnnxOp`](../../providers/ops/onnx) despite missing from
    /// the `Literal[...]` declaration.
    #[serde(rename = "onnx")]
    Onnx,
}

impl Default for OpType {
    fn default() -> Self {
        OpType::Default
    }
}

impl OpType {
    /// Returns the Python string literal for this op type.
    pub fn as_str(&self) -> &'static str {
        match self {
            OpType::Data => "data",
            OpType::Llm => "llm",
            OpType::Embedding => "embedding",
            OpType::Rerank => "rerank",
            OpType::Branch => "branch",
            OpType::ForLoop => "for",
            OpType::WhileLoop => "while",
            OpType::Stream => "stream",
            OpType::Code => "code",
            OpType::Lambda => "lambda",
            OpType::Parser => "parser",
            OpType::Prompt => "prompt",
            OpType::DocProcessor => "doc-processor",
            OpType::Milvus => "milvus",
            OpType::Mongo => "mongo",
            OpType::S3 => "s3",
            OpType::Graph => "graph",
            OpType::Default => "default",
            OpType::Dummy => "dummy",
            OpType::ToolExecutor => "tool-executor",
            OpType::Mcp => "mcp",
            OpType::Triton => "triton",
            OpType::Onnx => "onnx",
        }
    }
}

/// Execution-bound hint — scheduler uses this to pick a dispatch strategy.
///
/// Mirrors Python's `bound: "sync" | "io" | "cpu"` field on `BaseOp`.
/// See MIGRATION_rust.md §3b for dispatch mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum OpBound {
    /// Run inline on the scheduler thread. Fastest. For trivial / sync Rust ops.
    #[default]
    Sync,
    /// I/O-bound — `tokio::spawn`. For HTTP, LLM streams, disk.
    Io,
    /// CPU-bound — `rayon::spawn`. For ONNX, heavy compute. Keeps tokio workers free.
    Cpu,
}

// ── Compiled adjacency link ───────────────────────────────────────────────

/// One entry in [`OpConfig::compiled_adj`]. Python emits these as `[dst, soft]`
/// (a JSON array, not an object) — we mirror that on the wire.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CompiledLink {
    pub dst: String,
    pub soft: bool,
}

impl Serialize for CompiledLink {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeTuple;
        let mut tup = serializer.serialize_tuple(2)?;
        tup.serialize_element(&self.dst)?;
        tup.serialize_element(&self.soft)?;
        tup.end()
    }
}

impl<'de> Deserialize<'de> for CompiledLink {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let (dst, soft) = <(String, bool)>::deserialize(deserializer)?;
        Ok(CompiledLink { dst, soft })
    }
}

// ── LoopConfig ────────────────────────────────────────────────────────────

/// Loop-control block for [`GraphOp::loop`](../../ops/graph/graph_op/struct.GraphOp.html#method.loop).
///
/// Per §4b.2 the `until` field is **strings only** (callable conditions are
/// dropped at Python serialization time), and there is **no `loop_vars`
/// field** — loop state is carried through ordinary `inputs`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct LoopConfig {
    #[serde(default)]
    pub until: Option<String>,
    #[serde(default)]
    pub max_iterations: Option<u32>,
}

// ── OpConfig — the serialized form of any op ──────────────────────────────

fn true_default() -> bool {
    true
}

fn default_concurrency() -> u32 {
    64
}

/// The runtime's view of one serialized op — flat, all-fields-present.
///
/// Matches the dict emitted by `BaseOp.serialize()` + `GraphOp.serialize()`.
/// Fields not applicable to a given `kind` stay at their defaults (`None`,
/// empty collection, etc.). Dispatch at the scheduler layer reads `kind` and
/// picks which fields to consult.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpConfig {
    // ── Base metadata (every op) ──────────────────────────────────────────
    #[serde(rename = "type")]
    pub kind: OpType,

    pub name: String,

    #[serde(default)]
    pub full_name: String,

    #[serde(default = "true_default")]
    pub enabled: bool,

    #[serde(default)]
    pub verbose: bool,

    #[serde(default)]
    pub stream: bool,

    #[serde(default)]
    pub bound: OpBound,

    #[serde(default)]
    pub inputs: BTreeMap<String, Param>,

    #[serde(default)]
    pub outputs: BTreeMap<String, Param>,

    #[serde(default)]
    pub cache: Option<CacheConfig>,

    #[serde(default)]
    pub delay: f64,

    #[serde(default)]
    pub description: Option<String>,

    // ── FuncOp (`type = "code"`) fields ───────────────────────────────────
    #[serde(default)]
    pub func_name: Option<String>,

    #[serde(default)]
    pub is_async: bool,

    #[serde(default)]
    pub is_generator: bool,

    // ── BranchOp (`type = "branch"`) fields ───────────────────────────────
    /// Ordered (condition, target) cases. The first case whose condition
    /// evaluates truthy wins. Python's `BranchOp.serialize()` emits the
    /// condition as a `Ref` with `transforms` (e.g. an `eq` / `ge` pair).
    #[serde(default)]
    pub cases: Vec<BranchCase>,

    /// Fallback target when no case matches. `None` surfaces a runtime
    /// error in that scenario.
    #[serde(default)]
    pub default: Option<String>,

    /// Explicit list of valid target names. Optional — when omitted, the
    /// runtime can derive it from `cases` + `default`.
    #[serde(default)]
    pub candidates: Option<Vec<String>>,

    // ── GraphOp (`type = "graph"`) fields ─────────────────────────────────
    #[serde(default)]
    pub ops: BTreeMap<String, OpConfig>,

    #[serde(default)]
    pub edges: Vec<EdgeConfig>,

    #[serde(default)]
    pub entries: Vec<String>,

    #[serde(default)]
    pub exits: Vec<String>,

    #[serde(default)]
    pub initial_ready_count: BTreeMap<String, i32>,

    #[serde(default)]
    pub compiled_adj: BTreeMap<String, Vec<CompiledLink>>,

    #[serde(default)]
    pub stream_initial_ready: BTreeMap<String, BTreeMap<String, i32>>,

    #[serde(default)]
    pub loop_config: Option<LoopConfig>,

    #[serde(default = "default_concurrency")]
    pub max_stream_concurrent: u32,

    // ── Provider-op fields (LLMOp / EmbeddingOp / RerankOp / OnnxOp /
    //    TritonOp). Flat extensions set by `LLMOp.serialize()` etc. ────────
    /// Resource key(s) for the backend to use. String for single-model ops,
    /// list for load-balanced LLMs.
    #[serde(default)]
    pub resource: Option<Value>,

    /// Weighted load-balancing ratios (length matches `resource` when list).
    #[serde(default)]
    pub ratios: Option<Vec<f32>>,

    /// Ordered fallback chain — tried when the primary resource errors.
    #[serde(default)]
    pub fallback: Option<Vec<String>>,

    /// OpenAI Batch API mode (50% cheaper, async polling).
    #[serde(default)]
    pub batch_mode: bool,

    /// Per-LLM embedded backend configs — Python serializes full
    /// `LLMConfig`/`EmbeddingConfig`/etc dicts under this key.
    #[serde(default)]
    pub resource_config: Option<Value>,
    #[serde(default)]
    pub resource_configs: Vec<Value>,
    #[serde(default)]
    pub fallback_configs: Vec<Value>,

    /// Triton input/output tensor-name mapping.
    #[serde(default)]
    pub inputs_map: BTreeMap<String, String>,
    #[serde(default)]
    pub outputs_map: BTreeMap<String, String>,

    // ── Python-only field explicitly dropped on deserialize ───────────────
    /// `python_callable` rides on Python's internal dict but must not be
    /// deserialized into Rust. We accept it (so `deny_unknown_fields` configs
    /// round-trip) and never re-emit it.
    #[serde(default, skip_serializing, rename = "python_callable")]
    pub python_callable: Option<Value>,
}

impl Default for OpConfig {
    fn default() -> Self {
        Self {
            kind: OpType::default(),
            name: String::new(),
            full_name: String::new(),
            enabled: true,
            verbose: false,
            stream: false,
            bound: OpBound::default(),
            inputs: BTreeMap::new(),
            outputs: BTreeMap::new(),
            cache: None,
            delay: 0.0,
            description: None,
            func_name: None,
            is_async: false,
            is_generator: false,
            cases: Vec::new(),
            default: None,
            candidates: None,
            ops: BTreeMap::new(),
            edges: Vec::new(),
            entries: Vec::new(),
            exits: Vec::new(),
            initial_ready_count: BTreeMap::new(),
            compiled_adj: BTreeMap::new(),
            stream_initial_ready: BTreeMap::new(),
            loop_config: None,
            max_stream_concurrent: default_concurrency(),
            resource: None,
            ratios: None,
            fallback: None,
            batch_mode: false,
            resource_config: None,
            resource_configs: Vec::new(),
            fallback_configs: Vec::new(),
            inputs_map: BTreeMap::new(),
            outputs_map: BTreeMap::new(),
            python_callable: None,
        }
    }
}

impl OpConfig {
    /// Normalize `resource` into a `Vec<String>`:
    /// - `None` → `[]`
    /// - `Some(String("x"))` → `["x"]`
    /// - `Some(Array(["x","y"]))` → `["x","y"]`
    pub fn resource_keys(&self) -> Vec<String> {
        match &self.resource {
            None | Some(Value::Null) => Vec::new(),
            Some(Value::String(s)) => vec![s.clone()],
            Some(Value::Array(arr)) => arr
                .iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect(),
            _ => Vec::new(),
        }
    }

    /// `true` if this op's resource is a list (triggers load-balanced
    /// selection).
    pub fn is_multi_resource(&self) -> bool {
        matches!(&self.resource, Some(Value::Array(_)))
    }
}

impl OpConfig {
    /// `true` if this config describes a nested graph (`kind == Graph`).
    pub fn is_graph(&self) -> bool {
        matches!(self.kind, OpType::Graph)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn compiled_link_roundtrips_as_tuple() {
        let link = CompiledLink {
            dst: "next".into(),
            soft: true,
        };
        let json = serde_json::to_string(&link).unwrap();
        assert_eq!(json, r#"["next",true]"#);
        let back: CompiledLink = serde_json::from_str(&json).unwrap();
        assert_eq!(back, link);
    }

    #[test]
    fn op_config_parses_graph_envelope() {
        let src = r#"{
            "type": "graph",
            "name": "main",
            "full_name": "main",
            "ops": {},
            "edges": [],
            "entries": [],
            "exits": [],
            "initial_ready_count": {},
            "compiled_adj": {},
            "stream_initial_ready": {}
        }"#;
        let cfg: OpConfig = serde_json::from_str(src).unwrap();
        assert!(cfg.is_graph());
        assert_eq!(cfg.name, "main");
        assert_eq!(cfg.max_stream_concurrent, 64);
    }

    #[test]
    fn op_config_parses_func_op() {
        let src = r#"{
            "type": "code",
            "name": "double",
            "full_name": "main.double",
            "func_name": "double",
            "is_async": false,
            "is_generator": false,
            "bound": "sync"
        }"#;
        let cfg: OpConfig = serde_json::from_str(src).unwrap();
        assert!(!cfg.is_graph());
        assert_eq!(cfg.kind, OpType::Code);
        assert_eq!(cfg.func_name.as_deref(), Some("double"));
        assert_eq!(cfg.bound, OpBound::Sync);
    }

    #[test]
    fn python_callable_is_accepted_and_dropped_on_reserialize() {
        let src = r#"{
            "type": "code",
            "name": "f",
            "full_name": "main.f",
            "python_callable": "<function f at 0x…>"
        }"#;
        let cfg: OpConfig = serde_json::from_str(src).unwrap();
        // Survives round-trip without emitting the field.
        let out = serde_json::to_string(&cfg).unwrap();
        assert!(!out.contains("python_callable"));
    }

    #[test]
    fn loop_config_only_accepts_string_until() {
        let src = r#"{"until": "count >= 5", "max_iterations": 10}"#;
        let cfg: LoopConfig = serde_json::from_str(src).unwrap();
        assert_eq!(cfg.until.as_deref(), Some("count >= 5"));
        assert_eq!(cfg.max_iterations, Some(10));

        let none_src = r#"{"until": null, "max_iterations": null}"#;
        let cfg: LoopConfig = serde_json::from_str(none_src).unwrap();
        assert!(cfg.until.is_none());
        assert!(cfg.max_iterations.is_none());
    }
}