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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! The attribution check of a report: a figure must stand next to the entity whose facts hold it.
//!
//! [`super::figures`] asks whether a number is one of the facts. A report can still give a true
//! number to the wrong entity: "Garden reached 31% of revenue" when 31% is the share of
//! Electronics. Here the facts are grouped by entity (a store, a product category, a
//! campaign), and every figure of a text is compared with the entity the text gives it to:
//!
//! - The text **names** an entity by its label or an alias, as a whole word, in any case, with
//!   any run of spaces between the words of the label. The longest label wins
//!   ("Garden Tools" before "Garden"), and a label is never read as figures ("Store 12").
//! - A figure is **given to** the entity named closest before it in its clause. When none is, a
//!   figure that opens its clause goes to the first entity named after it in the clause, any
//!   other to the entity named closest before it in its sentence, else the first one after it,
//!   else the entity the field is about (its *scope*). Clauses end at a comma or a semicolon
//!   followed by a space, a bracket, a dash between spaces and words such as "while", "but",
//!   "sedangkan", never inside a label.
//! - A **group** ("all categories", "campaigns") names no entity of its own: when a figure is
//!   given to a group, the entity the sentence names decides, else the scope when it holds the
//!   figure. A group with no facts allows any figure; a group with facts (the total of all
//!   campaigns) must hold it.
//! - A figure is **misattributed** when some entities hold it and the one it is given to does
//!   not. A figure no entity holds is left to the numbers check, and a figure given to no entity
//!   is not judged. Small counts (`3 stores`, up to [`AttributionRules::integers_up_to`]) and
//!   years (1900 to 2100) written with digits alone are not judged: too many entities share
//!   them.
//!
//! Figures are compared as the numbers check compares them ([`super::figures::NumberRules`]):
//! rounding, percentages and ratios, notations.

use super::figures::{Figures, NumberRules, scan, sentence_at, sentence_span};

/// Words that start a new clause.
const JOINERS: &[&str] = &["while", "whilst", "whereas", "but", "sedangkan", "tetapi", "tapi", "namun", "padahal"];

/// How the attribution check judges figures.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AttributionRules {
    pub numbers: NumberRules,
    /// Numbers written with digits alone up to this value are counts too common to judge.
    pub integers_up_to: f64,
}

impl Default for AttributionRules {
    fn default() -> Self {
        Self { numbers: NumberRules::default(), integers_up_to: 10.0 }
    }
}

/// A figure given to an entity whose facts do not hold it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Misattributed {
    /// The number as the text writes it.
    pub number: String,
    pub sentence: String,
    /// The label of the entity the text gives the figure to.
    pub named: String,
    /// The labels of the entities whose facts hold it.
    pub owners: Vec<String>,
}

/// One entity: what names it and the numbers its facts hold.
#[derive(Clone, Debug)]
struct Entity {
    label: String,
    aliases: Vec<String>,
    group: bool,
    figures: Figures,
}

/// The entities of a report and their facts.
#[derive(Clone, Debug, Default)]
pub struct Entities {
    list: Vec<Entity>,
}

