meerkat-mob 0.8.11

Multi-agent orchestration runtime for Meerkat
Documentation
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
//! Pure condition evaluator for flow specs.

use super::path::{PathResolveError, resolve_context_path};
use crate::definition::ConditionExpr;
use crate::run::FlowContext;
use serde_json::Value;

/// Outcome of resolving a leaf operand path against the flow context.
///
/// A leaf comparison (`Eq`/`In`/`Gt`/`Lt`) distinguishes three cases:
/// - the value is present (`Present`),
/// - the named context root is simply not produced yet (`AbsentRoot`) — a
///   legitimate "not present" signal, not a fault,
/// - the reference is structurally invalid (`StructuralFault`) — a typo'd key
///   inside a present root, an unparsable reference, or a walk into a scalar.
enum OperandResolution<'a> {
    Present(&'a Value),
    AbsentRoot,
    StructuralFault(ConditionEvalError),
}

/// Resolve a leaf operand path, classifying an absent context root as a
/// definite "not present" rather than a fault.
///
/// `MissingRoot` means the named step/loop-iteration output has not been
/// produced yet. Conditions legitimately reference such roots to gate
/// first-vs-subsequent behavior (e.g. a loop-body step keyed on a prior
/// iteration's output that does not exist on the first pass). For a comparison
/// operand this is a definite "value not present", so the comparison is
/// `false` — exactly as the former `-> bool` evaluator behaved. Every other
/// resolution failure (typo'd key, unparsable reference, scalar walk) remains a
/// structural fault that the caller surfaces as a step/flow fault.
fn resolve_operand<'a>(ctx: &'a FlowContext, path: &str) -> OperandResolution<'a> {
    match resolve_context_path(ctx, path) {
        Ok(value) => OperandResolution::Present(value),
        Err(PathResolveError::MissingRoot { .. }) => OperandResolution::AbsentRoot,
        Err(error) => OperandResolution::StructuralFault(ConditionEvalError::UnresolvedPath(error)),
    }
}

/// Why a condition expression could not be evaluated to a definite boolean.
///
/// A condition references runtime context that must exist and be of a
/// comparable shape. The former `-> bool` evaluator collapsed *every* such
/// fault (missing path, non-comparable operand types) into a silent `false`,
/// so a typo in a `path` or a schema-violating step output would skip a step
/// rather than surface a flow fault. These are now typed and propagated by the
/// caller as a step/flow fault — EXCEPT an absent context root, which remains a
/// definite "not present" so conditions can gate on not-yet-produced outputs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ConditionEvalError {
    /// The referenced context path did not resolve to a present value.
    UnresolvedPath(PathResolveError),
    /// A relational comparison (`Gt`/`Lt`) was attempted on operands that are
    /// not mutually comparable (e.g. number vs string, or a non-scalar value).
    IncomparableOperands {
        path: String,
        left: Value,
        right: Value,
    },
}

impl std::fmt::Display for ConditionEvalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnresolvedPath(error) => {
                write!(f, "condition path did not resolve: {error}")
            }
            Self::IncomparableOperands { path, left, right } => write!(
                f,
                "condition path '{path}' value {left} is not comparable to {right}"
            ),
        }
    }
}

impl From<PathResolveError> for ConditionEvalError {
    fn from(error: PathResolveError) -> Self {
        Self::UnresolvedPath(error)
    }
}

