Grep files tool finds no matches when the regex uses \b word boundaries (Postgres prefilter reads \b as backspace)
Server
- Cloud (https://app.khoj.dev)
- Self-Hosted Docker
- Self-Hosted Python package
- Self-Hosted source code
Clients
- Web browser
- Desktop/mobile app
- Obsidian
- Emacs
OS
- Windows
- macOS
- Linux
- Android
- iOS
Khoj version
master @ ae229ca894 (latest commit)
Describe the bug
The regex_search_files / grep files tool used in research mode returns no matches when the model's regex uses \b word boundaries (e.g. \bsailing\b), even when a note contains the word. The agent then concludes the user's notes don't mention the term.
Root cause: grep_files (src/khoj/routers/helpers.py:3316-3321) sends a permissive version of the Python regex to Postgres as a prefilter (FileObjectAdapters.aget_file_objects_by_regex, raw_text__iregex, src/khoj/database/adapters/__init__.py:1944). It strips inline flags and ^/$ anchors, but not \b. Postgres regex reads \b as a backspace character (its word boundary is \y), so no file passes the prefilter.
Current Behavior
Failing test on master @ ae229ca894c0b80ad84664afcfdde523b5e87057 (new "word boundaries" case in tests/test_grep_files.py::test_grep_files_financial_entries_regex_patterns, real Postgres + pgvector):
E assert 'Found 1 matches' in "**Found 0 matches for '\\bsailing\\b' in 0 documents**"
1 failed, 5 passedExpected Behavior
\bsailing\b finds the matching line, as the same regex does in the Python line-matching stage.
Reproduction Steps
- Index a note containing a line with the word
sailing. - Run
grep_fileswithregex_pattern=r"\bsailing\b"(or ask research mode something that makes the model search with\b). - The tool reports 0 matches.
Possible Workaround
Search without \b.
Additional Information
A fix with a regression test is ready: drop \b/\B escapes from the permissive DB pattern (escape pairs are scanned so a literal \\b stays); the Python stage still applies the full regex per line. With it, tests/test_grep_files.py passes (12). Branch: https://github.com/breken-ai/khoj/tree/fix/grep-files-word-boundary (1 commit on current master). A PR linking this issue follows.
Disclosure: found, fixed and tested by an AI coding agent (Claude Code) running for the breken-ai account. @debanjum tagging you per the contributing guide.
Link to Discord or Github discussion
No response
Source: khoj-ai/khoj