/// Where a text names an entity: its index and byte span.
#[derive(Clone, Copy, Debug)]
struct Mention {
    entity: usize,
    start: usize,
    end: usize,
}

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

    /// Whether there is no entity.
    pub fn is_empty(&self) -> bool {
        self.list.is_empty()
    }

    /// The index of the entity labelled `label` (any case), added without facts when missing.
    fn entry(&mut self, label: &str) -> usize {
        let label = label.trim();
        if let Some(index) = self.find(label) {
            return index;
        }
        self.list.push(Entity { label: label.to_owned(), aliases: Vec::new(), group: false, figures: Figures::new() });
        self.list.len() - 1
    }

    fn find(&self, label: &str) -> Option<usize> {
        let label = label.trim();
        self.list.iter().position(|entity| entity.label.to_lowercase() == label.to_lowercase())
    }

    /// Adds the entity `label` with the numbers of `facts` (a JSON value: its numbers as they
    /// are, its strings as texts). An entity added twice keeps the facts and aliases of both.
    pub fn add(&mut self, label: &str, aliases: &[String], group: bool, facts: &serde_json::Value) {
        if label.trim().is_empty() {
            return;
        }
        let index = self.entry(label);
        if let Some(entity) = self.list.get_mut(index) {
            for alias in aliases {
                let alias = alias.trim();
                if !alias.is_empty() && !entity.aliases.iter().any(|known| known.eq_ignore_ascii_case(alias)) {
                    entity.aliases.push(alias.to_owned());
                }
            }
            entity.group |= group;
            entity.figures.add_json(facts);
        }
    }

    /// Adds a group word that names no entity ("all stores", "campaigns").
    pub fn add_group(&mut self, label: &str) {
        self.add(label, &[], true, &serde_json::Value::Null);
    }

    /// Adds the entities of a JSON value:
    ///
    /// - a list of records, each naming its entity under `label_key` with optional `aliases` (a
    ///   list of strings) and `group` (a bool); every other field holds the entity's facts:
    ///   `[{"entity": "Garden", "aliases": ["garden goods"], "revenue": 1200}]`. Records with
    ///   the same label make one entity, so `{entity, metric, value}` rows work too;
    /// - an object of facts per label: `{"Garden": {"revenue": 1200}, "Toys": {"revenue": 900}}`.
    ///
    /// Returns what is wrong with the value, if anything.
    pub fn add_json(&mut self, value: &serde_json::Value, label_key: &str) -> Result<(), String> {
        match value {
            serde_json::Value::Array(records) => {
                for (index, record) in records.iter().enumerate() {
                    self.add_record(record, label_key).map_err(|problem| format!("item {index}: {problem}"))?;
                }
                Ok(())
            }
            serde_json::Value::Object(per_label) => {
                for (label, facts) in per_label {
                    self.add(label, &[], false, facts);
                }
                Ok(())
            }
            other => Err(format!("expected a list of records or an object of facts per entity, got {}", kind(other))),
        }
    }

    fn add_record(&mut self, record: &serde_json::Value, label_key: &str) -> Result<(), String> {
        let serde_json::Value::Object(fields) = record else {
            return Err(format!("expected a record (an object), got {}", kind(record)));
        };
        let label = match fields.get(label_key) {
            Some(serde_json::Value::String(label)) => label.as_str(),
            Some(serde_json::Value::Number(_)) | Some(serde_json::Value::Bool(_)) => {
                return Err(format!("`{label_key}` must be a string"));
            }
            // A record with no label (a missing or empty name in the data) names nothing.
            Some(serde_json::Value::Null) | None => return Ok(()),
            Some(_) => return Err(format!("`{label_key}` must be a string")),
        };
        let aliases = match fields.get("aliases") {
            None | Some(serde_json::Value::Null) => Vec::new(),
            Some(serde_json::Value::Array(aliases)) => aliases
                .iter()
                .map(|alias| alias.as_str().map(str::to_owned).ok_or("`aliases` must be a list of strings"))
                .collect::<Result<Vec<_>, _>>()?,
            Some(_) => return Err("`aliases` must be a list of strings".to_owned()),
        };
        let group = match fields.get("group") {
            None | Some(serde_json::Value::Null) => false,
            Some(serde_json::Value::Bool(group)) => *group,
            Some(_) => return Err("`group` must be a bool".to_owned()),
        };
        let facts: serde_json::Map<String, serde_json::Value> = fields
            .iter()
            .filter(|(name, _)| !matches!(name.as_str(), "aliases" | "group") && name.as_str() != label_key)
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect();
        self.add(label, &aliases, group, &serde_json::Value::Object(facts));
        Ok(())
    }

    /// The figures of `text` given to an entity whose facts do not hold them. `scope` is the
    /// label of the entity the text is about, if any: an entity no source lists holds nothing.
    pub fn misattributed(&self, text: &str, scope: Option<&str>, rules: AttributionRules) -> Vec<Misattributed> {
        if self.list.is_empty() {
            return Vec::new();
        }
        // A scope no source lists is an entity of its own that holds nothing, after the others.
        let scope_label = scope.map(str::trim).filter(|label| !label.is_empty());
        let scope = scope_label.map(|label| self.find(label).unwrap_or(self.list.len()));
        let label = |index: usize| match self.list.get(index) {
            Some(entity) => entity.label.clone(),
            None => scope_label.unwrap_or_default().to_owned(),
        };
        let mentions = self.mentions(text);
        let blanked = blank(text, &mentions);
        let numbers = scan(&blanked);
        let spans: Vec<(usize, usize)> = numbers.iter().map(|number| (number.at, number.end)).collect();
        let mut found = Vec::new();
        for number in numbers {
            if number.plain_value().is_some_and(|value| value <= rules.integers_up_to || is_a_year(value)) {
                continue;
            }
            let owners: Vec<usize> = self
                .list
                .iter()
                .enumerate()
                .filter(|(_, entity)| entity.figures.holds(&number, rules.numbers))
                .map(|(index, _)| index)
                .collect();
            if owners.is_empty() {
                continue;
            }
            let Some(named) = self.given_to(text, &mentions, number.at, number.end, scope, &owners) else {
                continue;
            };
            if owners.contains(&named) || listed(text, &mentions, &spans, number.at, named, &owners) {
                continue;
            }
            found.push(Misattributed {
                number: number.text,
                sentence: sentence_at(text, number.at),
                named: label(named),
                owners: owners.into_iter().map(label).collect(),
            });
        }
        found
    }

    /// The entity a figure at `start..end` of `text` is given to, `None` when it is given to
    /// none, or to a group that allows it.
    fn given_to(
        &self,
        text: &str,
        mentions: &[Mention],
        start: usize,
        end: usize,
        scope: Option<usize>,
        owners: &[usize],
    ) -> Option<usize> {
        let (sentence_start, sentence_end) = sentence_span(text, start);
        let clause = clause_span(text, sentence_start, sentence_end, start, mentions);
        let (clause_start, clause_end) = (clause.start, clause.end);
        let within = |from: usize, to: usize, specific: bool| -> Vec<Mention> {
            mentions
                .iter()
                .filter(|mention| mention.start >= from && mention.end <= to)
                .filter(|mention| !specific || self.list.get(mention.entity).is_some_and(|entity| !entity.group))
                .copied()
                .collect()
        };
        // A figure that opens its clause ("..., 14% from garden") is about the entity after it
        // in the clause. Otherwise the clause continues what the sentence said before ("...,
        // which delivered 100% with 1 new customer"): the entity before it in the sentence.
        let opens_the_clause = text.get(clause_start..start).is_some_and(|before| {
            !before.trim_end_matches(|c: char| c.is_alphabetic() || c == '$').contains(char::is_alphabetic)
        });
        let pick = |specific: bool| {
            let in_clause = within(clause_start, clause_end, specific);
            let sentence = within(sentence_start, sentence_end, specific);
            // Never past a joining word: "X rose 5%, while campaigns fell" is not about campaigns.
            let ahead = within(sentence_start, clause.next_statement, specific);
            before(&in_clause, start)
                .or_else(|| if opens_the_clause { after(&in_clause, end) } else { None })
                .or_else(|| before(&sentence, start))
                .or_else(|| after(&ahead, end))
        };
        let named = pick(false).or(scope)?;
        let Some(group) = self.list.get(named).filter(|entity| entity.group) else {
            return Some(named);
        };
        if let Some(specific) = pick(true) {
            return Some(specific);
        }
        if scope.is_some_and(|scope| owners.contains(&scope)) || group.figures.is_empty() {
            return None;
        }
        Some(named)
    }

    /// Where `text` names the entities: the longest label first, never two on the same words.
    fn mentions(&self, text: &str) -> Vec<Mention> {
        let chars: Vec<(usize, char)> = text.char_indices().collect();
        let mut labels: Vec<(Vec<String>, usize)> = self
            .list
            .iter()
            .enumerate()
            .flat_map(|(index, entity)| {
                std::iter::once(&entity.label).chain(&entity.aliases).map(move |label| (label, index))
            })
            .map(|(label, index)| (label.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>(), index))
            .filter(|(words, _)| !words.is_empty())
            .collect();
        labels
            .sort_by_key(|(words, _)| std::cmp::Reverse(words.iter().map(|word| word.chars().count()).sum::<usize>()));
        let mut taken = vec![false; chars.len()];
        let mut found = Vec::new();
        for (words, entity) in &labels {
            let mut from = 0;
            while from < chars.len() {
                let Some(length) = match_at(&chars, from, words) else {
                    from += 1;
                    continue;
                };
                let span = from..from + length;
                if taken.get(span.clone()).is_some_and(|taken| taken.iter().any(|taken| *taken)) {
                    from += 1;
                    continue;
                }
                taken.get_mut(span.clone()).into_iter().flatten().for_each(|taken| *taken = true);
                let start = chars.get(span.start).map_or(text.len(), |(byte, _)| *byte);
                let end = chars.get(span.end).map_or(text.len(), |(byte, _)| *byte);
                found.push(Mention { entity: *entity, start, end });
                from = span.end;
            }
        }
        found
    }
}

