From 85e1c891912f73a5860016137192e8d4270a3ad9 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Tue, 13 Oct 2026 10:49:15 +0530 Subject: [PATCH] fix(safety): count an identifier once when two rules match it `scan` added one to a category's count for every rule match, so a value two rules both recognise was reported twice: `+1 415-555-0100` is a US-format phone number and an international one, and came back as PhoneNumber count 2 for a single identifier. Matches are now collected as byte spans per category and overlapping spans are folded into one before counting. Distinct values, including the same value written twice, still count separately. The US rule also takes its own `+1`: `\b` cannot sit between a space and a `+`, so the match began at the `1` and redaction left a stray `+` behind (`call +[redacted]`). The leading alternation lets the match start on the `+`, and the two rules now cover the same span. Closes #261 --- crates/tinymemory-api/src/safety/detector.rs | 34 +++++++++++++++-- .../src/safety/detector_tests.rs | 13 +++++++ crates/tinymemory-api/src/safety/mod_tests.rs | 37 +++++++++++++++++++ crates/tinymemory-api/src/safety/rules.rs | 7 +++- 4 files changed, 86 insertions(+), 5 deletions(-) diff --git a/crates/tinymemory-api/src/safety/detector.rs b/crates/tinymemory-api/src/safety/detector.rs index cae96f6b..0d1e2eb6 100644 --- a/crates/tinymemory-api/src/safety/detector.rs +++ b/crates/tinymemory-api/src/safety/detector.rs @@ -42,7 +42,12 @@ fn level_from_score(score: u32) -> RiskLevel { pub fn scan(content: &str) -> PiiScanResult { // BTreeMap keeps the output deterministic (categories emitted in enum // order) without a separate sort pass. - let mut counts: BTreeMap = BTreeMap::new(); + // + // Spans rather than a running count: two rules in one category can match + // the same value (`+1 415-555-0100` is both a US-format and an + // international phone number), and a count is of identifiers, not of + // rules, so overlapping spans are folded into one before they are counted. + let mut spans: BTreeMap> = BTreeMap::new(); for rule in rules() { for m in rule.regex.find_iter(content) { @@ -51,13 +56,20 @@ pub fn scan(content: &str) -> PiiScanResult { { continue; } - *counts.entry(rule.category).or_default() += 1; + spans + .entry(rule.category) + .or_default() + .push((m.start(), m.end())); } } - if counts.is_empty() { + if spans.is_empty() { return PiiScanResult::default(); } + let counts: BTreeMap = spans + .into_iter() + .map(|(category, spans)| (category, distinct_spans(spans))) + .collect(); let distinct = counts.len() as u32; let mut score: u32 = counts.keys().map(|c| c.weight()).sum(); @@ -85,6 +97,22 @@ pub fn scan(content: &str) -> PiiScanResult { } } +/// The number of distinct values among `spans`: byte ranges that overlap are +/// one value seen by more than one rule, ranges that merely touch or stand +/// apart are separate values. The same value written twice is two. +fn distinct_spans(mut spans: Vec<(usize, usize)>) -> usize { + spans.sort_unstable(); + let mut count = 0; + let mut covered_to = 0; + for (start, end) in spans { + if count == 0 || start >= covered_to { + count += 1; + } + covered_to = covered_to.max(end); + } + count +} + /// Replacement for every value [`redact_identifiers`] removes. pub const REDACTED_IDENTIFIER: &str = "[redacted]"; diff --git a/crates/tinymemory-api/src/safety/detector_tests.rs b/crates/tinymemory-api/src/safety/detector_tests.rs index c7e41bf5..2a662685 100644 --- a/crates/tinymemory-api/src/safety/detector_tests.rs +++ b/crates/tinymemory-api/src/safety/detector_tests.rs @@ -21,3 +21,16 @@ fn level_thresholds_are_monotonic() { assert_eq!(level_from_score(45), RiskLevel::High); assert_eq!(level_from_score(1000), RiskLevel::High); } + +#[test] +fn distinct_spans_folds_overlaps_and_keeps_separate_values() { + assert_eq!(distinct_spans(vec![]), 0); + assert_eq!(distinct_spans(vec![(5, 20)]), 1); + // Two rules over one value, one of them a sub-span of the other. + assert_eq!(distinct_spans(vec![(6, 20), (5, 20)]), 1); + // Partial overlap is still one value. + assert_eq!(distinct_spans(vec![(0, 10), (8, 15)]), 1); + // Touching and separate ranges are distinct values. + assert_eq!(distinct_spans(vec![(0, 10), (10, 20)]), 2); + assert_eq!(distinct_spans(vec![(30, 40), (0, 10), (12, 20)]), 3); +} diff --git a/crates/tinymemory-api/src/safety/mod_tests.rs b/crates/tinymemory-api/src/safety/mod_tests.rs index d45a9a1c..26405587 100644 --- a/crates/tinymemory-api/src/safety/mod_tests.rs +++ b/crates/tinymemory-api/src/safety/mod_tests.rs @@ -177,6 +177,43 @@ fn phone_shaped_ssn_not_double_counted_as_ssn() { assert!(!r.has_category(PiiCategory::NationalId)); } +fn count_of(r: &PiiScanResult, category: PiiCategory) -> usize { + r.hits + .iter() + .find(|hit| hit.category == category) + .map_or(0, |hit| hit.count) +} + +#[test] +fn a_value_matched_by_two_rules_counts_once() { + // `+1 415-555-0100` is both a US-format and an international phone + // number. It is one identifier, so it is one hit. + let r = scan("call +1 415-555-0100"); + assert_eq!(count_of(&r, PiiCategory::PhoneNumber), 1, "{r:?}"); + assert_eq!(r.level, RiskLevel::Low); +} + +#[test] +fn distinct_values_in_one_category_each_count() { + let r = scan("+1 415-555-0100, 415-555-0199 or +44 20 7946 0958"); + assert_eq!(count_of(&r, PiiCategory::PhoneNumber), 3, "{r:?}"); + // The same value written twice is two occurrences. + let r = scan("415-555-0100 then again 415-555-0100"); + assert_eq!(count_of(&r, PiiCategory::PhoneNumber), 2, "{r:?}"); +} + +#[test] +fn a_doubly_matched_value_is_redacted_whole() { + assert_eq!( + redact_identifiers("call +1 415-555-0100 now"), + "call [redacted] now" + ); + assert_eq!( + redact_identifiers("call +1 415.555.1234 now"), + "call [redacted] now" + ); +} + // --------------------------------------------------------------------------- // Risk-level escalation // --------------------------------------------------------------------------- diff --git a/crates/tinymemory-api/src/safety/rules.rs b/crates/tinymemory-api/src/safety/rules.rs index 6cad3122..221945ad 100644 --- a/crates/tinymemory-api/src/safety/rules.rs +++ b/crates/tinymemory-api/src/safety/rules.rs @@ -135,10 +135,13 @@ fn build_rules() -> Vec { None, ), // US-style phone number (3-3-4 groups, requires a separator so it - // doesn't swallow arbitrary 10-digit numbers). + // doesn't swallow arbitrary 10-digit numbers). A leading `+1` is part + // of the number: `\b` cannot sit between a space and the `+`, so the + // alternation lets the match start on the `+` itself and redaction + // takes the whole value rather than leaving a stray `+` behind. pattern_rule( PiiCategory::PhoneNumber, - r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b", + r"(?:\+|\b)(?:1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b", None, ), // Legacy international phone-like pattern. Its repetition counts