graphrt-core 0.9.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
//! `text-check`: checks the written text of values against rules (see
//! [`crate::text_check`]): phrases, patterns and contact details that must not
//! appear, texts that must, and the number of paragraphs of a field. Issues of
//! another check (the `unsupported` items of an `llm` node's `grounding`) may be
//! counted in, so one node says whether a draft needs another pass.
//!
//! Outputs: `passed`, `issues` (`[{field, rule, message, found?}]`),
//! `issues_total`, `notes` (one line per issue) and `fixed` (the value with the
//! `replace` of the forbid rules applied). With `on_fail: error` an issue fails
//! the node instead (kind `text_check`).

use futures::future::BoxFuture;
use serde::Deserialize;

use crate::dsl::NodeDoc;
use crate::node::{ConfigError, Node, NodeContext, NodeError, NodeOutput, NodeResult};
use crate::pool::{Selector, VariablePool};
use crate::text_check::{self, Issue, RuleSources, RulesConfig, Texts};
use crate::value::Value;

/// Error kind of a failed check with `on_fail: error`.
pub const FAILED: &str = "text_check";
/// Issues named in the error message of a failed check.
const ISSUES_IN_ERROR: usize = 10;

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

/// `text-check` configuration as written.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TextCheckConfig {
    /// The value to check, or a list of values.
    pub text: serde_json::Value,
    #[serde(default)]
    pub forbid: Option<serde_json::Value>,
    #[serde(default)]
    pub require: Option<serde_json::Value>,
    #[serde(default)]
    pub paragraphs: Option<serde_json::Value>,
    #[serde(default)]
    pub ignore: Vec<String>,
    /// Issues found by other checks.
    #[serde(default)]
    pub issues: Vec<Selector>,
    #[serde(default)]
    pub on_fail: OnFail,
}

/// The `text-check` node.
#[derive(Debug)]
pub struct TextCheckNode {
    texts: Vec<Selector>,
    /// Field paths are prefixed with the selector when several values are checked.
    prefixed: bool,
    rules: RuleSources,
    issues: Vec<Selector>,
    on_fail: OnFail,
}

impl TextCheckNode {
    pub fn new(doc: &NodeDoc, config: TextCheckConfig) -> Result<Self, ConfigError> {
        let texts = texts(&config.text).map_err(|message| ConfigError::new(doc, message).at_field("text"))?;
        let rules = RuleSources::parse(&RulesConfig {
            forbid: config.forbid,
            require: config.require,
            paragraphs: config.paragraphs,
            ignore: config.ignore,
        })
        .map_err(|(field, error)| ConfigError::new(doc, error.0).at_field(field))?;
        if rules.is_empty() && config.issues.is_empty() {
            return Err(ConfigError::new(doc, "give at least one of `forbid`, `require`, `paragraphs` and `issues`"));
        }
        Ok(Self { prefixed: texts.len() > 1, texts, rules, issues: config.issues, on_fail: config.on_fail })
    }

    fn prefix(&self, selector: &Selector) -> String {
        if self.prefixed { selector.to_string() } else { String::new() }
    }