/// Whether the figure at `at` follows a list of entities in its clause that includes `named` and
/// one of `owners`, named one after the other with no figure between them ("A and B followed at 49.7%
/// and 32.1%"): the figures may go to them in order. "A at 30% and B at 50%" is no such list.
fn listed(
    text: &str,
    mentions: &[Mention],
    figures: &[(usize, usize)],
    at: usize,
    named: usize,
    owners: &[usize],
) -> bool {
    let (sentence_start, sentence_end) = sentence_span(text, at);
    let clause = clause_span(text, sentence_start, sentence_end, at, mentions);
    let mut earlier: Vec<&Mention> =
        mentions.iter().filter(|mention| mention.start >= clause.start && mention.end <= at).collect();
    earlier.sort_by_key(|mention| mention.start);
    let Some(last) = earlier.pop() else { return false };
    let mut run = vec![last.entity];
    let mut next = last;
    while let Some(previous) = earlier.pop() {
        let figure_between = figures.iter().any(|(start, end)| *start >= previous.end && *end <= next.start);
        if figure_between {
            break;
        }
        run.push(previous.entity);
        next = previous;
    }
    run.len() >= 2 && run.contains(&named) && run.iter().any(|entity| owners.contains(entity))
}

/// The entity of the mention closest before `start` (by where it ends).
fn before(mentions: &[Mention], start: usize) -> Option<usize> {
    mentions
        .iter()
        .filter(|mention| mention.end <= start)
        .max_by_key(|mention| mention.end)
        .map(|mention| mention.entity)
}

