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
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
//! The numbers check of a report: every number a text states must be one of the facts, as
//! rounded for the text.
//!
//! Unlike [`super::check`], which reads a chat reply sentence by sentence, this check looks at
//! numbers only and leaves the words to the writer: a report may say anything about the figures,
//! as long as each figure is one of the facts. It reports the numbers that are not, and changes
//! nothing.
//!
//! - **Rounding**: a number matches a fact that rounds to it at the precision it is written with.
//!   `13.2%` matches `13.19`, `13%` matches `12.6`, `1.2 million` matches `1,234,567`, but
//!   `13.21` does not match `13.2` (a figure more precise than the facts is made up).
//!   [`Tolerance::Exact`] asks for the value itself.
//! - **Shares**: with `ratios_as_percent`, `13.19%` matches the ratio `0.1319` and `0.13`
//!   matches `13%`.
//! - **Notation**: `1.234.567` and `1,234,567` are the same number, and so are `13,19` and
//!   `13.19`. A number that can be read both ways (`1.234`) matches either reading. Multipliers
//!   (`15k`, `15 rb`, `2 jt`, `1.5 million`, `3 miliar`) are applied. Signs are ignored:
//!   "down 5%" states the figure `-5%` as `5%`.
//! - **Words**: `0`, `1` and `2` written alone are words ("2 stores"), not figures. A digit glued
//!   to letters before it (`Q3`, `H1`, `v2`) is a name, not a figure.
//!
//! Facts are texts, read the same way, or JSON values, whose numbers are taken as they are (a
//! JSON `1.234` is one and a quarter, never a thousand).

/// How close a number must be to a fact.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Tolerance {
    /// The fact rounds to the number at the precision it is written with.
    #[default]
    Rounding,
    /// The number is the fact.
    Exact,
}

/// How numbers are compared.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NumberRules {
    pub tolerance: Tolerance,
    /// A percentage matches the ratio it is (`13.19%` and `0.1319`), both ways.
    pub ratios_as_percent: bool,
}

/// A number the facts do not hold, with the sentence it stands in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnsupportedNumber {
    /// The number as the text writes it (`13.2%`, `1,2 juta`).
    pub number: String,
    pub sentence: String,
}

/// The numbers some facts hold.
#[derive(Clone, Debug, Default)]
pub struct Figures {
    /// Each value, and whether it was written as a percentage.
    values: Vec<(f64, bool)>,
}

/// Multipliers a number may be written with, in the word right after it.
const MULTIPLIERS: &[(&str, f64)] = &[
    ("k", 1e3),
    ("rb", 1e3),
    ("ribu", 1e3),
    ("thousand", 1e3),
    ("jt", 1e6),
    ("juta", 1e6),
    ("mn", 1e6),
    ("million", 1e6),
    ("millions", 1e6),
    ("miliar", 1e9),
    ("milyar", 1e9),
    ("billion", 1e9),
    ("bn", 1e9),
    ("triliun", 1e12),
    ("trillion", 1e12),
];

/// Currency codes and signs written right before a number (`Rp15.000`, `US$5`, `IDR 2jt`):
/// the letters do not make the number part of a name.
const CURRENCY_PREFIXES: &[&str] = &[
    "rp", "idr", "us", "usd", "eur", "sgd", "s", "myr", "rm", "gbp", "jpy", "aud", "a", "inr", "rs", "php", "thb",
    "vnd", "cny", "rmb", "hkd", "hk", "cad", "c", "nzd", "nz", "chf", "brl", "r", "zar", "krw", "kes", "ksh", "ngn",
];

/// One number in a text: the readings it may have.
#[derive(Clone, Debug)]
pub(super) struct Written {
    pub(super) text: String,
    readings: Vec<Reading>,
    percent: bool,
    /// Written with digits alone: no separator, multiplier or percent sign (`7`, `2024`).
    pub(super) plain: bool,
    /// Byte offset in the text, for its sentence.
    pub(super) at: usize,
    /// Byte offset right after the number as written (its multiplier and `%` included).
    pub(super) end: usize,
}

impl Written {
    /// The value of a plain number (`Self::plain`), `None` for any other.
    pub(super) fn plain_value(&self) -> Option<f64> {
        match self.readings.as_slice() {
            [reading] if self.plain => Some(reading.value),
            _ => None,
        }
    }
}

/// One reading of a number: its value and the half unit of its last written digit.
#[derive(Clone, Copy, Debug)]
struct Reading {
    value: f64,
    half_unit: f64,
}

