Skip to main content

graphrt_core/grounding/
entities.rs

1//! The attribution check of a report: a figure must stand next to the entity whose facts hold it.
2//!
3//! [`super::figures`] asks whether a number is one of the facts. A report can still give a true
4//! number to the wrong entity: "Garden reached 31% of revenue" when 31% is the share of
5//! Electronics. Here the facts are grouped by entity (a store, a product category, a
6//! campaign), and every figure of a text is compared with the entity the text gives it to:
7//!
8//! - The text **names** an entity by its label or an alias, as a whole word, in any case, with
9//!   any run of spaces between the words of the label. The longest label wins
10//!   ("Garden Tools" before "Garden"), and a label is never read as figures ("Store 12").
11//! - A figure is **given to** the entity named closest before it in its clause. When none is, a
12//!   figure that opens its clause goes to the first entity named after it in the clause, any
13//!   other to the entity named closest before it in its sentence, else the first one after it,
14//!   else the entity the field is about (its *scope*). Clauses end at a comma or a semicolon
15//!   followed by a space, a bracket, a dash between spaces and words such as "while", "but",
16//!   "sedangkan", never inside a label.
17//! - A **group** ("all categories", "campaigns") names no entity of its own: when a figure is
18//!   given to a group, the entity the sentence names decides, else the scope when it holds the
19//!   figure. A group with no facts allows any figure; a group with facts (the total of all
20//!   campaigns) must hold it.
21//! - A figure is **misattributed** when some entities hold it and the one it is given to does
22//!   not. A figure no entity holds is left to the numbers check, and a figure given to no entity
23//!   is not judged. Small counts (`3 stores`, up to [`AttributionRules::integers_up_to`]) and
24//!   years (1900 to 2100) written with digits alone are not judged: too many entities share
25//!   them.
26//!
27//! Figures are compared as the numbers check compares them ([`super::figures::NumberRules`]):
28//! rounding, percentages and ratios, notations.
29
30use super::figures::{Figures, NumberRules, scan, sentence_at, sentence_span};
31
32/// Words that start a new clause.
33const JOINERS: &[&str] = &["while", "whilst", "whereas", "but", "sedangkan", "tetapi", "tapi", "namun", "padahal"];
34
35/// How the attribution check judges figures.
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct AttributionRules {
38    pub numbers: NumberRules,
39    /// Numbers written with digits alone up to this value are counts too common to judge.
40    pub integers_up_to: f64,
41}
42
43impl Default for AttributionRules {
44    fn default() -> Self {
45        Self { numbers: NumberRules::default(), integers_up_to: 10.0 }
46    }
47}
48
49/// A figure given to an entity whose facts do not hold it.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct Misattributed {
52    /// The number as the text writes it.
53    pub number: String,
54    pub sentence: String,
55    /// The label of the entity the text gives the figure to.
56    pub named: String,
57    /// The labels of the entities whose facts hold it.
58    pub owners: Vec<String>,
59}
60
61/// One entity: what names it and the numbers its facts hold.
62#[derive(Clone, Debug)]
63struct Entity {
64    label: String,
65    aliases: Vec<String>,
66    group: bool,
67    figures: Figures,
68}
69
70/// The entities of a report and their facts.
71#[derive(Clone, Debug, Default)]
72pub struct Entities {
73    list: Vec<Entity>,
74}
75
76/// Where a text names an entity: its index and byte span.
77#[derive(Clone, Copy, Debug)]
78struct Mention {
79    entity: usize,
80    start: usize,
81    end: usize,
82}
83
84impl Entities {
85    pub fn new() -> Self {
86        Self::default()
87    }
88
89    /// Whether there is no entity.
90    pub fn is_empty(&self) -> bool {
91        self.list.is_empty()
92    }
93
94    /// The index of the entity labelled `label` (any case), added without facts when missing.
95    fn entry(&mut self, label: &str) -> usize {
96        let label = label.trim();
97        if let Some(index) = self.find(label) {
98            return index;
99        }
100        self.list.push(Entity { label: label.to_owned(), aliases: Vec::new(), group: false, figures: Figures::new() });
101        self.list.len() - 1
102    }
103
104    fn find(&self, label: &str) -> Option<usize> {
105        let label = label.trim();
106        self.list.iter().position(|entity| entity.label.to_lowercase() == label.to_lowercase())
107    }
108
109    /// Adds the entity `label` with the numbers of `facts` (a JSON value: its numbers as they
110    /// are, its strings as texts). An entity added twice keeps the facts and aliases of both.
111    pub fn add(&mut self, label: &str, aliases: &[String], group: bool, facts: &serde_json::Value) {
112        if label.trim().is_empty() {
113            return;
114        }
115        let index = self.entry(label);
116        if let Some(entity) = self.list.get_mut(index) {
117            for alias in aliases {
118                let alias = alias.trim();
119                if !alias.is_empty() && !entity.aliases.iter().any(|known| known.eq_ignore_ascii_case(alias)) {
120                    entity.aliases.push(alias.to_owned());
121                }
122            }
123            entity.group |= group;
124            entity.figures.add_json(facts);
125        }
126    }
127
128    /// Adds a group word that names no entity ("all stores", "campaigns").
129    pub fn add_group(&mut self, label: &str) {
130        self.add(label, &[], true, &serde_json::Value::Null);
131    }
132
133    /// Adds the entities of a JSON value:
134    ///
135    /// - a list of records, each naming its entity under `label_key` with optional `aliases` (a
136    ///   list of strings) and `group` (a bool); every other field holds the entity's facts:
137    ///   `[{"entity": "Garden", "aliases": ["garden goods"], "revenue": 1200}]`. Records with
138    ///   the same label make one entity, so `{entity, metric, value}` rows work too;
139    /// - an object of facts per label: `{"Garden": {"revenue": 1200}, "Toys": {"revenue": 900}}`.
140    ///
141    /// Returns what is wrong with the value, if anything.
142    pub fn add_json(&mut self, value: &serde_json::Value, label_key: &str) -> Result<(), String> {
143        match value {
144            serde_json::Value::Array(records) => {
145                for (index, record) in records.iter().enumerate() {
146                    self.add_record(record, label_key).map_err(|problem| format!("item {index}: {problem}"))?;
147                }
148                Ok(())
149            }
150            serde_json::Value::Object(per_label) => {
151                for (label, facts) in per_label {
152                    self.add(label, &[], false, facts);
153                }
154                Ok(())
155            }
156            other => Err(format!("expected a list of records or an object of facts per entity, got {}", kind(other))),
157        }
158    }
159
160    fn add_record(&mut self, record: &serde_json::Value, label_key: &str) -> Result<(), String> {
161        let serde_json::Value::Object(fields) = record else {
162            return Err(format!("expected a record (an object), got {}", kind(record)));
163        };
164        let label = match fields.get(label_key) {
165            Some(serde_json::Value::String(label)) => label.as_str(),
166            Some(serde_json::Value::Number(_)) | Some(serde_json::Value::Bool(_)) => {
167                return Err(format!("`{label_key}` must be a string"));
168            }
169            // A record with no label (a missing or empty name in the data) names nothing.
170            Some(serde_json::Value::Null) | None => return Ok(()),
171            Some(_) => return Err(format!("`{label_key}` must be a string")),
172        };
173        let aliases = match fields.get("aliases") {
174            None | Some(serde_json::Value::Null) => Vec::new(),
175            Some(serde_json::Value::Array(aliases)) => aliases
176                .iter()
177                .map(|alias| alias.as_str().map(str::to_owned).ok_or("`aliases` must be a list of strings"))
178                .collect::<Result<Vec<_>, _>>()?,
179            Some(_) => return Err("`aliases` must be a list of strings".to_owned()),
180        };
181        let group = match fields.get("group") {
182            None | Some(serde_json::Value::Null) => false,
183            Some(serde_json::Value::Bool(group)) => *group,
184            Some(_) => return Err("`group` must be a bool".to_owned()),
185        };
186        let facts: serde_json::Map<String, serde_json::Value> = fields
187            .iter()
188            .filter(|(name, _)| !matches!(name.as_str(), "aliases" | "group") && name.as_str() != label_key)
189            .map(|(name, value)| (name.clone(), value.clone()))
190            .collect();
191        self.add(label, &aliases, group, &serde_json::Value::Object(facts));
192        Ok(())
193    }
194
195    /// The figures of `text` given to an entity whose facts do not hold them. `scope` is the
196    /// label of the entity the text is about, if any: an entity no source lists holds nothing.
197    pub fn misattributed(&self, text: &str, scope: Option<&str>, rules: AttributionRules) -> Vec<Misattributed> {
198        if self.list.is_empty() {
199            return Vec::new();
200        }
201        // A scope no source lists is an entity of its own that holds nothing, after the others.
202        let scope_label = scope.map(str::trim).filter(|label| !label.is_empty());
203        let scope = scope_label.map(|label| self.find(label).unwrap_or(self.list.len()));
204        let label = |index: usize| match self.list.get(index) {
205            Some(entity) => entity.label.clone(),
206            None => scope_label.unwrap_or_default().to_owned(),
207        };
208        let mentions = self.mentions(text);
209        let blanked = blank(text, &mentions);
210        let numbers = scan(&blanked);
211        let spans: Vec<(usize, usize)> = numbers.iter().map(|number| (number.at, number.end)).collect();
212        let mut found = Vec::new();
213        for number in numbers {
214            if number.plain_value().is_some_and(|value| value <= rules.integers_up_to || is_a_year(value)) {
215                continue;
216            }
217            let owners: Vec<usize> = self
218                .list
219                .iter()
220                .enumerate()
221                .filter(|(_, entity)| entity.figures.holds(&number, rules.numbers))
222                .map(|(index, _)| index)
223                .collect();
224            if owners.is_empty() {
225                continue;
226            }
227            let Some(named) = self.given_to(text, &mentions, number.at, number.end, scope, &owners) else {
228                continue;
229            };
230            if owners.contains(&named) || listed(text, &mentions, &spans, number.at, named, &owners) {
231                continue;
232            }
233            found.push(Misattributed {
234                number: number.text,
235                sentence: sentence_at(text, number.at),
236                named: label(named),
237                owners: owners.into_iter().map(label).collect(),
238            });
239        }
240        found
241    }
242
243    /// The entity a figure at `start..end` of `text` is given to, `None` when it is given to
244    /// none, or to a group that allows it.
245    fn given_to(
246        &self,
247        text: &str,
248        mentions: &[Mention],
249        start: usize,
250        end: usize,
251        scope: Option<usize>,
252        owners: &[usize],
253    ) -> Option<usize> {
254        let (sentence_start, sentence_end) = sentence_span(text, start);
255        let clause = clause_span(text, sentence_start, sentence_end, start, mentions);
256        let (clause_start, clause_end) = (clause.start, clause.end);
257        let within = |from: usize, to: usize, specific: bool| -> Vec<Mention> {
258            mentions
259                .iter()
260                .filter(|mention| mention.start >= from && mention.end <= to)
261                .filter(|mention| !specific || self.list.get(mention.entity).is_some_and(|entity| !entity.group))
262                .copied()
263                .collect()
264        };
265        // A figure that opens its clause ("..., 14% from garden") is about the entity after it
266        // in the clause. Otherwise the clause continues what the sentence said before ("...,
267        // which delivered 100% with 1 new customer"): the entity before it in the sentence.
268        let opens_the_clause = text.get(clause_start..start).is_some_and(|before| {
269            !before.trim_end_matches(|c: char| c.is_alphabetic() || c == '$').contains(char::is_alphabetic)
270        });
271        let pick = |specific: bool| {
272            let in_clause = within(clause_start, clause_end, specific);
273            let sentence = within(sentence_start, sentence_end, specific);
274            // Never past a joining word: "X rose 5%, while campaigns fell" is not about campaigns.
275            let ahead = within(sentence_start, clause.next_statement, specific);
276            before(&in_clause, start)
277                .or_else(|| if opens_the_clause { after(&in_clause, end) } else { None })
278                .or_else(|| before(&sentence, start))
279                .or_else(|| after(&ahead, end))
280        };
281        let named = pick(false).or(scope)?;
282        let Some(group) = self.list.get(named).filter(|entity| entity.group) else {
283            return Some(named);
284        };
285        if let Some(specific) = pick(true) {
286            return Some(specific);
287        }
288        if scope.is_some_and(|scope| owners.contains(&scope)) || group.figures.is_empty() {
289            return None;
290        }
291        Some(named)
292    }
293
294    /// Where `text` names the entities: the longest label first, never two on the same words.
295    fn mentions(&self, text: &str) -> Vec<Mention> {
296        let chars: Vec<(usize, char)> = text.char_indices().collect();
297        let mut labels: Vec<(Vec<String>, usize)> = self
298            .list
299            .iter()
300            .enumerate()
301            .flat_map(|(index, entity)| {
302                std::iter::once(&entity.label).chain(&entity.aliases).map(move |label| (label, index))
303            })
304            .map(|(label, index)| (label.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>(), index))
305            .filter(|(words, _)| !words.is_empty())
306            .collect();
307        labels
308            .sort_by_key(|(words, _)| std::cmp::Reverse(words.iter().map(|word| word.chars().count()).sum::<usize>()));
309        let mut taken = vec![false; chars.len()];
310        let mut found = Vec::new();
311        for (words, entity) in &labels {
312            let mut from = 0;
313            while from < chars.len() {
314                let Some(length) = match_at(&chars, from, words) else {
315                    from += 1;
316                    continue;
317                };
318                let span = from..from + length;
319                if taken.get(span.clone()).is_some_and(|taken| taken.iter().any(|taken| *taken)) {
320                    from += 1;
321                    continue;
322                }
323                taken.get_mut(span.clone()).into_iter().flatten().for_each(|taken| *taken = true);
324                let start = chars.get(span.start).map_or(text.len(), |(byte, _)| *byte);
325                let end = chars.get(span.end).map_or(text.len(), |(byte, _)| *byte);
326                found.push(Mention { entity: *entity, start, end });
327                from = span.end;
328            }
329        }
330        found
331    }
332}
333
334/// Whether the figure at `at` follows a list of entities in its clause that includes `named` and
335/// one of `owners`, named one after the other with no figure between them ("A and B followed at 49.7%
336/// and 32.1%"): the figures may go to them in order. "A at 30% and B at 50%" is no such list.
337fn listed(
338    text: &str,
339    mentions: &[Mention],
340    figures: &[(usize, usize)],
341    at: usize,
342    named: usize,
343    owners: &[usize],
344) -> bool {
345    let (sentence_start, sentence_end) = sentence_span(text, at);
346    let clause = clause_span(text, sentence_start, sentence_end, at, mentions);
347    let mut earlier: Vec<&Mention> =
348        mentions.iter().filter(|mention| mention.start >= clause.start && mention.end <= at).collect();
349    earlier.sort_by_key(|mention| mention.start);
350    let Some(last) = earlier.pop() else { return false };
351    let mut run = vec![last.entity];
352    let mut next = last;
353    while let Some(previous) = earlier.pop() {
354        let figure_between = figures.iter().any(|(start, end)| *start >= previous.end && *end <= next.start);
355        if figure_between {
356            break;
357        }
358        run.push(previous.entity);
359        next = previous;
360    }
361    run.len() >= 2 && run.contains(&named) && run.iter().any(|entity| owners.contains(entity))
362}
363
364/// The entity of the mention closest before `start` (by where it ends).
365fn before(mentions: &[Mention], start: usize) -> Option<usize> {
366    mentions
367        .iter()
368        .filter(|mention| mention.end <= start)
369        .max_by_key(|mention| mention.end)
370        .map(|mention| mention.entity)
371}
372
373/// The entity of the first mention after `end`.
374fn after(mentions: &[Mention], end: usize) -> Option<usize> {
375    mentions
376        .iter()
377        .filter(|mention| mention.start >= end)
378        .min_by_key(|mention| mention.start)
379        .map(|mention| mention.entity)
380}
381
382/// How many characters of `chars` from `at` spell `words` (lower case) as whole words, with any
383/// run of whitespace between them.
384fn match_at(chars: &[(usize, char)], at: usize, words: &[String]) -> Option<usize> {
385    if at > 0 && chars.get(at - 1).is_some_and(|(_, c)| c.is_alphanumeric()) {
386        return None;
387    }
388    let mut index = at;
389    for (number, word) in words.iter().enumerate() {
390        if number > 0 {
391            let spaces_from = index;
392            while chars.get(index).is_some_and(|(_, c)| c.is_whitespace()) {
393                index += 1;
394            }
395            if index == spaces_from {
396                return None;
397            }
398        }
399        for expected in word.chars() {
400            let (_, written) = chars.get(index)?;
401            if written.to_lowercase().ne(expected.to_lowercase()) {
402                return None;
403            }
404            index += 1;
405        }
406    }
407    if chars.get(index).is_some_and(|(_, c)| c.is_alphanumeric()) {
408        return None;
409    }
410    Some(index - at)
411}
412
413/// `text` with the mentioned labels turned into spaces, byte for byte, so offsets stay.
414fn blank(text: &str, mentions: &[Mention]) -> String {
415    text.char_indices()
416        .map(|(at, c)| {
417            if mentions.iter().any(|mention| at >= mention.start && at < mention.end) {
418                " ".repeat(c.len_utf8())
419            } else {
420                c.to_string()
421            }
422        })
423        .collect()
424}
425
426/// The clauses of a sentence around a figure.
427struct Clause {
428    start: usize,
429    end: usize,
430    /// Where the first joining word after the figure starts ("while", "but"), else the end of
431    /// the sentence: what comes after it is another statement.
432    next_statement: usize,
433}
434
435/// The clause around `at`, inside the sentence `sentence_start..sentence_end`. A comma or a
436/// word inside a label ("Buy One, Get One") ends no clause.
437fn clause_span(text: &str, sentence_start: usize, sentence_end: usize, at: usize, mentions: &[Mention]) -> Clause {
438    let sentence = text.get(sentence_start..sentence_end).unwrap_or_default();
439    // Each break: its span in the sentence and whether it is a joining word.
440    let mut breaks: Vec<(usize, usize, bool)> = Vec::new();
441    let chars: Vec<(usize, char)> = sentence.char_indices().collect();
442    for (position, &(offset, c)) in chars.iter().enumerate() {
443        let next_is_space = chars.get(position + 1).is_some_and(|(_, next)| next.is_whitespace());
444        let previous_is_space = position > 0 && chars.get(position - 1).is_some_and(|(_, prev)| prev.is_whitespace());
445        let cuts = match c {
446            ',' | ';' => next_is_space,
447            '(' | ')' | '[' | ']' => true,
448            '-' | '\u{2013}' | '\u{2014}' => next_is_space && previous_is_space,
449            _ => false,
450        };
451        if cuts {
452            breaks.push((offset, offset + c.len_utf8(), false));
453        }
454    }
455    let mut word_start = None;
456    for (position, &(offset, c)) in chars.iter().enumerate() {
457        if c.is_alphabetic() {
458            word_start.get_or_insert(offset);
459            let ends = chars.get(position + 1).is_none_or(|(_, next)| !next.is_alphabetic());
460            if let (true, Some(from)) = (ends, word_start) {
461                let to = offset + c.len_utf8();
462                let word = sentence.get(from..to).unwrap_or_default().to_lowercase();
463                if JOINERS.contains(&word.as_str()) {
464                    breaks.push((from, to, true));
465                }
466                word_start = None;
467            }
468        } else {
469            word_start = None;
470        }
471    }
472    breaks.retain(|(from, to, _)| {
473        let (from, to) = (sentence_start + from, sentence_start + to);
474        !mentions.iter().any(|mention| from < mention.end && to > mention.start)
475    });
476    let at = at.saturating_sub(sentence_start);
477    let start = breaks.iter().filter(|(_, end, _)| *end <= at).map(|(_, end, _)| *end).max().unwrap_or(0);
478    let end =
479        breaks.iter().filter(|(from, _, _)| *from >= at).map(|(from, _, _)| *from).min().unwrap_or(sentence.len());
480    let next_statement = breaks
481        .iter()
482        .filter(|(from, _, joiner)| *joiner && *from >= at)
483        .map(|(from, _, _)| *from)
484        .min()
485        .unwrap_or(sentence.len());
486    Clause { start: sentence_start + start, end: sentence_start + end, next_statement: sentence_start + next_statement }
487}
488
489fn is_a_year(value: f64) -> bool {
490    (1900.0..=2100.0).contains(&value) && value.fract() == 0.0
491}
492
493fn kind(value: &serde_json::Value) -> &'static str {
494    match value {
495        serde_json::Value::Null => "null",
496        serde_json::Value::Bool(_) => "a bool",
497        serde_json::Value::Number(_) => "a number",
498        serde_json::Value::String(_) => "a string",
499        serde_json::Value::Array(_) => "a list",
500        serde_json::Value::Object(_) => "an object",
501    }
502}
503
504#[cfg(test)]
505#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
506mod tests {
507    use serde_json::json;
508
509    use super::*;
510    use crate::grounding::figures::Tolerance;
511
512    fn rules() -> AttributionRules {
513        AttributionRules {
514            numbers: NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true },
515            integers_up_to: 10.0,
516        }
517    }
518
519    /// A shop with three product categories and the whole store as a group with facts.
520    fn shop() -> Entities {
521        let mut entities = Entities::new();
522        entities
523            .add_json(
524                &json!([
525                    {"entity": "Electronics", "aliases": ["gadgets"], "revenue": 48200, "share": 0.3125, "orders": 1240, "growth_pct": 12.4},
526                    {"entity": "Garden Tools", "aliases": ["garden"], "revenue": 21900, "share": 0.1419, "orders": 615, "growth_pct": -3.8},
527                    {"entity": "Toys", "revenue": 15350, "share": 0.0995, "orders": 702, "growth_pct": 7.1},
528                    {"entity": "All categories", "aliases": ["the store", "overall"], "group": true, "revenue": 154250, "orders": 4310}
529                ]),
530                "entity",
531            )
532            .unwrap();
533        entities.add_group("categories");
534        entities
535    }
536
537    fn found(text: &str, scope: Option<&str>) -> Vec<(String, String, Vec<String>)> {
538        shop()
539            .misattributed(text, scope, rules())
540            .into_iter()
541            .map(|wrong| (wrong.number, wrong.named, wrong.owners))
542            .collect()
543    }
544
545    #[test]
546    fn true_attributions_pass() {
547        let report = "Electronics led with $48.2k in revenue (31.25% of sales) on 1,240 orders. \
548                      Garden Tools fell 3.8% to 21,900, while Toys grew 7.1% to 15,350. \
549                      31% of revenue came from gadgets, 14% from garden. \
550                      Across all categories the store took 154,250 on 4,310 orders.";
551        assert_eq!(found(report, None), []);
552    }
553
554    #[test]
555    fn a_figure_of_another_entity_is_caught() {
556        assert_eq!(
557            found("Toys reached 31.25% of sales.", None),
558            [("31.25%".to_owned(), "Toys".to_owned(), vec!["Electronics".to_owned()])]
559        );
560        // An alias names its entity.
561        assert_eq!(found("Gadgets took 702 orders.", None)[0].2, ["Toys"]);
562    }
563
564    #[test]
565    fn swapped_entities_are_caught() {
566        let wrong = found("Electronics grew 7.1% and Toys grew 12.4%.", None);
567        assert_eq!(wrong.len(), 2);
568        assert_eq!((wrong[0].1.as_str(), wrong[1].1.as_str()), ("Electronics", "Toys"));
569    }
570
571    #[test]
572    fn a_swapped_metric_is_not_a_misattribution_of_the_entity() {
573        // The figure is the entity's own, under another metric: the attribution holds. The
574        // numbers check does not judge metrics either, so this is out of scope.
575        assert_eq!(found("Toys had 702 in revenue.", None), []);
576    }
577
578    #[test]
579    fn a_figure_of_another_entity_under_another_metric_is_caught() {
580        // 1,240 is the orders of Electronics: written as the revenue of Garden Tools.
581        assert_eq!(found("Garden Tools revenue was 1,240.", None)[0].2, ["Electronics"]);
582    }
583
584    #[test]
585    fn the_longest_label_wins_and_whole_words_only() {
586        let mut entities = Entities::new();
587        entities.add("Garden", &[], false, &json!({"revenue": 500}));
588        entities.add("Garden Tools", &[], false, &json!({"revenue": 21900}));
589        entities.add("Store 12", &[], false, &json!({"revenue": 777}));
590        assert!(entities.misattributed("Garden  tools made 21,900.", None, rules()).is_empty());
591        assert_eq!(entities.misattributed("Garden made 21,900.", None, rules()).len(), 1);
592        // "Gardens" is not "Garden", and the 12 of "Store 12" is not a figure.
593        assert!(entities.misattributed("Gardens made 21,900. Store 12 made 777.", None, rules()).is_empty());
594    }
595
596    #[test]
597    fn a_group_word_lets_the_named_entity_or_the_scope_decide() {
598        // The category the sentence names decides, wherever the group word stands.
599        assert_eq!(found("Among categories, Electronics took 48,200.", None), []);
600        assert_eq!(found("Among categories, Toys took 48,200.", None)[0].1, "Toys");
601        // A group word with no facts and no named entity: the scope decides, else it passes.
602        assert_eq!(found("These categories took 48,200.", Some("Electronics")), []);
603        assert_eq!(found("These categories took 48,200.", None), []);
604        // A group with facts must hold the figure when nothing else is named.
605        assert_eq!(found("The store took 154,250 on 4,310 orders.", None), []);
606        assert_eq!(found("Overall revenue was 48,200.", None)[0].1, "All categories");
607    }
608
609    #[test]
610    fn the_scope_is_the_entity_of_a_field_that_names_none() {
611        assert_eq!(found("Revenue grew 12.4% on 1,240 orders.", Some("Electronics")), []);
612        assert_eq!(found("Revenue grew 12.4% on 1,240 orders.", Some("Toys")).len(), 2);
613        // A sentence that names an entity is not about the scope.
614        assert_eq!(found("Toys grew 7.1%.", Some("Electronics")), []);
615        // An entity no source lists holds nothing.
616        assert_eq!(found("Revenue was 15,350.", Some("Books"))[0].1, "Books");
617    }
618
619    #[test]
620    fn small_counts_years_and_unowned_figures_are_not_judged() {
621        assert_eq!(found("In 2026 Toys opened 4 stores and earned 99,999.", None), []);
622        let mut entities = shop();
623        entities.add("Books", &[], false, &json!({"stores": 3, "opened": 2025}));
624        assert!(entities.misattributed("Toys opened 3 stores in 2025.", None, rules()).is_empty());
625        let loose = AttributionRules { integers_up_to: 0.0, ..rules() };
626        assert_eq!(entities.misattributed("Toys opened 3 stores.", None, loose)[0].owners, ["Books"]);
627    }
628
629    #[test]
630    fn clauses_bound_the_nearest_entity() {
631        // 14% is in the clause of "garden", although "gadgets" stands closer before it.
632        assert_eq!(found("31% of revenue came from gadgets, 14% from garden.", None), []);
633        assert_eq!(found("14% of revenue came from gadgets, 31% from garden.", None).len(), 2);
634        assert_eq!(found("Electronics revenue is 48,200 whereas Toys 21,900.", None)[0].1, "Toys");
635        // A clause that continues the sentence is about the entity before it, not a phrase after.
636        let mut entities = shop();
637        entities.add("New Buyers", &[], false, &json!({"share": 0.2}));
638        let text = "Orders came from Toys, which took 15,350 with 3 new buyers.";
639        assert!(entities.misattributed(text, None, rules()).is_empty());
640        assert_eq!(found("Electronics led, ahead of Toys with 48,200.", None)[0].1, "Toys");
641    }
642
643    #[test]
644    fn a_comma_inside_a_label_ends_no_clause() {
645        let mut offers = Entities::new();
646        offers.add("Buy One, Get One", &[], false, &json!({"share": 0.1277}));
647        offers.add("Get One", &[], false, &json!({"share": 0.617}));
648        offers.add("Flat 20 Off", &[], false, &json!({"share": 0.0426}));
649        let text = "Get One led with 61.70%, followed by Buy One, Get One at 12.77% and Flat 20 Off at 4.26%.";
650        assert!(offers.misattributed(text, None, rules()).is_empty());
651        let swapped = "Get One led with 12.77%, followed by Buy One, Get One at 61.70%.";
652        assert_eq!(offers.misattributed(swapped, None, rules()).len(), 2);
653    }
654
655    #[test]
656    fn figures_after_a_list_of_entities_go_to_them_in_order() {
657        assert_eq!(found("Electronics and Toys followed at 31.25% and 9.95%.", None), []);
658        assert_eq!(found("Toys and Electronics followed at 31.25% and 9.95%.", None), []);
659        // Interleaved, each figure is next to its entity.
660        assert_eq!(found("Electronics at 9.95% and Toys at 31.25%.", None).len(), 2);
661        // A list that does not hold the figure is still caught.
662        assert_eq!(found("Garden Tools and Toys followed at 31.25%.", None).len(), 1);
663    }
664
665    #[test]
666    fn a_joining_word_ends_the_search_ahead() {
667        // Nothing named before the figure, and the entity ahead is in another statement.
668        assert_eq!(found("Revenue rose 31.25%, while Toys fell.", None), []);
669        assert_eq!(found("Revenue rose 31.25% for Toys.", None).len(), 1);
670    }
671
672    #[test]
673    fn rows_and_objects_make_entities() {
674        let mut rows = Entities::new();
675        rows.add_json(
676            &json!([
677                {"entity": "North", "metric": "revenue", "value": 5100},
678                {"entity": "north", "metric": "visits", "value": 830},
679                {"entity": "South", "metric": "revenue", "value": 4400},
680                {"entity": null, "metric": "revenue", "value": 1}
681            ]),
682            "entity",
683        )
684        .unwrap();
685        assert!(rows.misattributed("North had 830 visits and 5,100 in revenue.", None, rules()).is_empty());
686        assert_eq!(rows.misattributed("South had 830 visits.", None, rules())[0].owners, ["North"]);
687
688        let mut per_label = Entities::new();
689        per_label.add_json(&json!({"North": {"revenue": 5100}, "South": {"revenue": 4400}}), "entity").unwrap();
690        assert_eq!(per_label.misattributed("North made 4,400.", None, rules())[0].named, "North");
691
692        let mut named = Entities::new();
693        named.add_json(&json!([{"name": "East", "revenue": 3000}]), "name").unwrap();
694        assert!(named.misattributed("East made 3,000.", None, rules()).is_empty());
695    }
696
697    #[test]
698    fn malformed_entities_are_reported() {
699        let mut entities = Entities::new();
700        assert!(entities.add_json(&json!("Garden"), "entity").unwrap_err().contains("a string"));
701        assert!(entities.add_json(&json!([1]), "entity").unwrap_err().starts_with("item 0"));
702        assert!(entities.add_json(&json!([{"entity": 5}]), "entity").unwrap_err().contains("must be a string"));
703        assert!(entities.add_json(&json!([{"entity": "A", "aliases": "a"}]), "entity").is_err());
704        assert!(entities.add_json(&json!([{"entity": "A", "group": "yes"}]), "entity").is_err());
705    }
706
707    #[test]
708    fn unicode_and_multibyte_text_keeps_its_offsets() {
709        let mut entities = Entities::new();
710        entities.add("Café Düsseldorf", &[], false, &json!({"revenue": 5100}));
711        entities.add("Été", &[], false, &json!({"revenue": 4400}));
712        assert!(entities.misattributed("Café  düsseldorf — 5.100 € — été 4.400 €.", None, rules()).is_empty());
713        assert_eq!(entities.misattributed("ÉTÉ réalise 5.100 €.", None, rules())[0].named, "Été");
714    }
715}