    fn compute(&self, pool: &VariablePool) -> Result<NodeOutput, NodeError> {
        let rules = self.rules.resolve(pool)?;
        let mut texts = Texts::default();
        let mut fixed = Vec::with_capacity(self.texts.len());
        for selector in &self.texts {
            let value = pool.get_or_null(selector);
            let prefix = self.prefix(selector);
            texts.add(&value, &prefix);
            fixed.push(text_check::fix(&value, &prefix, &rules.forbid));
        }
        let mut issues: Vec<Issue> = Vec::new();
        for selector in &self.issues {
            let found = text_check::issues_from(&pool.get_or_null(selector))
                .map_err(|e| NodeError::invalid_input(format!("`{selector}`: {e}")))?;
            issues.extend(found);
        }
        issues.extend(text_check::check(&texts, &rules));
        issues.truncate(text_check::MAX_ISSUES);

        if !issues.is_empty() && self.on_fail == OnFail::Error {
            let named: Vec<String> = issues.iter().take(ISSUES_IN_ERROR).map(Issue::to_string).collect();
            let more = issues.len().saturating_sub(ISSUES_IN_ERROR);
            let tail = if more > 0 { format!("; and {more} more") } else { String::new() };
            return Err(NodeError::new(
                FAILED,
                format!("text check failed with {} issue(s): {}{tail}", issues.len(), named.join("; ")),
            ));
        }
        let fixed = if self.prefixed { Value::array(fixed) } else { fixed.into_iter().next().unwrap_or(Value::Null) };
        Ok(NodeOutput::new()
            .with("passed", issues.is_empty())
            .with("issues_total", Value::Int(i64::try_from(issues.len()).unwrap_or(i64::MAX)))
            .with("notes", text_check::notes(&issues))
            .with("issues", Value::array(issues.iter().map(Issue::to_value)))
            .with("fixed", fixed))
    }
}