/// The entity of the first mention after `end`.
fn after(mentions: &[Mention], end: usize) -> Option<usize> {
    mentions
        .iter()
        .filter(|mention| mention.start >= end)
        .min_by_key(|mention| mention.start)
        .map(|mention| mention.entity)
}

/// How many characters of `chars` from `at` spell `words` (lower case) as whole words, with any
/// run of whitespace between them.
fn match_at(chars: &[(usize, char)], at: usize, words: &[String]) -> Option<usize> {
    if at > 0 && chars.get(at - 1).is_some_and(|(_, c)| c.is_alphanumeric()) {
        return None;
    }
    let mut index = at;
    for (number, word) in words.iter().enumerate() {
        if number > 0 {
            let spaces_from = index;
            while chars.get(index).is_some_and(|(_, c)| c.is_whitespace()) {
                index += 1;
            }
            if index == spaces_from {
                return None;
            }
        }
        for expected in word.chars() {
            let (_, written) = chars.get(index)?;
            if written.to_lowercase().ne(expected.to_lowercase()) {
                return None;
            }
            index += 1;
        }
    }
    if chars.get(index).is_some_and(|(_, c)| c.is_alphanumeric()) {
        return None;
    }
    Some(index - at)
}

/// `text` with the mentioned labels turned into spaces, byte for byte, so offsets stay.
fn blank(text: &str, mentions: &[Mention]) -> String {
    text.char_indices()
        .map(|(at, c)| {
            if mentions.iter().any(|mention| at >= mention.start && at < mention.end) {
                " ".repeat(c.len_utf8())
            } else {
                c.to_string()
            }
        })
        .collect()
}

/// The clauses of a sentence around a figure.
struct Clause {
    start: usize,
    end: usize,
    /// Where the first joining word after the figure starts ("while", "but"), else the end of
    /// the sentence: what comes after it is another statement.
    next_statement: usize,
}

