graphrt-core 0.11.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! `rule-check`: declarative checks of values, such as the quality checks of a
//! report's numbers before it goes out.
//!
//! Each rule names its values with an expression (`facts.uplift.control_size < 30`,
//! Jinja2 syntax, the same sandboxed engine as `template-transform`) and raises
//! a flag with a severity and a message when the expression is true. `for_each`
//! checks every item of a list (`item`, `index`). Rules live in the workflow, not
//! in a code node, so a business reader can change a threshold.
//!
//! A key the data does not have is undefined and a selector with no value is
//! none: both render as an empty text, a `for_each` over them checks nothing,
//! and both compare below every number (values of different kinds compare by
//! kind), so a threshold on a value that may be missing or not a number is
//! guarded (`x is number and x < 30`).
//!
//! Outputs: `flags` (`[{rule, severity, section?, message}]`), `passed` (no flag
//! of severity `error`), `errors`, `warnings`, `infos` and `notes` (one line per
//! flag). With `on_fail: error` a flag of severity `error` fails the node (kind
//! `rule_check`).

use std::sync::Arc;

use futures::future::BoxFuture;
use indexmap::IndexMap;
use minijinja::{Environment, UndefinedBehavior};
use serde::Deserialize;

use crate::dsl::NodeDoc;
use crate::node::{ConfigError, Node, NodeContext, NodeError, NodeOutput, NodeResult};
use crate::pool::{Selector, VariablePool};
use crate::value::Value;

/// Error kind of a failed check with `on_fail: error`.
pub const FAILED: &str = "rule_check";
/// At most this many flags are reported.
pub const MAX_FLAGS: usize = 200;
/// Flags named in the error message of a failed check.
const FLAGS_IN_ERROR: usize = 10;
/// Names the rules cannot give a value: `for_each` binds them.
const RESERVED: [&str; 2] = ["item", "index"];

/// How serious a flag is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// The value is wrong: with `on_fail: error` the node fails.
    Error,
    /// Someone should look at it (default).
    #[default]
    Warning,
    /// Worth knowing.
    Info,
}

impl Severity {
    fn as_str(self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "info",
        }
    }
}

/// What a check with error flags does.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OnFail {
    /// Report the flags in the outputs (default).
    #[default]
    Output,
    /// Fail the node when a flag of severity `error` is raised.
    Error,
}

/// One rule as written.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuleSpec {
    /// Name of the rule in its flags (`uplift_small_control`).
    pub id: String,
    /// An expression: the rule raises a flag when it is true.
    pub when: String,
    /// The flag's message, a template (`Control group has {{ facts.uplift.control_size }} customers`).
    pub message: String,
    #[serde(default)]
    pub severity: Severity,
    /// What the flag is about (a report section), a template.
    #[serde(default)]
    pub section: Option<String>,
    /// An expression giving a list: the rule is checked for every item, as `item` (and `index`, from 0).
    #[serde(default)]
    pub for_each: Option<String>,
}

/// `rule-check` configuration as written.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RuleCheckConfig {
    /// The values the rules read, by name: `{facts: [extract, facts]}`.
    pub values: IndexMap<String, Selector>,
    pub rules: Vec<RuleSpec>,
    #[serde(default)]
    pub on_fail: OnFail,
}

/// A raised flag.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Flag {
    rule: String,
    severity: Severity,
    section: Option<String>,
    message: String,
}

impl Flag {
    fn to_value(&self) -> Value {
        let mut entries =
            vec![("rule", Value::from(self.rule.as_str())), ("severity", Value::from(self.severity.as_str()))];
        if let Some(section) = &self.section {
            entries.push(("section", Value::from(section.as_str())));
        }
        entries.push(("message", Value::from(self.message.as_str())));
        Value::object(entries)
    }

    fn line(&self) -> String {
        match &self.section {
            Some(section) => format!("- [{}] {section}: {} ({})", self.severity.as_str(), self.message, self.rule),
            None => format!("- [{}] {} ({})", self.severity.as_str(), self.message, self.rule),
        }
    }
}

/// The flags of a run: every flag counted, the first MAX_FLAGS kept.
#[derive(Debug, Default)]
struct Found {
    flags: Vec<Flag>,
    errors: usize,
    warnings: usize,
    infos: usize,
}