impl Figures {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds the numbers a text states.
    pub fn add_text(&mut self, text: &str) {
        for number in scan(text) {
            for reading in &number.readings {
                self.values.push((reading.value, number.percent));
            }
        }
    }

    /// Adds the numbers of a JSON value: its numbers as they are, its strings as texts.
    pub fn add_json(&mut self, value: &serde_json::Value) {
        match value {
            serde_json::Value::Number(number) => {
                if let Some(value) = number.as_f64() {
                    self.values.push((value.abs(), false));
                }
            }
            serde_json::Value::String(text) => self.add_text(text),
            serde_json::Value::Array(items) => items.iter().for_each(|item| self.add_json(item)),
            serde_json::Value::Object(fields) => fields.values().for_each(|item| self.add_json(item)),
            serde_json::Value::Null | serde_json::Value::Bool(_) => {}
        }
    }

    /// Whether the facts hold no number.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// The numbers of `text` the facts do not hold, in order.
    pub fn unsupported(&self, text: &str, rules: NumberRules) -> Vec<UnsupportedNumber> {
        scan(text)
            .into_iter()
            .filter(|number| !self.holds(number, rules))
            .map(|number| UnsupportedNumber { sentence: sentence_at(text, number.at), number: number.text })
            .collect()
    }

    pub(super) fn holds(&self, number: &Written, rules: NumberRules) -> bool {
        number.readings.iter().any(|reading| {
            self.values.iter().any(|(fact, fact_percent)| {
                let mut candidates = vec![(*fact, 1.0)];
                if rules.ratios_as_percent {
                    // A ratio fact read as a percentage, a percentage fact as a ratio.
                    if number.percent && !fact_percent {
                        candidates.push((fact * 100.0, 1.0));
                    }
                    if !number.percent && *fact_percent {
                        candidates.push((fact / 100.0, 1.0));
                    }
                }
                candidates.iter().any(|(fact, _)| close(*fact, *reading, rules.tolerance))
            })
        })
    }
}

fn close(fact: f64, reading: Reading, tolerance: Tolerance) -> bool {
    let room = match tolerance {
        Tolerance::Rounding => reading.half_unit,
        Tolerance::Exact => 0.0,
    };
    // A little more, for values that binary floating point cannot write exactly.
    let slack = 1e-9 * reading.value.abs().max(1.0);
    (fact.abs() - reading.value).abs() <= room + slack
}

/// The numbers of `text`.
pub(super) fn scan(text: &str) -> Vec<Written> {
    let chars: Vec<(usize, char)> = text.char_indices().collect();
    let mut found = Vec::new();
    let mut index = 0;
    while let Some(&(at, c)) = chars.get(index) {
        if !c.is_ascii_digit() {
            index += 1;
            continue;
        }
        // A digit glued to letters (`Q3`, `H1`, `v2`, `gpt5`) is part of a name, unless the
        // letters are a currency (`Rp15.000`).
        let in_a_name =
            letters_before(&chars, index).is_some_and(|letters| !CURRENCY_PREFIXES.contains(&letters.as_str()));
        let start = index;
        while let Some(&(_, c)) = chars.get(index) {
            let separator_between_digits = matches!(c, '.' | ',')
                && chars.get(index + 1).is_some_and(|(_, next)| next.is_ascii_digit())
                && index > start;
            if c.is_ascii_digit() || separator_between_digits {
                index += 1;
            } else {
                break;
            }
        }
        let token: String = chars.get(start..index).unwrap_or_default().iter().map(|(_, c)| c).collect();
        // Letters right after the digits (`15k`, `2jt`) or a word after a space (`15 ribu`).
        let (word, word_end) = word_after(&chars, index);
        if in_a_name {
            index = index.max(word_end);
            continue;
        }
        let multiplier =
            word.as_deref().and_then(|word| MULTIPLIERS.iter().find(|(name, _)| *name == word).map(|(_, by)| *by));
        let glued_letters = chars.get(index).is_some_and(|(_, c)| c.is_alphabetic());
        // Letters glued to the digits that are not a multiplier (`3rd`, `2x`): still a number.
        let percent = percent_after(&chars, index, word.as_deref());
        let mut written = token.clone();
        let mut end = index;
        if let Some(word) = word.as_deref().filter(|_| multiplier.is_some()) {
            written = if glued_letters { format!("{token}{word}") } else { format!("{token} {word}") };
            end = word_end;
        }
        if percent {
            written.push('%');
        }
        let readings: Vec<Reading> = readings_of(&token)
            .into_iter()
            .map(|reading| match multiplier {
                Some(by) => Reading { value: reading.value * by, half_unit: reading.half_unit * by },
                None => reading,
            })
            .collect();
        let plain = !percent && multiplier.is_none() && !token.contains(['.', ',']);
        let a_word = plain && readings.iter().all(|reading| reading.value <= 2.0);
        if !readings.is_empty() && !a_word {
            let end_at = match word.as_deref() {
                _ if !percent => end,
                Some("percent" | "persen" | "pct") => word_end,
                _ => percent_end(&chars, end),
            };
            let end_byte = chars.get(end_at).map_or(text.len(), |(byte, _)| *byte);
            found.push(Written { text: written, readings, percent, plain, at, end: end_byte });
        }
        index = end.max(index);
    }
    found
}

