Skip to content

fix(bm25): support fragment queries via sub-token expansion (v4.7.0) - #141

Merged
lyonzin merged 2 commits into
masterfrom
fix/bm25-tokenizer-fragment-support
Aug 1, 2026
Merged

lyonzin merged 2 commits into
masterfrom
fix/bm25-tokenizer-fragment-support

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

BM25 tokenizer preserved hyphens intentionally, indexing composite tokens like RULE-A002 as a single token rule-a002. Fragment queries (A002, RULE, B005) silently returned NO_RESULTS even 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: _tokenize now 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 like pass-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)

bm25.search("A002")   # ← was []; now returns RULE-A002 doc
bm25.search("RULE")   # ← was []; now returns all RULE-* family
bm25.search("B005")   # ← was []; now returns RULE-B005 doc

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

  • ✅ Backwards-compatible (composite queries continue to match)
  • ✅ Zero API/config change
  • ⚠️ +30-50% BM25 inverted-index memory overhead
  • ⚠️ Requires reindex_documents(force=True) on upgrade

Known 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

  • 28 fragment tests covering unit tokenizer + integration + patterns
  • Full local suite green
  • 9-cell CI matrix green
  • Bench: bm25 query within perf gate

Note: v4.7.0 shipped with real deployment names in tests/CHANGELOG. v4.7.1 (#143) sanitizes them. Prefer v4.7.1.

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
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: faf83e00-95f2-4899-8d22-146f7aa22821

📥 Commits

Reviewing files that changed from the base of the PR and between 2eae503 and a77c07e.

📒 Files selected for processing (3)
  • README.md
  • mcp_server/server.py
  • tests/test_bm25_tokenizer_fragment.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • README.md
  • mcp_server/server.py

📝 Walkthrough

Walkthrough

Changes

BM25 fragment matching

Layer / File(s) Summary
Hyphenated-token expansion and regression coverage
mcp_server/server.py, tests/test_bm25_tokenizer_fragment.py
BM25Index._tokenize retains composite tokens and adds qualifying hyphen-separated parts. Tests cover normalization, filtering, matching, ranking, and issue #140 query patterns.
Release and repository updates
README.md, mcp_server/__init__.py, pyproject.toml, npm/package.json, .gitignore
Version metadata and release notes move to 4.7.0. The notes document forced reindexing, memory usage, and glued-token limitations. Benchmark output is ignored.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the BM25 fragment-query fix and the sub-token expansion approach.
Linked Issues check ✅ Passed The changes satisfy issue #140 by enabling digit-bearing hyphenated fragments, preserving exact matches, avoiding API changes, and documenting reindexing and limitations.
Out of Scope Changes check ✅ Passed The version, changelog, package metadata, ignore rule, implementation, and tests directly support the BM25 fix and its 4.7.0 release.
Docstring Coverage ✅ Passed Docstring coverage is 86.21% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/bm25-tokenizer-fragment-support

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9ee58d5 and 2eae503.

📒 Files selected for processing (7)
  • .gitignore
  • README.md
  • mcp_server/__init__.py
  • mcp_server/server.py
  • npm/package.json
  • pyproject.toml
  • tests/test_bm25_tokenizer_fragment.py

Comment thread .gitignore
# Path(config.data_dir) reproduces. Preventive: use spec=Config or
# types.SimpleNamespace when mocking config in tests.
MagicMock/
.benchmarks/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
.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.

Comment thread mcp_server/__init__.py
sys.stdout = sys.stderr

__version__ = "4.6.0"
__version__ = "4.7.0"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment thread mcp_server/server.py Resolved
Comment thread npm/package.json
"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.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
"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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a silent BM25 miss for fragment queries against hyphenated alphanumeric codes (MDR-*, CVE-*, MS17-*). The tokenizer previously indexed MDR-AD002 as a single token, so queries for AD002 or MDR returned zero results even when the composite existed in the corpus.

  • mcp_server/server.py: _tokenize now emits the composite token plus all length-≥-2 sub-parts whenever the composite contains a hyphen and at least one digit; natural-language hyphenated phrases (no digit) are left as single tokens to avoid flooding the index with stop-word-like sub-tokens.
  • tests/test_bm25_tokenizer_fragment.py: 25 new tests across 4 classes validate unit tokenizer behavior, end-to-end fragment matching, multi-doc disambiguation, IDF ranking invariants, and all 5 query patterns from issue fix(bm25): fragment queries return NO_RESULTS for hyphenated composite tokens #140.
  • Versioning: pyproject.toml, mcp_server/__init__.py, and npm/package.json are atomically bumped to 4.7.0; README CHANGELOG documents the reindex requirement and +30-50% BM25 memory impact.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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

Comment thread npm/package.json
"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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

Comment thread npm/package.json
"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.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 The em dash was re-encoded as Windows-1252 mojibake during this PR. Restore the correct Unicode character so the npm registry displays the description properly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

…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
@lyonzin
lyonzin merged commit 75a164b into master Aug 1, 2026
38 checks passed
@lyonzin
lyonzin deleted the fix/bm25-tokenizer-fragment-support branch August 1, 2026 02:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(bm25): fragment queries return NO_RESULTS for hyphenated composite tokens

1 participant