/// The `rule-check` node.
#[derive(Debug)]
pub struct RuleCheckNode {
    values: IndexMap<String, Selector>,
    rules: Vec<RuleSpec>,
    on_fail: OnFail,
    /// The rules' messages and sections, compiled once (`message:<n>`, `section:<n>`).
    env: Arc<Environment<'static>>,
}

fn message_template(index: usize) -> String {
    format!("message:{index}")
}

fn section_template(index: usize) -> String {
    format!("section:{index}")
}

impl RuleCheckNode {
    pub fn new(doc: &NodeDoc, config: RuleCheckConfig) -> Result<Self, ConfigError> {
        if config.values.is_empty() {
            return Err(ConfigError::new(doc, "give the values the rules read in `values`").at_field("values"));
        }
        if let Some(name) = config.values.keys().find(|name| RESERVED.contains(&name.as_str())) {
            return Err(ConfigError::new(
                doc,
                format!("`{name}` is the item of `for_each`; give the value another name"),
            )
            .at_field("values"));
        }
        if config.rules.is_empty() {
            return Err(ConfigError::new(doc, "give at least one rule").at_field("rules"));
        }
        let mut env = super::template_transform::sandboxed_env();
        env.set_undefined_behavior(UndefinedBehavior::Chainable);
        let mut ids: Vec<&str> = Vec::with_capacity(config.rules.len());
        for (index, rule) in config.rules.iter().enumerate() {
            let at = |field: &str| format!("rules[{index}].{field}");
            if rule.id.trim().is_empty() {
                return Err(ConfigError::new(doc, "a rule needs an `id`").at_field(at("id")));
            }
            if ids.contains(&rule.id.as_str()) {
                return Err(ConfigError::new(doc, format!("two rules have the id `{}`", rule.id)).at_field(at("id")));
            }
            ids.push(&rule.id);
            env.compile_expression(&rule.when).map_err(|e| {
                ConfigError::new(doc, format!("rule `{}`: invalid `when`: {e}", rule.id)).at_field(at("when"))
            })?;
            if let Some(list) = &rule.for_each {
                env.compile_expression(list).map_err(|e| {
                    ConfigError::new(doc, format!("rule `{}`: invalid `for_each`: {e}", rule.id))
                        .at_field(at("for_each"))
                })?;
            }
            env.add_template_owned(message_template(index), rule.message.clone()).map_err(|e| {
                ConfigError::new(doc, format!("rule `{}`: invalid `message`: {e}", rule.id)).at_field(at("message"))
            })?;
            if let Some(section) = &rule.section {
                env.add_template_owned(section_template(index), section.clone()).map_err(|e| {
                    ConfigError::new(doc, format!("rule `{}`: invalid `section`: {e}", rule.id)).at_field(at("section"))
                })?;
            }
        }
        Ok(Self { values: config.values, rules: config.rules, on_fail: config.on_fail, env: Arc::new(env) })
    }

    fn compute(&self, pool: &VariablePool) -> Result<NodeOutput, NodeError> {
        let values: Vec<(String, minijinja::Value)> = self
            .values
            .iter()
            .map(|(name, selector)| {
                (name.clone(), super::template_transform::to_template_value(pool.get(selector).unwrap_or(Value::Null)))
            })
            .collect();
        // Every rule is checked, so the counts, `passed` and `on_fail` see every flag; only the
        // reported list stops at MAX_FLAGS.
        let mut found = Found::default();
        for (index, rule) in self.rules.iter().enumerate() {
            match &rule.for_each {
                None => self.check(index, rule, context(&values, None), &mut found)?,
                Some(list) => {
                    let items = self.eval(rule, "for_each", list, context(&values, None))?;
                    if items.is_undefined() || items.is_none() {
                        continue;
                    }
                    let iter = items.try_iter().map_err(|e| {
                        NodeError::invalid_input(format!("rule `{}`: `for_each` must give a list: {e}", rule.id))
                    })?;
                    for (position, item) in iter.enumerate() {
                        self.check(index, rule, context(&values, Some((item, position))), &mut found)?;
                    }
                }
            }
        }
        let flags = &found.flags;
        let count = |n: usize| Value::Int(i64::try_from(n).unwrap_or(i64::MAX));
        let has_errors = found.errors > 0;
        if has_errors && self.on_fail == OnFail::Error {
            let named: Vec<String> = flags
                .iter()
                .filter(|flag| flag.severity == Severity::Error)
                .take(FLAGS_IN_ERROR)
                .map(|flag| format!("{}: {}", flag.rule, flag.message))
                .collect();
            let more = found.errors.saturating_sub(named.len());
            let tail = if more > 0 { format!("; and {more} more") } else { String::new() };
            return Err(NodeError::new(
                FAILED,
                format!("rule check failed with {} error(s): {}{tail}", found.errors, named.join("; ")),
            ));
        }
        Ok(NodeOutput::new()
            .with("passed", !has_errors)
            .with("errors", count(found.errors))
            .with("warnings", count(found.warnings))
            .with("infos", count(found.infos))
            .with("notes", flags.iter().map(Flag::line).collect::<Vec<_>>().join("\n"))
            .with("flags", Value::array(flags.iter().map(Flag::to_value))))
    }