/// The letters glued before position `at` (`$` signs skipped), lowercase, if any.
fn letters_before(chars: &[(usize, char)], at: usize) -> Option<String> {
    let mut start = at;
    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| *c == '$') {
        start -= 1;
    }
    let end = start;
    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| c.is_alphabetic()) {
        start -= 1;
    }
    (start < end)
        .then(|| chars.get(start..end).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect())
}

/// The word right after a number (glued or after spaces), lowercase, and where it ends.
fn word_after(chars: &[(usize, char)], from: usize) -> (Option<String>, usize) {
    let mut index = from;
    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
        index += 1;
    }
    let start = index;
    while chars.get(index).is_some_and(|(_, c)| c.is_alphabetic()) {
        index += 1;
    }
    if index == start {
        return (None, from);
    }
    let word: String = chars.get(start..index).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect();
    (Some(word), index)
}

/// Where the `%` after the number ends (the index after it), or `from` when the percent is a
/// word that `from` already passed.
fn percent_end(chars: &[(usize, char)], from: usize) -> usize {
    let mut index = from;
    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
        index += 1;
    }
    if chars.get(index).is_some_and(|(_, c)| *c == '%') { index + 1 } else { from }
}

/// Whether a `%` or the word percent follows the number.
fn percent_after(chars: &[(usize, char)], from: usize, word: Option<&str>) -> bool {
    let mut index = from;
    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
        index += 1;
    }
    chars.get(index).is_some_and(|(_, c)| *c == '%') || matches!(word, Some("percent" | "persen" | "pct"))
}

/// The values `token` (digits with `.` and `,`) may mean.
fn readings_of(token: &str) -> Vec<Reading> {
    let separators: Vec<char> = token.chars().filter(|c| matches!(c, '.' | ',')).collect();
    let groups: Vec<&str> = token.split(['.', ',']).collect();
    let integer = |digits: &str| digits.parse::<f64>().ok();
    let decimal = |whole: &str, fraction: &str| {
        let value = format!("{whole}.{fraction}").parse::<f64>().ok()?;
        let places = i32::try_from(fraction.len()).ok()?;
        Some(Reading { value, half_unit: 0.5 * 10f64.powi(-places) })
    };
    let whole = |digits: String| integer(&digits).map(|value| Reading { value, half_unit: 0.5 });
    let mut readings = Vec::new();
    match separators.as_slice() {
        [] => readings.extend(whole(token.to_owned())),
        [_] => {
            let (Some(left), Some(right)) = (groups.first(), groups.get(1)) else { return readings };
            // `1.234` or `1,234`: a thousand and more, or one and a little.
            if right.len() == 3 {
                readings.extend(whole(format!("{left}{right}")));
            }
            readings.extend(decimal(left, right));
        }
        [first, rest @ ..] => {
            let last = rest.last().copied().unwrap_or(*first);
            let all_same = rest.iter().all(|separator| separator == first);
            let inner_are_thousands = groups.iter().skip(1).take(groups.len().saturating_sub(2)).all(|g| g.len() == 3);
            if all_same && groups.iter().skip(1).all(|group| group.len() == 3) {
                // `1.234.567`
                readings.extend(whole(groups.concat()));
            } else if !all_same
                && last != *first
                && inner_are_thousands
                && rest.iter().rev().skip(1).all(|s| s == first)
            {
                // `1.234,56` and `1,234.56`: the last separator is the decimal one.
                let (Some(fraction), Some(head)) = (groups.last(), groups.get(..groups.len() - 1)) else {
                    return readings;
                };
                readings.extend(decimal(&head.concat(), fraction));
            }
        }
    }
    readings
}

/// The sentence of `text` around byte offset `at`, trimmed.
pub(super) fn sentence_at(text: &str, at: usize) -> String {
    let (start, end) = sentence_span(text, at);
    text.get(start..end).unwrap_or_default().trim().to_owned()
}

