Repository navigation
fix(bm25): support fragment queries via sub-token expansion (v4.7.0) - #141
Conversation
BM25 tokenizer previously preserved hyphens intentionally, indexing composite tokens like `MDR-AD002` as a single token `mdr-ad002`. Fragment queries (`AD002`, `MDR`, `CS005`) silently returned NO_RESULTS even when the composite existed in the corpus. This affects every hyphenated taxonomy in typical infosec/doc corpora: MDR-*, CVE-*, ADR-*, MS17-*, MDR-Custom001-xxxx. Fix: tokenizer now emits both the composite token AND its sub-parts of length >= 2. IDF preserves exact-match ranking (composite is rarer, so it ranks above fragment matches). - mcp_server/server.py: _tokenize sub-token emission (+10 net LOC) - tests/test_bm25_tokenizer_fragment.py: 25 new tests (unit + integration + patterns from #140) - README.md: v4.7.0 CHANGELOG entry with upgrade note (reindex required) - Version bump 4.6.0 → 4.7.0 (MINOR — tokenization behavior + reindex requirement, no API break) Trade-offs: - +30-50% BM25 inverted index memory overhead (measured +32.5% on synthetic) - Requires reindex_documents(force=True) on upgrade - Zero API/config change; check_api_surface.py clean; test_backwards_compat.py green Known limitation: alphanumeric-glued tokens without separators (HARDLAB11, hash prefixes) still require exact match — char n-grams tracked as follow-up. Closes #140
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughChangesBM25 fragment matching
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant RegressionTests
participant BM25Index
participant _tokenize
RegressionTests->>BM25Index: Search a fragment or composite query
BM25Index->>_tokenize: Tokenize query and indexed text
_tokenize-->>BM25Index: Return composite and qualifying sub-tokens
BM25Index-->>RegressionTests: Return ranked matching documents
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.gitignore:
- Line 74: Update the repository ignore configuration so the root-level
branch.json and master.json artifacts generated by the quality-gate workflow are
ignored, or change the workflow’s output location to .benchmarks/ and retain the
existing rule. Ensure the chosen fix matches the paths written by
.github/workflows/quality-gate.yml.
In `@mcp_server/__init__.py`:
- Line 11: Update the MCPServer initialization in server.py to use the shared
__version__ value from mcp_server/__init__.py instead of the hardcoded 4.6.0
string, keeping runtime version metadata consistent.
In `@mcp_server/server.py`:
- Around line 699-713: Update expand_query to use a composite-only tokenizer for
per-token and bigram expansion lookups, excluding hyphenated sub-parts such as
“js” and “gh” from query expansion. Keep _tokenize unchanged for indexing and
scoring, and preserve composite tokens so configured phrases like “gh actions”
still match.
In `@npm/package.json`:
- Line 4: Update the description value in package.json to replace the malformed
em-dash escape \u00e2\u20ac\u201d with the correct \u2014 escape, preserving the
surrounding metadata text.
In `@tests/test_bm25_tokenizer_fragment.py`:
- Line 9: Fix the Ruff I001 import-order violation in
tests/test_bm25_tokenizer_fragment.py by applying Ruff’s automatic check fix to
the import block containing BM25Index, and preserve the resulting formatter
output.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 3c8e4b8d-79ce-40a8-a718-322eba5ea774
📒 Files selected for processing (7)
.gitignoreREADME.mdmcp_server/__init__.pymcp_server/server.pynpm/package.jsonpyproject.tomltests/test_bm25_tokenizer_fragment.py
| # Path(config.data_dir) reproduces. Preventive: use spec=Config or | ||
| # types.SimpleNamespace when mocking config in tests. | ||
| MagicMock/ | ||
| .benchmarks/ |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Ignore the benchmark files generated by the quality gate.
.github/workflows/quality-gate.yml writes branch.json and master.json at the repository root. The .benchmarks/ rule does not match either file. Add root-level ignore rules or update the workflow to write into .benchmarks/.
Proposed fix
.benchmarks/
+/branch.json
+/master.json📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| .benchmarks/ | |
| .benchmarks/ | |
| /branch.json | |
| /master.json |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @.gitignore at line 74, Update the repository ignore configuration so the
root-level branch.json and master.json artifacts generated by the quality-gate
workflow are ignored, or change the workflow’s output location to .benchmarks/
and retain the existing rule. Ensure the chosen fix matches the paths written by
.github/workflows/quality-gate.yml.
| sys.stdout = sys.stderr | ||
|
|
||
| __version__ = "4.6.0" | ||
| __version__ = "4.7.0" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Keep runtime version metadata consistent.
mcp_server/__init__.py now reports 4.7.0, but mcp_server/server.py still passes version="4.6.0" to MCPServer. Clients that read server metadata will receive the stale release version. Update the server metadata to use the same version source.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@mcp_server/__init__.py` at line 11, Update the MCPServer initialization in
server.py to use the shared __version__ value from mcp_server/__init__.py
instead of the hardcoded 4.6.0 string, keeping runtime version metadata
consistent.
| "version": "4.6.0", | ||
| "description": "Local RAG System for Claude Code — Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", | ||
| "version": "4.7.0", | ||
| "description": "Local RAG System for Claude Code \u00e2\u20ac\u201d Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use the correct em-dash escape.
\u00e2\u20ac\u201d does not encode an em dash. It encodes three different characters and produces corrupted package metadata. Replace it with \u2014.
Proposed fix
- "description": "Local RAG System for Claude Code \u00e2\u20ac\u201d Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.",
+ "description": "Local RAG System for Claude Code \u2014 Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "description": "Local RAG System for Claude Code \u00e2\u20ac\u201d Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", | |
| "description": "Local RAG System for Claude Code \u2014 Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@npm/package.json` at line 4, Update the description value in package.json to
replace the malformed em-dash escape \u00e2\u20ac\u201d with the correct \u2014
escape, preserving the surrounding metadata text.
| fragments match while IDF preserves exact-match ranking. | ||
| """ | ||
|
|
||
| from mcp_server.server import BM25Index |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Fix the Ruff import-sort failure blocking CI.
CI reports Ruff rule I001 ("Import block is unsorted or unformatted") at Line 9. This fails the CI / Lint & Format job. Run ruff check --fix on this file and commit the resulting formatting change.
#!/bin/bash
# Description: Reproduce and preview the Ruff import-sort fix for this file.
set -euo pipefail
pip install ruff --quiet 2>/dev/null || true
ruff check --diff tests/test_bm25_tokenizer_fragment.py || true🧰 Tools
🪛 GitHub Actions: CI / 1_Lint & Format.txt
[error] 9-9: Ruff check failed: import block is unsorted or unformatted (I001). Organize the imports or run 'ruff check --fix'. Command failed with exit code 1.
🪛 GitHub Actions: CI / Lint & Format
[error] 9-9: Ruff I001: Import block is unsorted or unformatted. Run 'ruff check --fix' to organize imports.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/test_bm25_tokenizer_fragment.py` at line 9, Fix the Ruff I001
import-order violation in tests/test_bm25_tokenizer_fragment.py by applying
Ruff’s automatic check fix to the import block containing BM25Index, and
preserve the resulting formatter output.
Source: Pipeline failures
Greptile SummaryThis PR fixes a silent BM25 miss for fragment queries against hyphenated alphanumeric codes (
Confidence Score: 5/5Safe to merge — the tokenizer change is backward-compatible, the composite token is always preserved, ranking is validated by tests, and no API or config surface changes. The change is a pure additive extension to _tokenize: composite tokens are still emitted unchanged, and sub-token expansion is gated behind a digit heuristic that was carefully chosen to avoid stop-word inflation. The 25-test suite covers the exact failure modes from the original report plus IDF ranking invariants and retrocompat sentinels. Files Needing Attention: No files require special attention beyond confirming the npm description mojibake is addressed before publishing the npm package.
|
| Filename | Overview |
|---|---|
| mcp_server/server.py | Core fix: _tokenize now emits composite + length-filtered sub-tokens for hyphenated numeric codes; digit heuristic prevents expansion of natural-language phrases. |
| tests/test_bm25_tokenizer_fragment.py | 306-line test file with 25 tests across 4 classes covering unit tokenizer behavior, end-to-end fragment matching, multi-doc disambiguation, and the 5 reporter-listed query patterns; includes IDF ranking invariant and retrocompat sentinel. |
| npm/package.json | Version bumped to 4.7.0; em dash in description field was re-encoded as Windows-1252 mojibake (already flagged in a previous thread). |
| pyproject.toml | Version bumped from 4.6.0 to 4.7.0; no other changes. |
| mcp_server/init.py | Version string bumped to 4.7.0; no other changes. |
| README.md | CHANGELOG entry added for v4.7.0, documenting the fix, memory impact, reindex requirement, and known limitations. |
| .gitignore | Added .benchmarks/ to suppress pytest-benchmark artifact directory. |
Reviews (2): Last reviewed commit: "fix(bm25): restrict sub-token expansion ..." | Re-trigger Greptile
| "name": "knowledge-rag", | ||
| "version": "4.6.0", | ||
| "description": "Local RAG System for Claude Code — Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", | ||
| "version": "4.7.0", |
There was a problem hiding this comment.
Mojibake in npm description field
The em dash — in the description was corrupted to the Windows-1252 mojibake sequence \u00e2\u20ac\u201d (which renders as â€"). The old value had the correct Unicode em dash. The previous pyproject.toml entry keeps the correct character, so the Python package is unaffected. Any user who views this package on the npm registry will see the garbled string in the description.
| "version": "4.6.0", | ||
| "description": "Local RAG System for Claude Code — Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", | ||
| "version": "4.7.0", | ||
| "description": "Local RAG System for Claude Code \u00e2\u20ac\u201d Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.", |
There was a problem hiding this comment.
…perf gate) Follow-up to prior commit — the initial patch expanded ALL hyphenated composites into sub-tokens, which flooded the inverted index when the corpus contained natural-language hyphenated phrases like "pass-the-hash" (frequent in infosec corpora). Concurrent BM25 queries regressed +50-60% in bench (2000-doc corpus, all containing "pass-the-hash" → 3 extra posting-list scans per query). Fix: restrict sub-token expansion to composites containing at least one digit. Alphanumeric codes (MDR-AD002, CVE-2024-1234, MS17-010, MDR-CS005) still expand — that's the real use case. Natural-language phrases (pass-the-hash, state-of-the-art) stay as single tokens. - mcp_server/server.py: add `any(c.isdigit() for c in tok)` guard on expansion - tests/test_bm25_tokenizer_fragment.py: +3 tests pinning the heuristic (natural-language stays composite, alphanumeric still expands, regression sentinel) - README.md: CHANGELOG updated to document perf-safety heuristic - tests/test_bm25_tokenizer_fragment.py: apply ruff format (blank line) Bench concurrent restored to master baseline (~42ms / 202ms / 371ms). All 28 fragment tests pass. Full local suite: 324 passed, 0 regressions. Refs #140
Summary
BM25 tokenizer preserved hyphens intentionally, indexing composite tokens like
RULE-A002as a single tokenrule-a002. Fragment queries (A002,RULE,B005) silently returnedNO_RESULTSeven when the composite existed in the corpus.This affects every hyphenated taxonomy in typical infosec/doc corpora:
RULE-*,CVE-*,ADR-*,MS17-*,PROJECT-Custom001-xxxx.Fix:
_tokenizenow emits both the composite token AND its sub-parts of length ≥ 2 (only when the composite contains at least one digit — perf-safety heuristic to avoid expanding natural-language phrases likepass-the-hash). IDF preserves exact-match ranking.Closes #140.
Note on Examples
The original PR body used real deployment code names in the reproduction snippet. Those were replaced with synthetic placeholders (
RULE-*,PROJECT-*) and public identifiers (CVE-*,MS17-*,ADR-*,T1078.002) in v4.7.1 (#143). If you're looking at v4.7.0 code, prefer v4.7.1 — the fix is identical, only the test fixtures / CHANGELOG examples changed.Reproduction (after)
Root Cause
mcp_server/server.py:698-702— regex[a-z0-9][-a-z0-9]*[a-z0-9]|[a-z0-9]treats hyphen as intra-token, no split occurs.Trade-offs
reindex_documents(force=True)on upgradeKnown Limitations (out of scope)
Alphanumeric-glued tokens without separators (single-token IDs with no hyphens, hash prefixes) still miss. Char n-grams as follow-up.
Test Plan
Note: v4.7.0 shipped with real deployment names in tests/CHANGELOG. v4.7.1 (#143) sanitizes them. Prefer v4.7.1.