    /// Checks one rule (for one item): counts its flag when `when` is true, and keeps it while
    /// fewer than MAX_FLAGS are kept.
    fn check(
        &self,
        index: usize,
        rule: &RuleSpec,
        context: minijinja::Value,
        found: &mut Found,
    ) -> Result<(), NodeError> {
        if !self.eval(rule, "when", &rule.when, context.clone())?.is_true() {
            return Ok(());
        }
        match rule.severity {
            Severity::Error => found.errors += 1,
            Severity::Warning => found.warnings += 1,
            Severity::Info => found.infos += 1,
        }
        if found.flags.len() >= MAX_FLAGS {
            return Ok(());
        }
        let message = self.render(rule, "message", &message_template(index), context.clone())?;
        let section = match rule.section {
            Some(_) => Some(self.render(rule, "section", &section_template(index), context)?),
            None => None,
        };
        found.flags.push(Flag { rule: rule.id.clone(), severity: rule.severity, section, message });
        Ok(())
    }

    fn eval(
        &self,
        rule: &RuleSpec,
        field: &str,
        expression: &str,
        context: minijinja::Value,
    ) -> Result<minijinja::Value, NodeError> {
        self.env
            .compile_expression(expression)
            .and_then(|compiled| compiled.eval(context))
            .map_err(|e| NodeError::invalid_input(format!("rule `{}`: `{field}` failed: {e}", rule.id)))
    }

    fn render(&self, rule: &RuleSpec, field: &str, name: &str, context: minijinja::Value) -> Result<String, NodeError> {
        self.env
            .get_template(name)
            .and_then(|template| template.render(context))
            .map_err(|e| NodeError::invalid_input(format!("rule `{}`: `{field}` failed: {e}", rule.id)))
    }
}

/// The names a rule reads: the values, and `item` and `index` of `for_each`.
fn context(values: &[(String, minijinja::Value)], item: Option<(minijinja::Value, usize)>) -> minijinja::Value {
    let mut entries: std::collections::BTreeMap<String, minijinja::Value> = values.iter().cloned().collect();
    if let Some((item, position)) = item {
        entries.insert("item".to_owned(), item);
        entries.insert("index".to_owned(), minijinja::Value::from(position));
    }
    minijinja::Value::from(entries)
}

