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
//! `template-transform`: renders a Jinja2-compatible template.
//!
//! Rendering is sandboxed: there is no filesystem loader, execution is bounded
//! by a fuel limit and a recursion limit, the output size is capped and
//! auto-escaping is off. Secret values are masked in the template context.

use std::sync::Arc;

use futures::future::BoxFuture;
use minijinja::value::{Enumerator, Object};
use minijinja::{AutoEscape, 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;

/// Instruction budget per render.
pub const FUEL: u64 = 100_000;
/// Maximum rendered output size in bytes.
pub const MAX_OUTPUT_BYTES: usize = 1024 * 1024;
const RECURSION_LIMIT: usize = 64;

/// `template-transform` configuration.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct TemplateTransformConfig {
    #[serde(default)]
    pub template: String,
    #[serde(default)]
    pub variables: Vec<TemplateVariable>,
}

/// A template variable bound to a selector.
#[derive(Clone, Debug, Deserialize)]
pub struct TemplateVariable {
    pub variable: String,
    pub value_selector: Selector,
}

/// The `template-transform` node.
#[derive(Debug)]
pub struct TemplateTransformNode {
    config: TemplateTransformConfig,
    /// `config.variables`, shared with every render's [`TemplateVars`].
    variables: Arc<[TemplateVariable]>,
    env: Environment<'static>,
}

/// The template context of one render: each variable is resolved from the
/// node's pool snapshot when the template reads it.
///
/// This replaces building a map of every variable and converting it into a
/// minijinja map on each render, which cost several allocations per node
/// execution; now a render allocates only this object.
#[derive(Debug)]
struct TemplateVars {
    variables: Arc<[TemplateVariable]>,
    pool: VariablePool,
}

impl Object for TemplateVars {
    fn get_value(self: &Arc<Self>, key: &minijinja::Value) -> Option<minijinja::Value> {
        self.get_value_by_str(key.as_str()?)
    }

    fn get_value_by_str(self: &Arc<Self>, key: &str) -> Option<minijinja::Value> {
        // A repeated name binds its last declaration, as a map built in order would.
        let variable = self.variables.iter().rev().find(|v| v.variable == key)?;
        let value = self.pool.get(&variable.value_selector).unwrap_or(Value::Null);
        Some(to_template_value(value))
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        let mut names: Vec<&str> = Vec::with_capacity(self.variables.len());
        for v in self.variables.iter() {
            if !names.contains(&v.variable.as_str()) {
                names.push(&v.variable);
            }
        }
        Enumerator::Values(names.into_iter().map(minijinja::Value::from).collect())
    }
}

/// Convert a pool value for the template. Scalars and strings convert
/// directly (a string shares its `Arc<str>` instead of being copied); everything
/// else goes through `Serialize`, which masks secrets.
pub(crate) fn to_template_value(value: Value) -> minijinja::Value {
    match value {
        Value::Null => minijinja::Value::from(()),
        Value::Bool(b) => minijinja::Value::from(b),
        Value::Int(i) => minijinja::Value::from(i),
        Value::Float(f) => minijinja::Value::from(f),
        Value::String(s) => minijinja::Value::from(s),
        other => minijinja::Value::from(minijinja::value::Serde(&other)),
    }
}

pub(crate) fn sandboxed_env() -> Environment<'static> {
    let mut env = Environment::new();
    env.set_fuel(Some(FUEL));
    env.set_recursion_limit(RECURSION_LIMIT);
    env.set_auto_escape_callback(|_| AutoEscape::None);
    env.set_undefined_behavior(UndefinedBehavior::Lenient);
    env.add_filter("grounded", |text: String, sources: minijinja::Value| {
        crate::grounding::grounded_numbers(&text, &source_texts(&sources))
    });
    #[cfg(feature = "compare-numbers")]
    env.add_filter("compare_numbers", compare_numbers_filter);
    #[cfg(feature = "number-format")]
    super::number_format::register(&mut env);
    env
}