fn texts(value: &serde_json::Value) -> Result<Vec<Selector>, String> {
    if let Ok(selector) = serde_json::from_value::<Selector>(value.clone()) {
        return Ok(vec![selector]);
    }
    let selectors = serde_json::from_value::<Vec<Selector>>(value.clone())
        .map_err(|_| "`text` must be a selector or a list of selectors".to_owned())?;
    if selectors.is_empty() {
        return Err("`text` must name at least one value".into());
    }
    Ok(selectors)
}

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

    fn inputs(&self) -> Vec<Selector> {
        let mut out = self.texts.clone();
        out.extend(self.rules.selectors());
        out.extend(self.issues.iter().cloned());
        out
    }
}

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

    use super::*;
    use crate::node::NodeOutcome;

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

    fn pool(values: &[(&str, &str, serde_json::Value)]) -> VariablePool {
        let mut pool = VariablePool::new();
        for (node, name, value) in values {
            pool.insert(node, name, Value::from_json(value.clone()));
        }
        pool
    }

    async fn run(node: &TextCheckNode, pool: VariablePool) -> Result<NodeOutput, NodeError> {
        match node.run(NodeContext::for_test("check", pool)).await? {
            NodeOutcome::Completed(out) => Ok(out),
            other => panic!("unexpected outcome {other:?}"),
        }
    }

    #[tokio::test]
    async fn reports_issues_of_inline_and_computed_rules_and_other_checks() {
        let node = node(json!({
            "text": ["write", "structured_output"],
            "forbid": [{"name": "semicolon", "text": ";", "message": "use a full stop", "replace": "."}],
            "require": ["prep", "required"],
            "paragraphs": {"notes": 2},
            "issues": [["write", "unsupported"]]
        }))
        .unwrap();
        assert_eq!(
            node.inputs().iter().map(ToString::to_string).collect::<Vec<_>>(),
            vec!["write.structured_output", "prep.required", "write.unsupported"]
        );
        let pool = pool(&[
            ("write", "structured_output", json!({"summary": "Up 4%; steady.", "notes": ["One."]})),
            ("write", "unsupported", json!([{"field": "summary", "number": "4%", "reason": "value"}])),
            ("prep", "required", json!([{"field": "summary", "text": "May", "message": "name the month"}])),
        ]);
        let out = run(&node, pool).await.unwrap();
        assert_eq!(out.outputs.get("passed"), Some(&Value::Bool(false)));
        assert_eq!(out.outputs.get("issues_total"), Some(&Value::Int(4)));
        assert_eq!(
            out.outputs.get("notes").map(Value::to_text).unwrap(),
            "- summary: 4% is not in the facts\n- summary: use a full stop (\";\")\n\
             - summary: name the month\n- notes: write exactly 2 paragraphs, not 1"
        );
        assert_eq!(
            out.outputs.get("fixed").map(Value::to_json),
            Some(json!({"summary": "Up 4%. steady.", "notes": ["One."]}))
        );
    }

    #[tokio::test]
    async fn passes_a_clean_text_and_skips_missing_computed_rules() {
        let node = node(json!({"text": "write.text", "forbid": "prep.banned", "require": [["prep", "required"]]}));
        // `require` given as a list of selectors is not a list of rules.
        assert!(node.is_err());
        let node = node_ok(json!({"text": "write.text", "forbid": "prep.banned"}));
        let out = run(&node, pool(&[("write", "text", json!("All good."))])).await.unwrap();
        assert_eq!(out.outputs.get("passed"), Some(&Value::Bool(true)));
        assert_eq!(out.outputs.get("notes").map(Value::to_text).unwrap(), "");
        assert_eq!(out.outputs.get("fixed").map(Value::to_text).unwrap(), "All good.");
    }

    fn node_ok(config: serde_json::Value) -> TextCheckNode {
        node(config).unwrap()
    }

    #[tokio::test]
    async fn guards_several_values_and_fails_without_echoing_contacts() {
        let node = node_ok(json!({
            "text": [["extract", "facts"], ["extract", "examples"]],
            "forbid": [{"detect": "email"}, {"detect": "phone"}],
            "on_fail": "error"
        }));
        let clean =
            pool(&[("extract", "facts", json!({"rows": [{"sales": 1200}]})), ("extract", "examples", json!("x"))]);
        assert_eq!(run(&node, clean).await.unwrap().outputs.get("passed"), Some(&Value::Bool(true)));
        let leaking = pool(&[
            ("extract", "facts", json!({"rows": [{"owner": "ana@example.com"}]})),
            ("extract", "examples", json!("call +44 20 7946 0958")),
        ]);
        let error = run(&node, leaking).await.unwrap_err();
        assert_eq!(error.kind, FAILED);
        assert!(error.message.contains("extract.facts.rows[0].owner: contains an email address"), "{}", error.message);
        assert!(error.message.contains("extract.examples: contains a phone number"), "{}", error.message);
        assert!(!error.message.contains("ana@") && !error.message.contains("7946"), "{}", error.message);
    }

    #[tokio::test]
    async fn computed_rules_of_the_wrong_shape_fail_the_node() {
        let node = node_ok(json!({"text": "write.text", "paragraphs": "prep.shape"}));
        let error =
            run(&node, pool(&[("write", "text", json!("a")), ("prep", "shape", json!(["x"]))])).await.unwrap_err();
        assert!(error.message.contains("`prep.shape`: paragraphs must map fields to counts"), "{}", error.message);
        let node = node_ok(json!({"text": "write.text", "forbid": "prep.banned"}));
        let bad_pattern = pool(&[("write", "text", json!("a")), ("prep", "banned", json!([{"pattern": "("}]))]);
        assert!(run(&node, bad_pattern).await.is_err());
    }

    #[test]
    fn wrong_configs_are_refused() {
        for (config, says) in [
            (json!({"text": "write.text"}), "at least one of"),
            (json!({"text": 3, "forbid": []}), "`text` must be a selector"),
            (json!({"text": [], "forbid": []}), "`text` must"),
            (json!({"text": "w.t", "forbid": [{"pattern": "a", "text": "b"}]}), "exactly one of"),
            (json!({"text": "w.t", "require": [{"field": "a"}]}), "require must be a list"),
            (json!({"text": "w.t", "require": [["a", "b"]]}), "require must be a list of rules"),
            (json!({"text": "w.t", "paragraphs": {"a": -1}}), "paragraphs must map"),
            (json!({"text": "w.t", "forbid": [], "on_fail": "fallback"}), "unknown variant"),
            (json!({"text": "w.t", "forbid": [], "extra": 1}), "unknown field"),
        ] {
            let error = node(config.clone()).err().unwrap_or_else(|| panic!("accepted {config}"));
            assert!(error.to_string().contains(says), "{config}: {error}");
        }
    }
}