/// The clause around `at`, inside the sentence `sentence_start..sentence_end`. A comma or a
/// word inside a label ("Buy One, Get One") ends no clause.
fn clause_span(text: &str, sentence_start: usize, sentence_end: usize, at: usize, mentions: &[Mention]) -> Clause {
    let sentence = text.get(sentence_start..sentence_end).unwrap_or_default();
    // Each break: its span in the sentence and whether it is a joining word.
    let mut breaks: Vec<(usize, usize, bool)> = Vec::new();
    let chars: Vec<(usize, char)> = sentence.char_indices().collect();
    for (position, &(offset, c)) in chars.iter().enumerate() {
        let next_is_space = chars.get(position + 1).is_some_and(|(_, next)| next.is_whitespace());
        let previous_is_space = position > 0 && chars.get(position - 1).is_some_and(|(_, prev)| prev.is_whitespace());
        let cuts = match c {
            ',' | ';' => next_is_space,
            '(' | ')' | '[' | ']' => true,
            '-' | '\u{2013}' | '\u{2014}' => next_is_space && previous_is_space,
            _ => false,
        };
        if cuts {
            breaks.push((offset, offset + c.len_utf8(), false));
        }
    }
    let mut word_start = None;
    for (position, &(offset, c)) in chars.iter().enumerate() {
        if c.is_alphabetic() {
            word_start.get_or_insert(offset);
            let ends = chars.get(position + 1).is_none_or(|(_, next)| !next.is_alphabetic());
            if let (true, Some(from)) = (ends, word_start) {
                let to = offset + c.len_utf8();
                let word = sentence.get(from..to).unwrap_or_default().to_lowercase();
                if JOINERS.contains(&word.as_str()) {
                    breaks.push((from, to, true));
                }
                word_start = None;
            }
        } else {
            word_start = None;
        }
    }
    breaks.retain(|(from, to, _)| {
        let (from, to) = (sentence_start + from, sentence_start + to);
        !mentions.iter().any(|mention| from < mention.end && to > mention.start)
    });
    let at = at.saturating_sub(sentence_start);
    let start = breaks.iter().filter(|(_, end, _)| *end <= at).map(|(_, end, _)| *end).max().unwrap_or(0);
    let end =
        breaks.iter().filter(|(from, _, _)| *from >= at).map(|(from, _, _)| *from).min().unwrap_or(sentence.len());
    let next_statement = breaks
        .iter()
        .filter(|(from, _, joiner)| *joiner && *from >= at)
        .map(|(from, _, _)| *from)
        .min()
        .unwrap_or(sentence.len());
    Clause { start: sentence_start + start, end: sentence_start + end, next_statement: sentence_start + next_statement }
}

fn is_a_year(value: f64) -> bool {
    (1900.0..=2100.0).contains(&value) && value.fract() == 0.0
}