/// The `compare_numbers` filter: `{{ text | compare_numbers(reference) }}` is
/// `{both, text_only, reference_only, both_count, text_only_count, reference_only_count}`.
/// The reference is a text or a list of texts; `tolerance` (`rounding` or `exact`) and
/// `ratios_as_percent` are the options of `grounding.numbers`.
#[cfg(feature = "compare-numbers")]
fn compare_numbers_filter(
    text: minijinja::Value,
    reference: minijinja::Value,
    kwargs: minijinja::value::Kwargs,
) -> Result<minijinja::Value, minijinja::Error> {
    use crate::grounding::figures::{NumberRules, Tolerance};
    let tolerance = match kwargs.get::<Option<String>>("tolerance")?.as_deref() {
        None | Some("rounding") => Tolerance::Rounding,
        Some("exact") => Tolerance::Exact,
        Some(other) => {
            return Err(minijinja::Error::new(
                minijinja::ErrorKind::InvalidOperation,
                format!("`tolerance` is `rounding` or `exact`, not `{other}`"),
            ));
        }
    };
    let ratios_as_percent = kwargs.get::<Option<bool>>("ratios_as_percent")?.unwrap_or(false);
    kwargs.assert_all_used()?;
    let text = match text.kind() {
        minijinja::value::ValueKind::Undefined | minijinja::value::ValueKind::None => String::new(),
        _ => text.to_string(),
    };
    let reference = source_texts(&reference).join("\n");
    let found = crate::grounding::compare_numbers(&text, &reference, NumberRules { tolerance, ratios_as_percent });
    let (both_count, text_only_count, reference_only_count) =
        (found.both_count(), found.text_only_count(), found.reference_only_count());
    let fields: std::collections::BTreeMap<&str, minijinja::Value> = [
        ("both", minijinja::Value::from(found.both)),
        ("text_only", minijinja::Value::from(found.text_only)),
        ("reference_only", minijinja::Value::from(found.reference_only)),
        ("both_count", minijinja::Value::from(both_count)),
        ("text_only_count", minijinja::Value::from(text_only_count)),
        ("reference_only_count", minijinja::Value::from(reference_only_count)),
    ]
    .into_iter()
    .collect();
    Ok(minijinja::Value::from(fields))
}

/// The texts of the `grounded` filter's sources: a text or a list of texts.
fn source_texts(sources: &minijinja::Value) -> Vec<String> {
    match sources.kind() {
        minijinja::value::ValueKind::Seq => {
            sources.try_iter().map(|items| items.map(|item| item.to_string()).collect()).unwrap_or_default()
        }
        minijinja::value::ValueKind::Undefined | minijinja::value::ValueKind::None => Vec::new(),
        _ => vec![sources.to_string()],
    }
}

/// Render target that refuses to grow past [`MAX_OUTPUT_BYTES`].
///
/// Fuel counts instructions, not bytes: one instruction can emit a 100 MB
/// string, so a short loop could render gigabytes before a size check on the
/// finished string ran. Failing the write stops the render at the limit.
#[derive(Default)]
struct CappedOutput {
    bytes: Vec<u8>,
    /// Set when a write was refused; minijinja reports only a generic I/O error.
    overflowed: bool,
}

