From 92b9727173ec910b1fae7e8b470b0f9be65778f6 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Tue, 24 Nov 2026 18:12:04 -0800 Subject: [PATCH 1/3] Fix narrowing for concatenated alternations Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CONTRIBUTING.md | 4 +- Cargo.lock | 4 +- Cargo.toml | 2 +- README.md | 3 + fuzz/Cargo.lock | 2 +- tgrep-cli/src/search.rs | 4 + tgrep-cli/tests/ripgrep_compat.rs | 50 ++++++++++ tgrep-core/src/query.rs | 157 ++++++++++++++++++++++++++++-- 8 files changed, 211 insertions(+), 15 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 25372612..3ba5da0b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,10 +36,10 @@ cargo build --release After the version bump is merged and CI passes, open **Actions > Release > Run workflow**, select **main**, and enter the tag matching the workspace -version in `Cargo.toml`, for example `v1.2.8`. The equivalent CLI command is: +version in `Cargo.toml`, for example `v1.2.9`. The equivalent CLI command is: ```bash -gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.8 +gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.9 ``` The workflow validates the version, creates a missing tag at the exact commit diff --git a/Cargo.lock b/Cargo.lock index eb7eddca..488acfac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1360,7 +1360,7 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "tgrep-cli" -version = "1.2.8" +version = "1.2.9" dependencies = [ "anyhow", "assert_cmd", @@ -1389,7 +1389,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.8" +version = "1.2.9" dependencies = [ "anyhow", "blake3", diff --git a/Cargo.toml b/Cargo.toml index 23d1f468..f516b411 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ exclude = ["vendor/ignore"] resolver = "2" [workspace.package] -version = "1.2.8" +version = "1.2.9" edition = "2024" rust-version = "1.88" license = "MIT" diff --git a/README.md b/README.md index a9e4aa9e..78265fd9 100644 --- a/README.md +++ b/README.md @@ -816,6 +816,9 @@ exit code determined by the search alone. Suppress the message with trigrams in parallel. Sorted postings map trigrams to candidate files. 2. **Querying** decomposes regex literals into trigram lookups, intersects or unions posting lists, and verifies candidates with the full regex engine. + Concatenations retain alternation constraints: `React\.(useImperativeHandle|useReducer)` + intersects the prefix's candidates with the union of the branches' candidates, + without expanding combinations of multiple alternations. Inline case flags participate in planning; unsupported constructs use conservative plans rather than excluding possible matches. Case-insensitive fixed strings use the same Unicode-aware planning after escaping regex diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index b6b39534..535f22b8 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -770,7 +770,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.8" +version = "1.2.9" dependencies = [ "anyhow", "blake3", diff --git a/tgrep-cli/src/search.rs b/tgrep-cli/src/search.rs index 48330a9a..30f99aa8 100644 --- a/tgrep-cli/src/search.rs +++ b/tgrep-cli/src/search.rs @@ -3047,6 +3047,10 @@ fn index_narrowing_note(raw: u64, total: u64) -> &'static str { pub(crate) fn plan_summary(plan: &QueryPlan) -> String { match plan { QueryPlan::And(queries) => format!("AND({} trigrams)", queries.len()), + QueryPlan::All(plans) => { + let subs: Vec = plans.iter().map(plan_summary).collect(); + format!("ALL({})", subs.join(", ")) + } QueryPlan::Or(plans) => { let subs: Vec = plans.iter().map(plan_summary).collect(); format!("OR({})", subs.join(", ")) diff --git a/tgrep-cli/tests/ripgrep_compat.rs b/tgrep-cli/tests/ripgrep_compat.rs index 28277818..6ba1ca44 100644 --- a/tgrep-cli/tests/ripgrep_compat.rs +++ b/tgrep-cli/tests/ripgrep_compat.rs @@ -1778,6 +1778,56 @@ fn indexed_json_keeps_line_terminators_and_raw_invalid_utf8() { }); } +#[test] +fn indexed_concatenated_alternations_keep_candidates_selective() { + let dir = TempDir::new().unwrap(); + let root = dir.path().join("testdata"); + fs::create_dir_all(&root).unwrap(); + for (name, content) in [ + ("imperative.txt", "React.useImperativeHandle\n"), + ("reducer.txt", "React.useReducer\n"), + ("other.txt", "Other.useReducer\n"), + ] { + fs::write(root.join(name), content).unwrap(); + } + for i in 0..256 { + fs::write(root.join(format!("decoy-{i}.txt")), "React.useState\n").unwrap(); + } + let cases: &[(&[&str], &str)] = &[ + (&[], r"React\.(useImperativeHandle|useReducer)"), + (&[], r"React.(useImperativeHandle|useReducer)"), + (&[], r"React\.useImperativeHandle|React\.useReducer"), + (&["-i"], r"react\.(useimperativehandle|usereducer)"), + (&["-P"], r"React\.(useImperativeHandle|useReducer)"), + (&["-P"], r"(?), + /// Every child plan must match (intersection of candidate sets). + All(Vec), /// Any branch can match (union of results). Or(Vec), /// No trigrams could be extracted — must scan all files. @@ -451,6 +453,7 @@ fn decompose_hir(hir: &Hir) -> QueryPlan { HirKind::Literal(Literal(bytes)) => literals_to_query_plan(bytes), HirKind::Concat(subs) => { let mut all_queries = Vec::new(); + let mut plans = Vec::new(); let mut current_literal = Vec::new(); let mut fold_run = false; let flush = @@ -477,21 +480,23 @@ fn decompose_hir(hir: &Hir) -> QueryPlan { fold_run = true; } else { flush(&mut current_literal, &mut fold_run, &mut all_queries); - // Recurse into the non-literal child - let sub_plan = decompose_hir(sub); - if let QueryPlan::And(queries) = sub_plan { - all_queries.extend(queries); + match decompose_hir(sub) { + QueryPlan::And(queries) => all_queries.extend(queries), + QueryPlan::MatchAll => {} + plan => plans.push(plan), } - // MatchAll or Or children don't contribute AND trigrams } } flush(&mut current_literal, &mut fold_run, &mut all_queries); - if all_queries.is_empty() { - QueryPlan::MatchAll - } else { - QueryPlan::And(all_queries) + if !all_queries.is_empty() { + plans.push(QueryPlan::And(all_queries)); + } + match plans.len() { + 0 => QueryPlan::MatchAll, + 1 => plans.pop().unwrap(), + _ => QueryPlan::All(plans), } } HirKind::Alternation(alts) => { @@ -544,6 +549,21 @@ fn simplify(plan: QueryPlan) -> QueryPlan { QueryPlan::And(queries) } } + QueryPlan::All(plans) => { + let mut simplified = Vec::new(); + for plan in plans.into_iter().map(simplify) { + match plan { + QueryPlan::MatchAll => {} + QueryPlan::All(children) => simplified.extend(children), + plan => simplified.push(plan), + } + } + match simplified.len() { + 0 => QueryPlan::MatchAll, + 1 => simplified.pop().unwrap(), + _ => QueryPlan::All(simplified), + } + } QueryPlan::Or(plans) => { let simplified: Vec = plans.into_iter().map(simplify).collect(); if simplified.len() == 1 { @@ -583,6 +603,9 @@ where } result } + QueryPlan::All(plans) => { + intersect_many_sorted(plans.iter().map(|sub| execute_plan(sub, lookup))) + } QueryPlan::Or(plans) => { let lists = plans.iter().map(|sub| execute_plan(sub, lookup)).collect(); union_many_sorted(lists) @@ -662,6 +685,9 @@ where candidates.into_iter().map(|(fid, _, _)| fid).collect() } + QueryPlan::All(plans) => { + intersect_many_sorted(plans.iter().map(|sub| execute_plan_with_masks(sub, lookup))) + } QueryPlan::Or(plans) => { let lists = plans .iter() @@ -673,6 +699,21 @@ where } } +fn intersect_many_sorted(lists: impl IntoIterator>) -> Vec { + let mut lists = lists.into_iter(); + let Some(mut result) = lists.next() else { + return Vec::new(); + }; + // Stop before evaluating another child if the conjunction is already empty. + while !result.is_empty() { + let Some(list) = lists.next() else { + break; + }; + result = intersect_sorted(&result, &list); + } + result +} + fn intersect_sorted(a: &[u32], b: &[u32]) -> Vec { let mut result = Vec::new(); let (mut i, mut j) = (0, 0); @@ -1031,6 +1072,104 @@ mod tests { } } + #[test] + fn concatenated_alternations_narrow_candidates() { + let contents = [ + "React.useImperativeHandle", + "React.useReducer", + "React.useState", + "Other.useReducer", + "React.useReducer.tail", + "React.useImperativeHandle.end", + "React.useState.tail", + "React.x", + "React.", + "React.\u{212a}elvin", + "React.KELVIN", + ]; + let mut inverted = std::collections::HashMap::>::new(); + for (file_id, content) in contents.iter().enumerate() { + for (tri, masks) in trigram::extract_merged_masks(content.as_bytes()) { + inverted.entry(tri).or_default().push(PostingEntry { + file_id: file_id as u32, + loc_mask: masks.loc_mask, + next_mask: masks.next_mask, + }); + } + } + let lookup = |tri| inverted.get(&tri).cloned().unwrap_or_default(); + let cases: &[(&str, &[u32])] = &[ + (r"React\.(useImperativeHandle|useReducer)", &[0, 1, 4, 5]), + (r"React.(useImperativeHandle|useReducer)", &[0, 1, 4, 5]), + (r"(useImperativeHandle|useReducer).*React\.", &[0, 1, 4, 5]), + (r"(useImperativeHandle|useReducer).*(tail|end)", &[4, 5]), + (r"(React\.useImperativeHandle|Other\.useReducer).*tail", &[]), + ( + r"(React\.(useImperativeHandle|useReducer)|Other).*tail", + &[4], + ), + ( + r"React\.(useImperativeHandle|useReducer)\.(tail|end)", + &[4, 5], + ), + (r"React\.(useImperativeHandle|useReducer)+", &[0, 1, 4, 5]), + ( + r"React\.(useImperativeHandle|useReducer)?", + &[0, 1, 2, 4, 5, 6, 7, 8, 9, 10], + ), + ( + r"React\.(useImperativeHandle|x)", + &[0, 1, 2, 4, 5, 6, 7, 8, 9, 10], + ), + (r"React\.(useImperativeHandle|(?i:kelvin))", &[0, 5, 9, 10]), + ]; + for &(pattern, expected) in cases { + let plan = build_query_plan(pattern, false).unwrap(); + assert!(!plan.is_match_all(), "{pattern}: {plan:?}"); + for candidates in [ + execute_plan(&plan, &|tri| { + lookup(tri).iter().map(|entry| entry.file_id).collect() + }), + execute_plan_with_masks(&plan, &lookup), + ] { + assert_eq!(candidates, expected, "{pattern}: {plan:?}"); + let matcher = regex::Regex::new(pattern).unwrap(); + for (id, content) in contents.iter().enumerate() { + if matcher.is_match(content) { + assert!( + candidates.contains(&(id as u32)), + "{pattern} lost {content:?}" + ); + } + } + } + } + } + + #[test] + fn many_concatenated_alternations_keep_planning_and_lookup_linear() { + let plan = build_query_plan(&"(alpha|omega)".repeat(32), false).unwrap(); + assert!(!plan.is_match_all()); + let lookups = std::cell::Cell::new(0); + let lookup = |_| { + lookups.set(lookups.get() + 1); + assert!(lookups.get() <= 256, "alternations must not be distributed"); + vec![PostingEntry { + file_id: 7, + loc_mask: u8::MAX, + next_mask: u8::MAX, + }] + }; + assert_eq!( + execute_plan(&plan, &|tri| { + lookup(tri).iter().map(|entry| entry.file_id).collect() + }), + vec![7] + ); + lookups.set(0); + assert_eq!(execute_plan_with_masks(&plan, &lookup), vec![7]); + } + #[test] fn test_short_pattern() { let plan = build_query_plan("ab", false).unwrap(); From 018bd948d1d3271de4cd92ec02763e8a3211ff07 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Tue, 24 Nov 2026 18:20:20 -0800 Subject: [PATCH 2/3] Short-circuit alternation lookups on literal misses Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tgrep-core/src/query.rs | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/tgrep-core/src/query.rs b/tgrep-core/src/query.rs index c5fd1727..df57444c 100644 --- a/tgrep-core/src/query.rs +++ b/tgrep-core/src/query.rs @@ -491,7 +491,9 @@ fn decompose_hir(hir: &Hir) -> QueryPlan { flush(&mut current_literal, &mut fold_run, &mut all_queries); if !all_queries.is_empty() { - plans.push(QueryPlan::And(all_queries)); + // Check literal constraints first so an empty posting set can + // skip materializing potentially common alternation branches. + plans.insert(0, QueryPlan::And(all_queries)); } match plans.len() { 0 => QueryPlan::MatchAll, @@ -1146,6 +1148,38 @@ mod tests { } } + #[test] + fn concatenated_alternation_skips_branch_lookups_after_literal_miss() { + let plan = build_query_plan("QZX(the|and)", false).unwrap(); + let QueryPlan::All(plans) = &plan else { + panic!("expected conjunction plan: {plan:?}"); + }; + let QueryPlan::And(literals) = &plans[0] else { + panic!("expected literal constraints first: {plan:?}"); + }; + let literal_hashes: Vec<_> = literals.iter().map(|query| query.hash).collect(); + + let calls = std::cell::RefCell::new(Vec::new()); + assert!( + execute_plan(&plan, &|tri| { + calls.borrow_mut().push(tri); + Vec::new() + }) + .is_empty() + ); + assert_eq!(*calls.borrow(), literal_hashes); + + calls.borrow_mut().clear(); + assert!( + execute_plan_with_masks(&plan, &|tri| { + calls.borrow_mut().push(tri); + Vec::new() + }) + .is_empty() + ); + assert_eq!(*calls.borrow(), literal_hashes); + } + #[test] fn many_concatenated_alternations_keep_planning_and_lookup_linear() { let plan = build_query_plan(&"(alpha|omega)".repeat(32), false).unwrap(); From 9578d598e6fb8d4420e7d42a0920ce9f0466d402 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Tue, 24 Nov 2026 22:40:13 -0800 Subject: [PATCH 3/3] Prioritize literals in nested query plans Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tgrep-core/src/query.rs | 57 ++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/tgrep-core/src/query.rs b/tgrep-core/src/query.rs index df57444c..33ab575a 100644 --- a/tgrep-core/src/query.rs +++ b/tgrep-core/src/query.rs @@ -560,6 +560,9 @@ fn simplify(plan: QueryPlan) -> QueryPlan { plan => simplified.push(plan), } } + // Nested captures can introduce a mandatory literal after an + // alternation; keep selective posting intersections first. + simplified.sort_by_key(|plan| !matches!(plan, QueryPlan::And(_))); match simplified.len() { 0 => QueryPlan::MatchAll, 1 => simplified.pop().unwrap(), @@ -1150,34 +1153,36 @@ mod tests { #[test] fn concatenated_alternation_skips_branch_lookups_after_literal_miss() { - let plan = build_query_plan("QZX(the|and)", false).unwrap(); - let QueryPlan::All(plans) = &plan else { - panic!("expected conjunction plan: {plan:?}"); - }; - let QueryPlan::And(literals) = &plans[0] else { - panic!("expected literal constraints first: {plan:?}"); - }; - let literal_hashes: Vec<_> = literals.iter().map(|query| query.hash).collect(); + for pattern in ["QZX(the|and)", "(the|and)(QZX(foo|bar))"] { + let plan = build_query_plan(pattern, false).unwrap(); + let QueryPlan::All(plans) = &plan else { + panic!("expected conjunction plan for {pattern}: {plan:?}"); + }; + let QueryPlan::And(literals) = &plans[0] else { + panic!("expected literal constraints first for {pattern}: {plan:?}"); + }; + let literal_hashes: Vec<_> = literals.iter().map(|query| query.hash).collect(); - let calls = std::cell::RefCell::new(Vec::new()); - assert!( - execute_plan(&plan, &|tri| { - calls.borrow_mut().push(tri); - Vec::new() - }) - .is_empty() - ); - assert_eq!(*calls.borrow(), literal_hashes); + let calls = std::cell::RefCell::new(Vec::new()); + assert!( + execute_plan(&plan, &|tri| { + calls.borrow_mut().push(tri); + Vec::new() + }) + .is_empty() + ); + assert_eq!(*calls.borrow(), literal_hashes, "{pattern}: {plan:?}"); - calls.borrow_mut().clear(); - assert!( - execute_plan_with_masks(&plan, &|tri| { - calls.borrow_mut().push(tri); - Vec::new() - }) - .is_empty() - ); - assert_eq!(*calls.borrow(), literal_hashes); + calls.borrow_mut().clear(); + assert!( + execute_plan_with_masks(&plan, &|tri| { + calls.borrow_mut().push(tri); + Vec::new() + }) + .is_empty() + ); + assert_eq!(*calls.borrow(), literal_hashes, "{pattern}: {plan:?}"); + } } #[test]