fn kind(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "a bool",
        serde_json::Value::Number(_) => "a number",
        serde_json::Value::String(_) => "a string",
        serde_json::Value::Array(_) => "a list",
        serde_json::Value::Object(_) => "an object",
    }
}

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

    use super::*;
    use crate::grounding::figures::Tolerance;

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

    /// A shop with three product categories and the whole store as a group with facts.
    fn shop() -> Entities {
        let mut entities = Entities::new();
        entities
            .add_json(
                &json!([
                    {"entity": "Electronics", "aliases": ["gadgets"], "revenue": 48200, "share": 0.3125, "orders": 1240, "growth_pct": 12.4},
                    {"entity": "Garden Tools", "aliases": ["garden"], "revenue": 21900, "share": 0.1419, "orders": 615, "growth_pct": -3.8},
                    {"entity": "Toys", "revenue": 15350, "share": 0.0995, "orders": 702, "growth_pct": 7.1},
                    {"entity": "All categories", "aliases": ["the store", "overall"], "group": true, "revenue": 154250, "orders": 4310}
                ]),
                "entity",
            )
            .unwrap();
        entities.add_group("categories");
        entities
    }

    fn found(text: &str, scope: Option<&str>) -> Vec<(String, String, Vec<String>)> {
        shop()
            .misattributed(text, scope, rules())
            .into_iter()
            .map(|wrong| (wrong.number, wrong.named, wrong.owners))
            .collect()
    }

    #[test]
    fn true_attributions_pass() {
        let report = "Electronics led with $48.2k in revenue (31.25% of sales) on 1,240 orders. \
                      Garden Tools fell 3.8% to 21,900, while Toys grew 7.1% to 15,350. \
                      31% of revenue came from gadgets, 14% from garden. \
                      Across all categories the store took 154,250 on 4,310 orders.";
        assert_eq!(found(report, None), []);
    }

    #[test]
    fn a_figure_of_another_entity_is_caught() {
        assert_eq!(
            found("Toys reached 31.25% of sales.", None),
            [("31.25%".to_owned(), "Toys".to_owned(), vec!["Electronics".to_owned()])]
        );
        // An alias names its entity.
        assert_eq!(found("Gadgets took 702 orders.", None)[0].2, ["Toys"]);
    }

    #[test]
    fn swapped_entities_are_caught() {
        let wrong = found("Electronics grew 7.1% and Toys grew 12.4%.", None);
        assert_eq!(wrong.len(), 2);
        assert_eq!((wrong[0].1.as_str(), wrong[1].1.as_str()), ("Electronics", "Toys"));
    }

    #[test]
    fn a_swapped_metric_is_not_a_misattribution_of_the_entity() {
        // The figure is the entity's own, under another metric: the attribution holds. The
        // numbers check does not judge metrics either, so this is out of scope.
        assert_eq!(found("Toys had 702 in revenue.", None), []);
    }

    #[test]
    fn a_figure_of_another_entity_under_another_metric_is_caught() {
        // 1,240 is the orders of Electronics: written as the revenue of Garden Tools.
        assert_eq!(found("Garden Tools revenue was 1,240.", None)[0].2, ["Electronics"]);
    }

    #[test]
    fn the_longest_label_wins_and_whole_words_only() {
        let mut entities = Entities::new();
        entities.add("Garden", &[], false, &json!({"revenue": 500}));
        entities.add("Garden Tools", &[], false, &json!({"revenue": 21900}));
        entities.add("Store 12", &[], false, &json!({"revenue": 777}));
        assert!(entities.misattributed("Garden  tools made 21,900.", None, rules()).is_empty());
        assert_eq!(entities.misattributed("Garden made 21,900.", None, rules()).len(), 1);
        // "Gardens" is not "Garden", and the 12 of "Store 12" is not a figure.
        assert!(entities.misattributed("Gardens made 21,900. Store 12 made 777.", None, rules()).is_empty());
    }

    #[test]
    fn a_group_word_lets_the_named_entity_or_the_scope_decide() {
        // The category the sentence names decides, wherever the group word stands.
        assert_eq!(found("Among categories, Electronics took 48,200.", None), []);
        assert_eq!(found("Among categories, Toys took 48,200.", None)[0].1, "Toys");
        // A group word with no facts and no named entity: the scope decides, else it passes.
        assert_eq!(found("These categories took 48,200.", Some("Electronics")), []);
        assert_eq!(found("These categories took 48,200.", None), []);
        // A group with facts must hold the figure when nothing else is named.
        assert_eq!(found("The store took 154,250 on 4,310 orders.", None), []);
        assert_eq!(found("Overall revenue was 48,200.", None)[0].1, "All categories");
    }

    #[test]
    fn the_scope_is_the_entity_of_a_field_that_names_none() {
        assert_eq!(found("Revenue grew 12.4% on 1,240 orders.", Some("Electronics")), []);
        assert_eq!(found("Revenue grew 12.4% on 1,240 orders.", Some("Toys")).len(), 2);
        // A sentence that names an entity is not about the scope.
        assert_eq!(found("Toys grew 7.1%.", Some("Electronics")), []);
        // An entity no source lists holds nothing.
        assert_eq!(found("Revenue was 15,350.", Some("Books"))[0].1, "Books");
    }

    #[test]
    fn small_counts_years_and_unowned_figures_are_not_judged() {
        assert_eq!(found("In 2026 Toys opened 4 stores and earned 99,999.", None), []);
        let mut entities = shop();
        entities.add("Books", &[], false, &json!({"stores": 3, "opened": 2025}));
        assert!(entities.misattributed("Toys opened 3 stores in 2025.", None, rules()).is_empty());
        let loose = AttributionRules { integers_up_to: 0.0, ..rules() };
        assert_eq!(entities.misattributed("Toys opened 3 stores.", None, loose)[0].owners, ["Books"]);
    }

    #[test]
    fn clauses_bound_the_nearest_entity() {
        // 14% is in the clause of "garden", although "gadgets" stands closer before it.
        assert_eq!(found("31% of revenue came from gadgets, 14% from garden.", None), []);
        assert_eq!(found("14% of revenue came from gadgets, 31% from garden.", None).len(), 2);
        assert_eq!(found("Electronics revenue is 48,200 whereas Toys 21,900.", None)[0].1, "Toys");
        // A clause that continues the sentence is about the entity before it, not a phrase after.
        let mut entities = shop();
        entities.add("New Buyers", &[], false, &json!({"share": 0.2}));
        let text = "Orders came from Toys, which took 15,350 with 3 new buyers.";
        assert!(entities.misattributed(text, None, rules()).is_empty());
        assert_eq!(found("Electronics led, ahead of Toys with 48,200.", None)[0].1, "Toys");
    }

    #[test]
    fn a_comma_inside_a_label_ends_no_clause() {
        let mut offers = Entities::new();
        offers.add("Buy One, Get One", &[], false, &json!({"share": 0.1277}));
        offers.add("Get One", &[], false, &json!({"share": 0.617}));
        offers.add("Flat 20 Off", &[], false, &json!({"share": 0.0426}));
        let text = "Get One led with 61.70%, followed by Buy One, Get One at 12.77% and Flat 20 Off at 4.26%.";
        assert!(offers.misattributed(text, None, rules()).is_empty());
        let swapped = "Get One led with 12.77%, followed by Buy One, Get One at 61.70%.";
        assert_eq!(offers.misattributed(swapped, None, rules()).len(), 2);
    }

    #[test]
    fn figures_after_a_list_of_entities_go_to_them_in_order() {
        assert_eq!(found("Electronics and Toys followed at 31.25% and 9.95%.", None), []);
        assert_eq!(found("Toys and Electronics followed at 31.25% and 9.95%.", None), []);
        // Interleaved, each figure is next to its entity.
        assert_eq!(found("Electronics at 9.95% and Toys at 31.25%.", None).len(), 2);
        // A list that does not hold the figure is still caught.
        assert_eq!(found("Garden Tools and Toys followed at 31.25%.", None).len(), 1);
    }

    #[test]
    fn a_joining_word_ends_the_search_ahead() {
        // Nothing named before the figure, and the entity ahead is in another statement.
        assert_eq!(found("Revenue rose 31.25%, while Toys fell.", None), []);
        assert_eq!(found("Revenue rose 31.25% for Toys.", None).len(), 1);
    }

    #[test]
    fn rows_and_objects_make_entities() {
        let mut rows = Entities::new();
        rows.add_json(
            &json!([
                {"entity": "North", "metric": "revenue", "value": 5100},
                {"entity": "north", "metric": "visits", "value": 830},
                {"entity": "South", "metric": "revenue", "value": 4400},
                {"entity": null, "metric": "revenue", "value": 1}
            ]),
            "entity",
        )
        .unwrap();
        assert!(rows.misattributed("North had 830 visits and 5,100 in revenue.", None, rules()).is_empty());
        assert_eq!(rows.misattributed("South had 830 visits.", None, rules())[0].owners, ["North"]);

        let mut per_label = Entities::new();
        per_label.add_json(&json!({"North": {"revenue": 5100}, "South": {"revenue": 4400}}), "entity").unwrap();
        assert_eq!(per_label.misattributed("North made 4,400.", None, rules())[0].named, "North");

        let mut named = Entities::new();
        named.add_json(&json!([{"name": "East", "revenue": 3000}]), "name").unwrap();
        assert!(named.misattributed("East made 3,000.", None, rules()).is_empty());
    }

    #[test]
    fn malformed_entities_are_reported() {
        let mut entities = Entities::new();
        assert!(entities.add_json(&json!("Garden"), "entity").unwrap_err().contains("a string"));
        assert!(entities.add_json(&json!([1]), "entity").unwrap_err().starts_with("item 0"));
        assert!(entities.add_json(&json!([{"entity": 5}]), "entity").unwrap_err().contains("must be a string"));
        assert!(entities.add_json(&json!([{"entity": "A", "aliases": "a"}]), "entity").is_err());
        assert!(entities.add_json(&json!([{"entity": "A", "group": "yes"}]), "entity").is_err());
    }

    #[test]
    fn unicode_and_multibyte_text_keeps_its_offsets() {
        let mut entities = Entities::new();
        entities.add("Café Düsseldorf", &[], false, &json!({"revenue": 5100}));
        entities.add("Été", &[], false, &json!({"revenue": 4400}));
        assert!(entities.misattributed("Café  düsseldorf — 5.100 € — été 4.400 €.", None, rules()).is_empty());
        assert_eq!(entities.misattributed("ÉTÉ réalise 5.100 €.", None, rules())[0].named, "Été");
    }
}