impl std::io::Write for CappedOutput {
    fn write(&mut self, chunk: &[u8]) -> std::io::Result<usize> {
        if self.bytes.len().saturating_add(chunk.len()) > MAX_OUTPUT_BYTES {
            self.overflowed = true;
            return Err(std::io::ErrorKind::FileTooLarge.into());
        }
        self.bytes.extend_from_slice(chunk);
        Ok(chunk.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// Name of the node's only template inside its private environment.
const TEMPLATE_NAME: &str = "template";

impl TemplateTransformNode {
    /// Compile the template once; every run renders the compiled form instead of
    /// re-parsing the source (about 6x cheaper per render).
    pub fn new(doc: &NodeDoc, config: TemplateTransformConfig) -> Result<Self, ConfigError> {
        let mut env = sandboxed_env();
        if let Err(e) = env.add_template_owned(TEMPLATE_NAME, config.template.clone()) {
            return Err(ConfigError::new(doc, format!("invalid template: {e}")));
        }
        let variables = config.variables.clone().into();
        Ok(Self { config, variables, env })
    }
}

impl Node for TemplateTransformNode {
    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(async move {
            let context =
                minijinja::Value::from_object(TemplateVars { variables: Arc::clone(&self.variables), pool: ctx.pool });
            let mut output = CappedOutput::default();
            self.env
                .get_template(TEMPLATE_NAME)
                .and_then(|template| template.render_captured_to(context, &mut output))
                .map_err(|e| {
                    let message = if output.overflowed {
                        format!("output exceeds the limit of {MAX_OUTPUT_BYTES} bytes")
                    } else {
                        e.to_string()
                    };
                    NodeError::fatal("template", message)
                })?;
            let output = String::from_utf8(output.bytes)
                .map_err(|_| NodeError::fatal("template", "rendered output is not valid UTF-8"))?;
            Ok(NodeOutput::new().with("output", output).into())
        })
    }

    fn inputs(&self) -> Vec<Selector> {
        self.config.variables.iter().map(|v| v.value_selector.clone()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::node::NodeOutcome;
    use crate::pool::VariablePool;
    use serde_json::json;
    use std::sync::Arc;

    fn node(cfg: serde_json::Value) -> Result<TemplateTransformNode, ConfigError> {
        let doc = NodeDoc::new("t", "template-transform", cfg);
        TemplateTransformNode::new(&doc, doc.parse_config().unwrap())
    }

    async fn render(cfg: serde_json::Value, pool: VariablePool) -> NodeResult {
        node(cfg).unwrap().run(NodeContext::for_test("t", pool)).await
    }

    #[tokio::test]
    async fn output_limit_stops_the_render_early() {
        // 100 GB if rendered to the end; only the writer's cap stops it.
        let started = std::time::Instant::now();
        let r = render(
            json!({"template": "{% for i in range(100000) %}{{ 'x' * 1000000 }}{% endfor %}"}),
            VariablePool::new(),
        )
        .await;
        let error = r.unwrap_err();
        assert!(error.message.contains("limit"), "{error:?}");
        assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed());
        // Right at the limit is fine.
        let exact = format!("{{{{ 'x' * {MAX_OUTPUT_BYTES} }}}}");
        let NodeOutcome::Completed(o) = render(json!({"template": exact}), VariablePool::new()).await.unwrap() else {
            panic!()
        };
        assert_eq!(o.outputs.get("output").and_then(Value::as_str).map(str::len), Some(MAX_OUTPUT_BYTES));
    }

    #[tokio::test]
    async fn renders_jinja() {
        let mut pool = VariablePool::new();
        pool.insert("n", "items", Value::from_json(json!(["a", "b"])));
        pool.insert("n", "key", Value::Secret(Arc::from("sk-live")));
        let r = render(
            json!({
                "template": "{% for i in items %}{{ i | upper }}{% endfor %} {{ key }} {{ missing }}|",
                "variables": [
                    {"variable": "items", "value_selector": ["n", "items"]},
                    {"variable": "key", "value_selector": ["n", "key"]}
                ]
            }),
            pool,
        )
        .await
        .unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("AB ****** |")));
    }

    #[tokio::test]
    async fn a_reply_is_checked_against_its_sources() {
        let mut pool = VariablePool::new();
        pool.insert("w", "text", Value::from("Our express laundry costs $15k per kg."));
        pool.insert("start", "message", Value::from("How much is express?"));
        let template =
            "{% set checked = reply | grounded([facts, message]) %}{{ checked if checked else 'I do not know.' }}";
        let config = |facts: &str| {
            json!({
                "template": template.replace("facts", &format!("'{facts}'")),
                "variables": [
                    {"variable": "reply", "value_selector": ["w", "text"]},
                    {"variable": "message", "value_selector": ["start", "message"]}
                ]
            })
        };
        let r = render(config("express 15k per kg"), pool.clone()).await.unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("Our express laundry costs 15k per kg.")));
        let r = render(config("express 12k per kg"), pool).await.unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("I do not know.")));
    }

    #[cfg(feature = "compare-numbers")]
    #[tokio::test]
    async fn compare_numbers_reports_the_numbers_of_a_section() {
        let mut pool = VariablePool::new();
        pool.insert("w", "text", Value::from("North sold 1.2 million (up 13.2%) on 1,520 orders, South 950k."));
        pool.insert("ref", "text", Value::from("North: revenue 1,234,567, growth 13.19%, orders 1520. East: 410,000."));
        let variables = json!([
            {"variable": "section", "value_selector": ["w", "text"]},
            {"variable": "reference", "value_selector": ["ref", "text"]}
        ]);
        let template = "{% set c = section | compare_numbers(reference) %}\
            {{ c.both | join(', ') }} | {{ c.text_only | join(', ') }} | {{ c.reference_only | join(', ') }} | \
            {{ c.both_count }}/{{ c.text_only_count }}/{{ c.reference_only_count }}";
        let r = render(json!({"template": template, "variables": variables}), pool.clone()).await.unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("1.2 million, 13.2%, 1,520 | 950k | 410,000 | 3/1/1")));
        // A list of reference texts, the options of `grounding.numbers`, and no text at all.
        let template = "{{ (section | compare_numbers([reference, 'South 950,000'], tolerance='exact')).both | join(', ') }} \
            {{ (none | compare_numbers(reference)).reference_only_count }} \
            {{ ('13%' | compare_numbers('0.13', ratios_as_percent=true)).both_count }}";
        let r = render(json!({"template": template, "variables": variables}), pool).await.unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("1,520, 950k 4 1")));
        let bad =
            render(json!({"template": "{{ 'a' | compare_numbers('b', tolerance='loose') }}"}), VariablePool::new())
                .await;
        assert!(bad.is_err());
    }

    #[cfg(feature = "number-format")]
    #[tokio::test]
    async fn numbers_are_formatted_for_a_report() {
        let mut pool = VariablePool::new();
        pool.insert("n", "facts", Value::from_json(json!({"revenue": 1234567.891, "share": 0.1234})));
        let r = render(
            json!({
                "template": "{{ facts.revenue | number }} {{ facts.revenue | number(2) }} {{ facts.share | percent }} [{{ facts.missing | number }}]",
                "variables": [{"variable": "facts", "value_selector": ["n", "facts"]}]
            }),
            pool,
        )
        .await
        .unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("1,234,568 1,234,567.89 12.34% []")));
    }

    #[tokio::test]
    async fn variables_resolve_like_a_declared_map() {
        let mut pool = VariablePool::new();
        pool.insert("n", "a", Value::from("first"));
        pool.insert("n", "b", Value::from("second"));
        pool.insert("n", "obj", Value::from_json(json!({"x": {"y": 7}})));
        let r = render(
            json!({
                // A repeated name binds its last declaration; a declared variable
                // whose selector is missing is defined (none), an undeclared one is not.
                "template": "{{ v }} {{ obj.x.y }} {{ gone is defined }} {{ gone is none }} {{ other is defined }}",
                "variables": [
                    {"variable": "v", "value_selector": ["n", "a"]},
                    {"variable": "obj", "value_selector": ["n", "obj"]},
                    {"variable": "gone", "value_selector": ["n", "missing"]},
                    {"variable": "v", "value_selector": ["n", "b"]}
                ]
            }),
            pool,
        )
        .await
        .unwrap();
        let NodeOutcome::Completed(o) = r else { panic!() };
        assert_eq!(o.outputs.get("output"), Some(&Value::from("second 7 True True False")));
    }

    #[test]
    fn context_enumerates_distinct_names_in_declaration_order() {
        let variable =
            |name: &str| TemplateVariable { variable: name.to_owned(), value_selector: Selector::of("n", name) };
        let vars = Arc::new(TemplateVars {
            variables: vec![variable("b"), variable("a"), variable("b")].into(),
            pool: VariablePool::new(),
        });
        let Enumerator::Values(names) = vars.enumerate() else { panic!("expected values") };
        assert_eq!(names, [minijinja::Value::from("b"), minijinja::Value::from("a")]);
    }

    #[test]
    fn syntax_error_is_config_error() {
        assert!(node(json!({"template": "{% for %}"})).is_err());
    }

    #[tokio::test]
    async fn runaway_template_is_stopped() {
        let r = render(
            json!({"template": "{% for i in range(100000) %}{% for j in range(100000) %}x{% endfor %}{% endfor %}"}),
            VariablePool::new(),
        )
        .await;
        assert!(r.is_err());
    }

    #[tokio::test]
    async fn no_filesystem_access() {
        let r = render(json!({"template": "{% include '/etc/passwd' %}"}), VariablePool::new()).await;
        assert!(r.is_err());
    }
}