rules: skip regex engine for pure-literal /i patterns using a pre-built lowercased-string set#2927
rules: skip regex engine for pure-literal /i patterns using a pre-built lowercased-string set#2927devs6186 wants to merge 3 commits intomandiant:masterfrom
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a significant performance optimization for Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a performance optimization for case-insensitive pure-literal regex patterns by using a pre-computed set for O(1) lookups, avoiding the regex engine in many common cases. The implementation is sound, with a fallback to the existing regex evaluation to ensure correctness for substring matches. The addition of break statements in the matching loop is also a good improvement. The new tests adequately cover the changes. I have one suggestion to improve code conciseness.
| if value.endswith("/i") and re.escape(pat) == pat: | ||
| self._is_pure_literal_ci: bool = True | ||
| self._normalized_lower: str = pat.lower() | ||
| else: | ||
| self._is_pure_literal_ci = False | ||
| self._normalized_lower = "" |
There was a problem hiding this comment.
This logic can be made more concise and Pythonic by using a conditional expression. This also resolves the minor inconsistency of having type hints only in the if branch.
self._is_pure_literal_ci: bool = value.endswith("/i") and re.escape(pat) == pat
self._normalized_lower: str = pat.lower() if self._is_pure_literal_ci else ""|
likewise, i think this is a fair idea, but the hard work is proving how this works against a real-world dataset. while we're reducing the overhead of matching some strings in some cases, this is probably a rare occurrence, and therefore the additional overhead that we introduce here might actually reduce performance. i'm just not sure, so i'd like to see the data. for a benchmark, i'd want to see how capa wallclock time changes when run against a whole bunch of samples (like capa-testfiles repo) before/after this PR. also, i'd encourage you to try a profiler (or two), like py-spy etc., to see how the CPU/memory behavior changes. |
…ased string fast path For Regex patterns that are pure literals with the /i flag (no metacharacters), add an O(1) pre-check using a frozenset of lowercased string values built once per scope evaluation. When the lowercased pattern is found in the set the rule is added to candidates without invoking the regex engine. When not found the full regex scan still runs to handle substring matches such as /createfile/i matching "CreateFileA". Adds _is_pure_literal_ci and _normalized_lower attrs to Regex and two tests to verify detection and correctness. Closes: mandiant#2129
…ased string fast path Closes mandiant#2129
- simplify pure-literal /i detection assignment in Regex - build lowercased string set lazily to avoid unnecessary overhead - keep regex fallback path to preserve substring semantics mandiant#2129
33713c3 to
8bf8736
Compare
|
Thanks @williballenthin for pushing on the data question , I agree this change should be justified empirically, so I went I also addressed the bot feedback and cleaned up the implementation:
Benchmark setup
Wallclock results (paired successful samples)
Correctness parity For the 7 successful paired samples, I compared base vs PR JSON outputs after canonicalization:
Profiling notes I attempted py-spy, but this Windows environment consistently returned Failed to find python version from Representative single-sample cProfile (same ELF sample on both commits):
So the matching-path cost in this sample is essentially flat; runtime movement is elsewhere in the pipeline Memory sampling (7 paired successful samples)
No material memory regression observed. Validation after rebase/conflict resolution
Successful paired set (7):
Excluded (3):
do let me know what you think of this? |
Summary
Closes #2129.
capa's rule matching loop currently evaluates every case-insensitive
Regexfeature (/pattern/i) by invokingre.search()against all extractedStringfeatures at each scope. For the ~400 pure-literal case-insensitive patterns in the default rule set (patterns with no metacharacters, e.g./createfile/i,/useragent/i), the regex engine is unnecessary overhead.When the binary has a string whose lowercased value equals the pattern (the common case for API names, file extensions, registry keys, etc.), we can determine candidacy in O(1) instead of O(n·regex) by checking membership in a pre-computed set of lowercased string values.
What changed
capa/features/common.pyRegex.__init__()now detects pure-literal/ipatterns (re.escape(pat) == pat) and stores two new instance attributes:_is_pure_literal_ci: booland_normalized_lower: str. Complex patterns (those with metacharacters) are unaffected.capa/rules/__init__.py—RuleSet._match()string_rulesscanning loop, afrozenset[str]of lowercased string values is built once per scope call (one pass over the already-filteredstring_featuresdict).Regexthat is a pure-literal/ipattern, the membership check_normalized_lower in lowercased_stringsshort-circuits the rule to a candidate with no regex call.evaluate()regex scan so that substring matches like/createfile/imatching"CreateFileA"are still caught correctly.breakafter a positive match in both the fast-path and normal-path branches; iterating the remainingwanted_stringsfor a rule that is already a candidate is redundant.Correctness
The fast path is a sufficient condition — if the exact lowercased pattern string is present among the extracted features,
re.searchis guaranteed to match it. If it is absent, we fall back to the full regex scan unchanged. This means there are no false negatives: every match the old code would have found is still found.Tests
Two new tests in
tests/test_match.py:test_regex_pure_literal_ci_fast_path_detection— checks that_is_pure_literal_ciand_normalized_lowerare set correctly for pure-literal vs. complex patterns.test_regex_ci_fast_path_correctness— exercises the full match path: exact CI hit (fast path), substring hit (regex fallback), and non-match, verifying identical results to the previous implementation.Test plan
pytest tests/test_match.py -v— all 25 tests passpytest tests/test_rules.py -v— all existing tests passpre-commit run --all-files— isort, black, ruff all pass