/// Evaluate a condition expression against runtime flow context.
///
/// Fails closed on STRUCTURAL faults: a typo'd key inside a present root, an
/// unparsable reference, or non-comparable operands surface as a typed
/// [`ConditionEvalError`] rather than silently evaluating to `false`. An absent
/// context root (a step/loop-iteration output not yet produced) is a definite
/// "not present" and resolves a comparison to `false`, so conditions can gate
/// on not-yet-produced outputs without faulting the step.
pub(crate) fn evaluate_condition(
    expr: &ConditionExpr,
    ctx: &FlowContext,
) -> Result<bool, ConditionEvalError> {
    match expr {
        ConditionExpr::Eq { path, value } => match resolve_operand(ctx, path) {
            OperandResolution::Present(resolved) => Ok(resolved == value),
            OperandResolution::AbsentRoot => Ok(false),
            OperandResolution::StructuralFault(error) => Err(error),
        },
        ConditionExpr::In { path, values } => match resolve_operand(ctx, path) {
            OperandResolution::Present(resolved) => Ok(values.contains(resolved)),
            OperandResolution::AbsentRoot => Ok(false),
            OperandResolution::StructuralFault(error) => Err(error),
        },
        ConditionExpr::Gt { path, value } => match resolve_operand(ctx, path) {
            OperandResolution::Present(resolved) => {
                Ok(compare_values(resolved, value, path)?.is_gt())
            }
            OperandResolution::AbsentRoot => Ok(false),
            OperandResolution::StructuralFault(error) => Err(error),
        },
        ConditionExpr::Lt { path, value } => match resolve_operand(ctx, path) {
            OperandResolution::Present(resolved) => {
                Ok(compare_values(resolved, value, path)?.is_lt())
            }
            OperandResolution::AbsentRoot => Ok(false),
            OperandResolution::StructuralFault(error) => Err(error),
        },
        ConditionExpr::And { exprs } => {
            for expr in exprs {
                if !evaluate_condition(expr, ctx)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        ConditionExpr::Or { exprs } => {
            for expr in exprs {
                if evaluate_condition(expr, ctx)? {
                    return Ok(true);
                }
            }
            Ok(false)
        }
        ConditionExpr::Not { expr } => Ok(!evaluate_condition(expr, ctx)?),
    }
}

fn compare_values(
    left: &Value,
    right: &Value,
    path: &str,
) -> Result<std::cmp::Ordering, ConditionEvalError> {
    let incomparable = || ConditionEvalError::IncomparableOperands {
        path: path.to_string(),
        left: left.clone(),
        right: right.clone(),
    };
    match (left, right) {
        (Value::Number(left_n), Value::Number(right_n)) => {
            let left_f = left_n.as_f64().ok_or_else(incomparable)?;
            let right_f = right_n.as_f64().ok_or_else(incomparable)?;
            left_f.partial_cmp(&right_f).ok_or_else(incomparable)
        }
        (Value::String(left_s), Value::String(right_s)) => Ok(left_s.cmp(right_s)),
        _ => Err(incomparable()),
    }
}

#[cfg(test)]
pub mod test_doubles {
    use serde_json::Value;
    use std::collections::VecDeque;

    /// Reusable adversarial step behavior fixture for flow runtime tests.
    #[derive(Debug, Clone)]
    pub enum MockStepBehavior {
        FailThenSucceed {
            failures_before_success: usize,
            success_payload: Value,
        },
        SchemaInvalid {
            payload: Value,
        },
        NeverResponds,
        UnexpectedType {
            payload: Value,
        },
        Success {
            payload: Value,
        },
    }

    /// One step result produced by a mock behavior.
    #[derive(Debug, Clone, PartialEq)]
    pub enum MockStepOutcome {
        Failure(String),
        SchemaInvalid(Value),
        NeverResponds,
        UnexpectedType(Value),
        Success(Value),
    }

    /// Queue-based driver that can be shared by runtime integration tests.
    #[derive(Debug, Default, Clone)]
    pub struct MockFlowStepDriver {
        behaviors: VecDeque<MockStepBehavior>,
    }

    impl MockFlowStepDriver {
        pub fn from_behaviors(behaviors: impl IntoIterator<Item = MockStepBehavior>) -> Self {
            Self {
                behaviors: behaviors.into_iter().collect(),
            }
        }

        pub fn next_outcome(&mut self) -> Option<MockStepOutcome> {
            let behavior = self.behaviors.pop_front()?;
            match behavior {
                MockStepBehavior::FailThenSucceed {
                    failures_before_success,
                    success_payload,
                } => {
                    if failures_before_success == 0 {
                        Some(MockStepOutcome::Success(success_payload))
                    } else {
                        self.behaviors
                            .push_front(MockStepBehavior::FailThenSucceed {
                                failures_before_success: failures_before_success - 1,
                                success_payload,
                            });
                        Some(MockStepOutcome::Failure("transient failure".to_string()))
                    }
                }
                MockStepBehavior::SchemaInvalid { payload } => {
                    Some(MockStepOutcome::SchemaInvalid(payload))
                }
                MockStepBehavior::NeverResponds => Some(MockStepOutcome::NeverResponds),
                MockStepBehavior::UnexpectedType { payload } => {
                    Some(MockStepOutcome::UnexpectedType(payload))
                }
                MockStepBehavior::Success { payload } => Some(MockStepOutcome::Success(payload)),
            }
        }
    }

    #[test]
    fn test_mock_driver_fail_then_succeed() {
        let mut driver = MockFlowStepDriver::from_behaviors([MockStepBehavior::FailThenSucceed {
            failures_before_success: 1,
            success_payload: serde_json::json!({"ok":true}),
        }]);

        assert!(matches!(
            driver.next_outcome(),
            Some(MockStepOutcome::Failure(_))
        ));
        assert_eq!(
            driver.next_outcome(),
            Some(MockStepOutcome::Success(serde_json::json!({"ok":true})))
        );
    }

    #[test]
    fn test_mock_driver_schema_invalid() {
        let mut driver = MockFlowStepDriver::from_behaviors([MockStepBehavior::SchemaInvalid {
            payload: serde_json::json!({"broken":true}),
        }]);
        assert_eq!(
            driver.next_outcome(),
            Some(MockStepOutcome::SchemaInvalid(
                serde_json::json!({"broken":true})
            ))
        );
    }

    #[test]
    fn test_mock_driver_never_responds() {
        let mut driver = MockFlowStepDriver::from_behaviors([MockStepBehavior::NeverResponds]);
        assert_eq!(driver.next_outcome(), Some(MockStepOutcome::NeverResponds));
    }

    #[test]
    fn test_mock_driver_unexpected_type() {
        let mut driver = MockFlowStepDriver::from_behaviors([MockStepBehavior::UnexpectedType {
            payload: serde_json::json!(["not", "an", "object"]),
        }]);
        assert_eq!(
            driver.next_outcome(),
            Some(MockStepOutcome::UnexpectedType(serde_json::json!([
                "not", "an", "object"
            ])))
        );
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;
    use crate::definition::ConditionExpr;
    use crate::ids::{RunId, StepId};
    use indexmap::IndexMap;

    fn context() -> FlowContext {
        let mut step_outputs = IndexMap::new();
        step_outputs.insert(
            StepId::from("step-a"),
            serde_json::json!({
                "score": 9,
                "nested": { "ok": true }
            }),
        );
        FlowContext {
            run_id: RunId::new(),
            activation_params: serde_json::json!({
                "priority": 2,
                "region": "us",
                "flags": ["a", "b"]
            }),
            step_outputs,
            loop_outputs: indexmap::IndexMap::new(),
        }
    }

    #[test]
    fn test_evaluate_eq_and_in() {
        let ctx = context();
        let eq = ConditionExpr::Eq {
            path: "params.region".to_string(),
            value: serde_json::json!("us"),
        };
        let in_expr = ConditionExpr::In {
            path: "params.region".to_string(),
            values: vec![serde_json::json!("eu"), serde_json::json!("us")],
        };
        assert!(evaluate_condition(&eq, &ctx).expect("eq should resolve"));
        assert!(evaluate_condition(&in_expr, &ctx).expect("in should resolve"));
    }

    #[test]
    fn test_evaluate_gt_lt_and_boolean_composition() {
        let ctx = context();
        let gt = ConditionExpr::Gt {
            path: "steps.step-a.score".to_string(),
            value: serde_json::json!(5),
        };
        let lt = ConditionExpr::Lt {
            path: "params.priority".to_string(),
            value: serde_json::json!(3),
        };
        let and = ConditionExpr::And {
            exprs: vec![gt, lt],
        };
        assert!(evaluate_condition(&and, &ctx).expect("and should resolve"));

        let not = ConditionExpr::Not {
            expr: Box::new(ConditionExpr::Eq {
                path: "params.region".to_string(),
                value: serde_json::json!("eu"),
            }),
        };
        let or = ConditionExpr::Or {
            exprs: vec![
                not,
                ConditionExpr::Eq {
                    path: "params.region".to_string(),
                    value: serde_json::json!("eu"),
                },
            ],
        };
        assert!(evaluate_condition(&or, &ctx).expect("or should resolve"));
    }

    #[test]
    fn test_evaluate_missing_path_fails_closed() {
        // Regression: a missing path used to evaluate silently to `false`,
        // skipping the step. It must now surface a typed fault so the flow
        // fails closed instead of silently mis-deciding the condition.
        let ctx = context();
        let expr = ConditionExpr::Eq {
            path: "steps.step-a.missing".to_string(),
            value: serde_json::json!(true),
        };
        let error = evaluate_condition(&expr, &ctx)
            .expect_err("a missing path must surface a typed fault, not silent false");
        assert!(matches!(
            error,
            ConditionEvalError::UnresolvedPath(PathResolveError::MissingSegment { .. })
        ));
    }

    #[test]
    fn test_evaluate_absent_root_resolves_false_not_fault() {
        // Regression guard: an absent context ROOT (a step/loop-iteration output
        // not yet produced) is a definite "not present", not a fault. A
        // comparison against it must evaluate to `false` so conditions can gate
        // on not-yet-produced outputs — exactly as the former `-> bool`
        // evaluator behaved. Only STRUCTURAL faults (typo'd keys inside a
        // present root, unparsable references) fail closed.
        let ctx = context();
        let expr = ConditionExpr::In {
            path: "steps.never-ran.value".to_string(),
            values: vec![serde_json::json!(1)],
        };
        assert!(
            !evaluate_condition(&expr, &ctx)
                .expect("an absent step root must resolve to a definite false, not a fault"),
            "absent root must compare as not-present (false)"
        );

        // An absent loop-iteration root (the exact shape the loop-body
        // conditions reference before the first iteration has run) is likewise
        // a definite "not present", not a fault.
        let loop_expr = ConditionExpr::Eq {
            path: "loops.never.iterations.0.steps.absent.done".to_string(),
            value: serde_json::json!(true),
        };
        assert!(
            !evaluate_condition(&loop_expr, &ctx)
                .expect("an absent loop-iteration root must resolve to a definite false"),
            "absent loop-iteration root must compare as not-present (false)"
        );
    }

    #[test]
    fn test_evaluate_incomparable_operands_fail_closed() {
        // A relational comparison between a string and a number must fail
        // closed rather than silently evaluating to `false`.
        let ctx = context();
        let gt = ConditionExpr::Gt {
            path: "params.region".to_string(),
            value: serde_json::json!(5),
        };
        let error = evaluate_condition(&gt, &ctx)
            .expect_err("incomparable operands must surface a typed fault");
        assert!(matches!(
            error,
            ConditionEvalError::IncomparableOperands { .. }
        ));
    }

    #[test]
    fn test_evaluate_present_null_compares_as_value() {
        // A present-null is a value that exists; `Eq` against null is a real
        // comparison, not an unresolved-path fault.
        let mut step_outputs = IndexMap::new();
        step_outputs.insert(StepId::from("step-a"), serde_json::json!({"maybe": null}));
        let ctx = FlowContext {
            run_id: RunId::new(),
            activation_params: serde_json::json!({}),
            step_outputs,
            loop_outputs: indexmap::IndexMap::new(),
        };
        let expr = ConditionExpr::Eq {
            path: "steps.step-a.maybe".to_string(),
            value: serde_json::Value::Null,
        };
        assert!(
            evaluate_condition(&expr, &ctx).expect("present-null eq should resolve"),
            "present-null must compare equal to null"
        );
    }
}