impl Node for RuleCheckNode {
    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(async move { self.compute(&ctx.pool).map(Into::into) })
    }

    fn inputs(&self) -> Vec<Selector> {
        self.values.values().cloned().collect()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn node(config: serde_json::Value) -> Result<RuleCheckNode, ConfigError> {
        let doc = NodeDoc::new("qc", "rule-check", config);
        RuleCheckNode::new(&doc, crate::node::parse_config(&doc)?)
    }

    fn run(node: &RuleCheckNode, facts: serde_json::Value) -> Result<NodeOutput, NodeError> {
        let mut pool = VariablePool::new();
        pool.insert("prep", "facts", Value::from_json(facts));
        node.compute(&pool)
    }

    fn output(node: &RuleCheckNode, facts: serde_json::Value) -> serde_json::Value {
        let out = run(node, facts).unwrap();
        serde_json::Value::Object(out.outputs.iter().map(|(k, v)| (k.to_string(), v.to_json())).collect())
    }

    fn sales_rules(on_fail: &str) -> serde_json::Value {
        json!({
            "values": { "facts": ["prep", "facts"] },
            "on_fail": on_fail,
            "rules": [
                { "id": "small_sample", "when": "facts.orders is number and facts.orders < 30", "severity": "warning", "section": "overview",
                  "message": "Only {{ facts.orders }} orders: shares are not meaningful." },
                { "id": "negative_revenue", "for_each": "facts.stores", "when": "item.revenue is number and item.revenue < 0", "severity": "error",
                  "section": "stores", "message": "{{ item.name }} has negative revenue ({{ item.revenue }})." },
                { "id": "store_count", "when": "facts.stores | length > 2", "severity": "info",
                  "message": "{{ facts.stores | length }} stores this month." }
            ]
        })
    }

    #[test]
    fn rules_raise_flags_with_rendered_messages() {
        let check = node(sales_rules("output")).unwrap();
        let out = output(
            &check,
            json!({ "orders": 12, "stores": [
                { "name": "North", "revenue": 1200 }, { "name": "South", "revenue": -50 }, { "name": "East", "revenue": 0 }
            ] }),
        );
        assert_eq!(out["passed"], json!(false));
        assert_eq!(out["errors"], json!(1));
        assert_eq!(out["warnings"], json!(1));
        assert_eq!(out["infos"], json!(1));
        assert_eq!(
            out["flags"],
            json!([
                { "rule": "small_sample", "severity": "warning", "section": "overview", "message": "Only 12 orders: shares are not meaningful." },
                { "rule": "negative_revenue", "severity": "error", "section": "stores", "message": "South has negative revenue (-50)." },
                { "rule": "store_count", "severity": "info", "message": "3 stores this month." }
            ])
        );
        assert_eq!(
            out["notes"],
            json!(
                "- [warning] overview: Only 12 orders: shares are not meaningful. (small_sample)\n\
                 - [error] stores: South has negative revenue (-50). (negative_revenue)\n\
                 - [info] 3 stores this month. (store_count)"
            )
        );
    }

    #[test]
    fn messages_format_numbers_and_percentages() {
        let check = node(json!({
            "values": { "facts": ["prep", "facts"] },
            "rules": [
                { "id": "small_store", "for_each": "facts.stores", "when": "item.share < 0.05",
                  "section": "{{ item.name }}",
                  "message": "{{ item.name }}: {{ item.revenue | number }} revenue is only {{ item.share | percent(1) }} of {{ facts.total | number(2) }}." }
            ]
        }))
        .unwrap();
        let out = output(
            &check,
            json!({ "total": 2450000.5, "stores": [
                { "name": "North", "revenue": 2380000, "share": 0.9714 },
                { "name": "South", "revenue": 70000.5, "share": 0.02857 }
            ] }),
        );
        assert_eq!(
            out["flags"],
            json!([{ "rule": "small_store", "severity": "warning", "section": "South",
                     "message": "South: 70,001 revenue is only 2.9% of 2,450,000.50." }])
        );
    }

    #[test]
    fn a_clean_value_passes() {
        let check = node(sales_rules("output")).unwrap();
        let out = output(&check, json!({ "orders": 500, "stores": [{ "name": "North", "revenue": 10 }] }));
        assert_eq!(out["passed"], json!(true));
        assert_eq!(out["flags"], json!([]));
        assert_eq!(out["notes"], json!(""));
    }

    #[test]
    fn missing_values_raise_nothing() {
        // A value the facts do not have is undefined: `is number` guards a comparison, a list is empty.
        let check = node(sales_rules("output")).unwrap();
        let out = output(&check, json!({}));
        assert_eq!(out["flags"], json!([]));
        let out = output(&check, json!(null));
        assert_eq!(out["passed"], json!(true));
    }

    #[test]
    fn on_fail_error_fails_on_an_error_flag_only() {
        let check = node(sales_rules("error")).unwrap();
        let failed = run(&check, json!({ "orders": 500, "stores": [{ "name": "South", "revenue": -5 }] }));
        let message = failed.unwrap_err().to_string();
        assert!(
            message.contains("rule check failed with 1 error(s): negative_revenue: South has negative revenue (-5)."),
            "{message}"
        );
        // A warning alone does not fail the node.
        let out = output(&check, json!({ "orders": 3, "stores": [] }));
        assert_eq!(out["passed"], json!(true));
        assert_eq!(out["warnings"], json!(1));
    }

    #[test]
    fn index_counts_from_zero() {
        let check = node(json!({
            "values": { "facts": ["prep", "facts"] },
            "rules": [{ "id": "late", "for_each": "facts.days", "when": "item > 5", "message": "day {{ index }}: {{ item }}" }]
        }))
        .unwrap();
        let out = output(&check, json!({ "days": [1, 9, 2, 7] }));
        assert_eq!(out["flags"][0]["message"], json!("day 1: 9"));
        assert_eq!(out["flags"][1]["message"], json!("day 3: 7"));
        assert_eq!(out["flags"][0]["severity"], json!("warning"));
    }

    #[test]
    fn for_each_of_a_value_that_is_not_a_list_is_an_error() {
        let check = node(json!({
            "values": { "facts": ["prep", "facts"] },
            "rules": [{ "id": "x", "for_each": "facts.orders", "when": "true", "message": "m" }]
        }))
        .unwrap();
        let message = run(&check, json!({ "orders": 4 })).unwrap_err().to_string();
        assert!(message.contains("rule `x`: `for_each` must give a list"), "{message}");
    }

    #[test]
    fn invalid_rules_are_refused_with_their_field() {
        let cases = [
            (json!({ "values": {}, "rules": [] }), "values"),
            (
                json!({ "values": { "item": ["a", "b"] }, "rules": [{ "id": "a", "when": "true", "message": "m" }] }),
                "values",
            ),
            (json!({ "values": { "f": ["a", "b"] }, "rules": [] }), "rules"),
            (
                json!({ "values": { "f": ["a", "b"] }, "rules": [{ "id": "a", "when": "f.x <", "message": "m" }] }),
                "rules[0].when",
            ),
            (
                json!({ "values": { "f": ["a", "b"] }, "rules": [{ "id": "a", "when": "true", "message": "{{ f" }] }),
                "rules[0].message",
            ),
            (
                json!({ "values": { "f": ["a", "b"] }, "rules": [
                    { "id": "a", "when": "true", "message": "m" }, { "id": "a", "when": "true", "message": "m" }
                ] }),
                "rules[1].id",
            ),
            (
                json!({ "values": { "f": ["a", "b"] }, "rules": [{ "id": " ", "when": "true", "message": "m" }] }),
                "rules[0].id",
            ),
        ];
        for (config, field) in cases {
            let error = node(config.clone()).unwrap_err();
            assert_eq!(error.field.as_deref(), Some(field), "{config}: {}", error.message);
        }
    }

    #[test]
    fn an_item_without_the_value_raises_nothing_when_guarded() {
        let check = node(sales_rules("output")).unwrap();
        let out = output(
            &check,
            json!({ "orders": 500, "stores": [{ "name": "West" }, { "name": "East", "revenue": "-5" }] }),
        );
        assert_eq!(out["flags"], json!([]));
    }

    #[test]
    fn an_error_after_the_flag_limit_still_fails_the_check() {
        let check = node(json!({
            "values": { "facts": ["prep", "facts"] },
            "on_fail": "error",
            "rules": [
                { "id": "each", "for_each": "facts.items", "when": "true", "message": "{{ item }}" },
                { "id": "late_error", "when": "true", "severity": "error", "message": "found after the limit" }
            ]
        }))
        .unwrap();
        let items: Vec<u32> = (0..300).collect();
        let message = run(&check, json!({ "items": items })).unwrap_err().to_string();
        assert!(message.contains("rule check failed with 1 error(s)"), "{message}");
        assert!(message.contains("and 1 more"), "the kept flags do not name it: {message}");
    }

    #[test]
    fn flags_stop_at_the_limit() {
        let check = node(json!({
            "values": { "facts": ["prep", "facts"] },
            "rules": [{ "id": "each", "for_each": "facts.items", "when": "true", "message": "{{ item }}" }]
        }))
        .unwrap();
        let items: Vec<u32> = (0..500).collect();
        let out = output(&check, json!({ "items": items }));
        assert_eq!(out["flags"].as_array().map(Vec::len), Some(MAX_FLAGS));
        assert_eq!(out["warnings"], json!(500), "the counts see every flag");
    }
}