/// The byte span of the sentence of `text` around byte offset `at`: from the end of the
/// sentence before it to the end of its own. A `.` between digits ends nothing.
pub(super) fn sentence_span(text: &str, at: usize) -> (usize, usize) {
    let ends_a_sentence = |index: usize, c: char| {
        matches!(c, '.' | '!' | '?' | '\n')
            && text
                .get(index + c.len_utf8()..)
                .is_none_or(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
    };
    let start = text
        .char_indices()
        .rfind(|(index, c)| *index < at && ends_a_sentence(*index, *c))
        .map_or(0, |(index, c)| index + c.len_utf8());
    let end = text
        .char_indices()
        .find(|(index, c)| *index >= at && ends_a_sentence(*index, *c))
        .map_or(text.len(), |(index, c)| index + c.len_utf8());
    (start, end)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
    use super::*;

    fn rules() -> NumberRules {
        NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true }
    }

    fn unsupported(facts: &[&str], text: &str, rules: NumberRules) -> Vec<String> {
        let mut known = Figures::new();
        facts.iter().for_each(|fact| known.add_text(fact));
        known.unsupported(text, rules).into_iter().map(|u| u.number).collect()
    }

    #[test]
    fn a_rounded_number_matches_its_fact() {
        let facts = ["revenue 1234567, growth 13.19, margin 12.6"];
        assert!(unsupported(&facts, "Revenue was 1.2 million, up 13.2, margin 13.", rules()).is_empty());
        assert!(unsupported(&facts, "Revenue reached 1,234,567 (13,19 growth).", rules()).is_empty());
        // More precise than the facts, or another figure.
        assert_eq!(unsupported(&facts, "Growth was 13.21 and 14.", rules()), ["13.21", "14"]);
        let exact = NumberRules { tolerance: Tolerance::Exact, ratios_as_percent: false };
        assert_eq!(unsupported(&facts, "Growth was 13.2, margin 12.6.", exact), ["13.2"]);
    }

    #[test]
    fn percentages_match_ratios() {
        let mut known = Figures::new();
        known.add_json(&serde_json::json!({"conversion": 0.1319, "share": "45%", "orders": 1520}));
        let rules = rules();
        let found = |text: &str| known.unsupported(text, rules).into_iter().map(|u| u.number).collect::<Vec<_>>();
        assert!(found("Conversion rose to 13.2% on 1,520 orders.").is_empty());
        assert!(found("Konversi 13,19 persen, pangsa 0,45.").is_empty());
        assert_eq!(found("Conversion was 14%."), ["14%"]);
        let plain = NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: false };
        assert_eq!(known.unsupported("Conversion was 13.2%.", plain).len(), 1);
        // A JSON fact is the number it is: 1.234 is not a thousand.
        let mut json = Figures::new();
        json.add_json(&serde_json::json!(1.234));
        assert_eq!(json.unsupported("It was 1234.", rules).len(), 1);
        assert!(json.unsupported("It was 1,23.", rules).is_empty());
    }

    #[test]
    fn multipliers_and_notations() {
        let facts = ["sales 15000, budget 2500000, total 3100000000"];
        assert!(
            unsupported(&facts, "Sales were 15k (Rp15 ribu), budget 2,5 jt, total 3,1 miliar.", rules()).is_empty()
        );
        assert!(unsupported(&facts, "Budget: 2.5 million. Sales: 15.000 (US$15k).", rules()).is_empty());
        // `m` is a metre as often as a million: a word, not a multiplier.
        assert_eq!(unsupported(&facts, "The shelf is 4 m.", rules()), ["4"]);
        assert_eq!(unsupported(&facts, "Sales were 16k.", rules()), ["16k"]);
    }

    #[test]
    fn words_names_and_signs_are_not_figures() {
        let facts = ["down 5.4"];
        assert!(unsupported(&facts, "In Q3 the 2 stores of H1 fell 5.4%.", NumberRules::default()).is_empty());
        assert!(unsupported(&facts, "It fell -5.4.", rules()).is_empty());
        assert_eq!(unsupported(&facts, "3 stores fell.", rules()), ["3"]);
    }

    #[test]
    fn the_sentence_of_each_number_is_reported() {
        let mut known = Figures::new();
        known.add_text("10");
        let found = known.unsupported("Orders grew 12.5% to 10. That beat the plan of 9.", rules());
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].number, "12.5%");
        assert_eq!(found[0].sentence, "Orders grew 12.5% to 10.");
        assert_eq!(found[1].sentence, "That beat the plan of 9.");
    }
}