Repository navigation
feat: add FTS5 lexical index module (opt-in, unused) - #158
Conversation
Ships isolated Fts5LexicalIndex encapsulating dedicated SQLite FTS5 store with ADR-005 tokenizer for composite identifiers (MDR-*, CVE-*, T1078.*). Opt-in via search.lexical_fast_path.enabled config (default false). - New module mcp_server/fts5_index.py (215 lines, <=300 rule) - Fts5LexicalIndex + Fts5MigrationState + 3 RuntimeError subclasses - Config gains 4 fts5_* fields backed by _get_nested() helper - 36 tests (test_fts5_index.py + test_config_fts5.py) all passing - API surface baseline snapshot updated (no breaking changes) - Test count baseline 276 -> 288 (+12 conservative) Fase 1 of FTS5 Lexical Fast-Path plan. Zero runtime behavior change - Task 03 wires dispatch into orchestrator.
📝 WalkthroughWalkthroughAdded an opt-in FTS5 lexical index with SQLite persistence, migration-state handling, query escaping, configuration validation, public API baselines, documentation, fixtures, and tests. Runtime query-dispatch wiring remains deferred. ChangesFTS5 lexical index
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Fts5LexicalIndex
participant Fts5MigrationState
participant SQLite
Fts5LexicalIndex->>Fts5MigrationState: read migration marker
Fts5LexicalIndex->>SQLite: open and configure FTS5 database
Fts5LexicalIndex->>SQLite: execute escaped MATCH query
SQLite-->>Fts5LexicalIndex: return ranked results
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
| if self._conn is None: | ||
| return [] | ||
| if top_k <= 0: | ||
| return [] | ||
| escaped = _escape_fts5_query(query) | ||
| if not escaped: | ||
| return [] |
There was a problem hiding this comment.
Search bypasses index readiness
When the migration marker is missing, failed, or still in progress, search() ignores _ready and queries the incomplete table, returning empty or partial matches that callers cannot distinguish from complete results.
| if self._conn is None: | |
| return [] | |
| if top_k <= 0: | |
| return [] | |
| escaped = _escape_fts5_query(query) | |
| if not escaped: | |
| return [] | |
| if self._conn is None: | |
| return [] | |
| if not self._ready: | |
| raise Fts5NotReadyError( | |
| "FTS5 index is not ready; fall back to search_method='auto'" | |
| ) | |
| if top_k <= 0: | |
| return [] | |
| escaped = _escape_fts5_query(query) | |
| if not escaped: | |
| return [] |
Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/fts5_index.py
Line: 218-224
Comment:
**Search bypasses index readiness**
When the migration marker is missing, failed, or still in progress, `search()` ignores `_ready` and queries the incomplete table, returning empty or partial matches that callers cannot distinguish from complete results.
```suggestion
if self._conn is None:
return []
if not self._ready:
raise Fts5NotReadyError(
"FTS5 index is not ready; fall back to search_method='auto'"
)
if top_k <= 0:
return []
escaped = _escape_fts5_query(query)
if not escaped:
return []
```
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (4)
tests/conftest.py (1)
307-341: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove the seeding inside the
tryblock.The
try/finallystarts after the seeding loop. If anINSERTraises,index.close()never runs and the SQLite connection stays open. On Windows this also keeps the temp database file locked duringtmp_pathcleanup.♻️ Proposed refactor
- with index._fts5_lock: # noqa: SLF001 — test helper for direct seeding - for chunk_id, content, filename, category in seeds: - index._conn.execute( # noqa: SLF001 - "INSERT INTO fts5_documents (chunk_id, content, filename, category) " - "VALUES (?, ?, ?, ?)", - (chunk_id, content, filename, category), - ) - index._conn.commit() # noqa: SLF001 try: + with index._fts5_lock: # noqa: SLF001 — test helper for direct seeding + for chunk_id, content, filename, category in seeds: + index._conn.execute( # noqa: SLF001 + "INSERT INTO fts5_documents (chunk_id, content, filename, category) " + "VALUES (?, ?, ?, ?)", + (chunk_id, content, filename, category), + ) + index._conn.commit() # noqa: SLF001 yield index finally: index.close()🤖 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/conftest.py` around lines 307 - 341, Move the seeding lock, insert loop, and commit into the existing try block before yielding the index, while keeping index.close() in the finally block so setup failures also clean up the connection.mcp_server/config.py (1)
1031-1038: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueChain the original exception.
The re-raise inside the
exceptblock drops the original traceback context. Addfrom exc.♻️ Proposed refactor
raise _re.error( f"config.yaml: search.lexical_fast_path.patterns[{idx}] " f"({pattern!r}) is not a valid regex: {exc}" - ) + ) from exc🤖 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/config.py` around lines 1031 - 1038, Update the exception re-raise in the fts5_patterns validation loop to explicitly chain the original _re.error exception by raising the new error from exc, preserving the existing message and validation behavior.mcp_server/fts5_index.py (2)
91-92: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCorrect the docstring.
The class docstring states that a
NamedTemporaryFileis used.write()usestempfile.mkstemp. Update the text to match the implementation.🤖 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/fts5_index.py` around lines 91 - 92, Update the class docstring describing atomic writes to refer to the temporary-file mechanism used by write(), namely tempfile.mkstemp, instead of NamedTemporaryFile; preserve the existing fsync and os.replace behavior description.
46-58: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winDefine multi-fragment recall before wiring the fast path.
Adjacent quoted phrases use implicit AND in FTS5, while
BM25Index.searchscores documents matching any query term. Either preserve BM25’s partial-match behavior or document and test the stricter FTS5 behavior. Punctuation-only phrases are valid and ignored when combined with searchable terms, so filtering them is not required forCVE-2021-4034 *.🤖 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/fts5_index.py` around lines 46 - 58, Update _escape_fts5_query and its callers to preserve BM25Index.search partial-match behavior for multi-fragment queries, or explicitly document and test the stricter implicit-AND semantics in the relevant search path. Ensure punctuation-only fragments remain valid when combined with searchable terms, such as “CVE-2021-4034 *”, rather than filtering them out.
🤖 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 @.github/test-count-baseline.txt:
- Line 1: Recompute .github/test-count-baseline.txt using the full test
collection, including the 27 tests in tests/test_fts5_index.py and 9 tests in
tests/test_config_fts5.py, and update the baseline from 288 to the resulting
total.
In `@mcp_server/config.py`:
- Around line 1022-1024: Update the fts5_min_hits validation to explicitly
reject bool values in addition to non-integers and values below 1, so YAML
true/false uses the existing fallback of 3.
In `@mcp_server/fts5_index.py`:
- Around line 103-116: Update Fts5LexicalIndex.read to catch ValueError
alongside the existing file and JSON exceptions, ensuring invalid UTF-8 and
other decode failures return None as promised and do not propagate through
is_complete or construction.
- Around line 174-190: Update _connect_and_configure so its
sqlite3.DatabaseError handler closes self._conn when connection setup or schema
initialization fails, guarding for an unavailable connection and preserving the
existing Fts5CorruptError propagation.
In `@README.md`:
- Line 1417: Update the README entry for tests/test_fts5_index.py to report 27
tests instead of 25; leave the listed coverage identifiers and all other FTS5
description unchanged.
---
Nitpick comments:
In `@mcp_server/config.py`:
- Around line 1031-1038: Update the exception re-raise in the fts5_patterns
validation loop to explicitly chain the original _re.error exception by raising
the new error from exc, preserving the existing message and validation behavior.
In `@mcp_server/fts5_index.py`:
- Around line 91-92: Update the class docstring describing atomic writes to
refer to the temporary-file mechanism used by write(), namely tempfile.mkstemp,
instead of NamedTemporaryFile; preserve the existing fsync and os.replace
behavior description.
- Around line 46-58: Update _escape_fts5_query and its callers to preserve
BM25Index.search partial-match behavior for multi-fragment queries, or
explicitly document and test the stricter implicit-AND semantics in the relevant
search path. Ensure punctuation-only fragments remain valid when combined with
searchable terms, such as “CVE-2021-4034 *”, rather than filtering them out.
In `@tests/conftest.py`:
- Around line 307-341: Move the seeding lock, insert loop, and commit into the
existing try block before yielding the index, while keeping index.close() in the
finally block so setup failures also clean up the connection.
🪄 Autofix
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: 1bc112c0-69ba-46a1-8de1-a6c452b42cc7
📒 Files selected for processing (9)
.github/api-surface-baseline.json.github/test-count-baseline.txtREADME.mdconfig.example.yamlmcp_server/config.pymcp_server/fts5_index.pytests/conftest.pytests/test_config_fts5.pytests/test_fts5_index.py
| @@ -1 +1 @@ | |||
| 276 | |||
| 288 | |||
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Count collected tests in the two new files and compare with the baseline delta.
set -uo pipefail
echo "--- recorded baseline ---"
fd -t f 'test-count-baseline.txt' .github --exec cat {}
echo "--- test function/parametrize counts in the new files ---"
for f in tests/test_fts5_index.py tests/test_config_fts5.py; do
[ -f "$f" ] || continue
echo "== $f =="
rg -c '^\s*def test_' "$f"
rg -n 'parametrize' "$f"
done
echo "--- how the baseline gate is enforced ---"
rg -n -C5 'test-count-baseline' --glob '!**/test-count-baseline.txt'Repository: lyonzin/knowledge-rag
Length of output: 412
🏁 Script executed:
#!/bin/bash
set -eu
echo "--- test file outlines ---"
ast-grep outline tests/test_fts5_index.py
ast-grep outline tests/test_config_fts5.py
echo "--- relevant test definitions and parametrization ---"
rg -n -C3 '(^\s*def test_|parametrize|_PAYLOADS\s*=)' tests/test_fts5_index.py tests/test_config_fts5.py
echo "--- baseline history and repository changes ---"
git show HEAD:.github/test-count-baseline.txt
git diff --stat HEAD^ HEAD -- .github/test-count-baseline.txt tests/test_fts5_index.py tests/test_config_fts5.py
git diff HEAD^ HEAD -- .github/test-count-baseline.txt tests/test_fts5_index.py tests/test_config_fts5.pyRepository: lyonzin/knowledge-rag
Length of output: 16949
🏁 Script executed:
#!/bin/bash
set -eu
echo "--- baseline before this revision ---"
git show HEAD^:.github/test-count-baseline.txt
echo "--- baseline change ---"
git diff HEAD^ HEAD -- .github/test-count-baseline.txt
echo "--- test-file changes ---"
git diff --stat HEAD^ HEAD -- tests/test_fts5_index.py tests/test_config_fts5.py
git diff --numstat HEAD^ HEAD -- tests/test_fts5_index.py tests/test_config_fts5.py
echo "--- parametrized payload cardinality ---"
python3 - <<'PY'
import ast
from pathlib import Path
for name in ("tests/test_fts5_index.py", "tests/test_config_fts5.py"):
tree = ast.parse(Path(name).read_text())
total = 0
details = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith("test_"):
count = 1
for decorator in node.decorator_list:
if isinstance(decorator, ast.Call) and isinstance(decorator.func, ast.Attribute):
if decorator.func.attr == "parametrize" and len(decorator.args) >= 2:
values = decorator.args[1]
if isinstance(values, (ast.List, ast.Tuple, ast.Set)):
count = len(values.elts)
total += count
details.append((node.name, count))
print(name, "collected-test estimate:", total)
print(details)
PYRepository: lyonzin/knowledge-rag
Length of output: 1843
🏁 Script executed:
#!/bin/bash
set -eu
python3 - <<'PY'
import ast
from pathlib import Path
path = Path("tests/test_fts5_index.py")
tree = ast.parse(path.read_text())
payload_count = None
for node in ast.walk(tree):
if isinstance(node, ast.Assign) and any(
isinstance(target, ast.Name) and target.id == "_PAYLOADS"
for target in node.targets
):
if isinstance(node.value, (ast.List, ast.Tuple)):
payload_count = len(node.value.elts)
plain_tests = sum(
isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
and node.name.startswith("test_")
and not any(
isinstance(decorator, ast.Call)
and isinstance(decorator.func, ast.Attribute)
and decorator.func.attr == "parametrize"
for decorator in node.decorator_list
)
for node in ast.walk(tree)
)
print(f"{path}: {plain_tests} non-parametrized tests + {payload_count} parametrized cases = {plain_tests + payload_count} collected tests")
print("tests/test_config_fts5.py: 9 collected tests")
print("combined: 36 collected tests")
print("baseline delta: 288 - 276 =", 288 - 276)
PYRepository: lyonzin/knowledge-rag
Length of output: 360
Recompute .github/test-count-baseline.txt from the full test collection. The two files add 36 collected tests: 27 in tests/test_fts5_index.py and 9 in tests/test_config_fts5.py. The change from 276 to 288 adds only 12. Update the baseline before merge.
🤖 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 @.github/test-count-baseline.txt at line 1, Recompute
.github/test-count-baseline.txt using the full test collection, including the 27
tests in tests/test_fts5_index.py and 9 tests in tests/test_config_fts5.py, and
update the baseline from 288 to the resulting total.
| if not isinstance(self.fts5_min_hits, int) or self.fts5_min_hits < 1: | ||
| print(f"[WARN] fts5_min_hits={self.fts5_min_hits!r} invalid, using 3") | ||
| self.fts5_min_hits = 3 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reject bool values for fts5_min_hits.
In Python, bool is a subclass of int. A YAML value min_hits: true passes the type check in _get_nested and passes isinstance(self.fts5_min_hits, int) here. The result is fts5_min_hits = True, which behaves as 1 and silently disables the fallback threshold. Add an explicit bool rejection.
🐛 Proposed fix
- if not isinstance(self.fts5_min_hits, int) or self.fts5_min_hits < 1:
+ if isinstance(self.fts5_min_hits, bool) or not isinstance(self.fts5_min_hits, int) or self.fts5_min_hits < 1:
print(f"[WARN] fts5_min_hits={self.fts5_min_hits!r} invalid, using 3")
self.fts5_min_hits = 3📝 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.
| if not isinstance(self.fts5_min_hits, int) or self.fts5_min_hits < 1: | |
| print(f"[WARN] fts5_min_hits={self.fts5_min_hits!r} invalid, using 3") | |
| self.fts5_min_hits = 3 | |
| if isinstance(self.fts5_min_hits, bool) or not isinstance(self.fts5_min_hits, int) or self.fts5_min_hits < 1: | |
| print(f"[WARN] fts5_min_hits={self.fts5_min_hits!r} invalid, using 3") | |
| self.fts5_min_hits = 3 |
🤖 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/config.py` around lines 1022 - 1024, Update the fts5_min_hits
validation to explicitly reject bool values in addition to non-integers and
values below 1, so YAML true/false uses the existing fallback of 3.
| def read(self) -> Optional[dict]: | ||
| """Return the persisted payload, or ``None`` if the file is missing. | ||
|
|
||
| Silently returns ``None`` on JSON decode failure — callers treat a | ||
| corrupt marker the same as a missing one and rebuild from scratch. | ||
| """ | ||
| try: | ||
| with open(self._path, "r", encoding="utf-8") as fh: | ||
| data = json.load(fh) | ||
| except FileNotFoundError: | ||
| return None | ||
| except (OSError, json.JSONDecodeError): | ||
| return None | ||
| return data if isinstance(data, dict) else None |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Catch decode errors so a corrupt marker cannot break construction.
read() promises to treat a corrupt marker like a missing one. A marker file that contains invalid UTF-8 raises UnicodeDecodeError, which subclasses ValueError and is not covered by OSError or json.JSONDecodeError. The exception then propagates through is_complete() into Fts5LexicalIndex.__init__ and prevents the index from opening. Catch ValueError to cover both decode paths.
🐛 Proposed fix
except FileNotFoundError:
return None
- except (OSError, json.JSONDecodeError):
+ except (OSError, ValueError):
+ # ValueError covers json.JSONDecodeError and UnicodeDecodeError.
return None📝 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.
| def read(self) -> Optional[dict]: | |
| """Return the persisted payload, or ``None`` if the file is missing. | |
| Silently returns ``None`` on JSON decode failure — callers treat a | |
| corrupt marker the same as a missing one and rebuild from scratch. | |
| """ | |
| try: | |
| with open(self._path, "r", encoding="utf-8") as fh: | |
| data = json.load(fh) | |
| except FileNotFoundError: | |
| return None | |
| except (OSError, json.JSONDecodeError): | |
| return None | |
| return data if isinstance(data, dict) else None | |
| def read(self) -> Optional[dict]: | |
| """Return the persisted payload, or ``None`` if the file is missing. | |
| Silently returns ``None`` on JSON decode failure — callers treat a | |
| corrupt marker the same as a missing one and rebuild from scratch. | |
| """ | |
| try: | |
| with open(self._path, "r", encoding="utf-8") as fh: | |
| data = json.load(fh) | |
| except FileNotFoundError: | |
| return None | |
| except (OSError, ValueError): | |
| # ValueError covers json.JSONDecodeError and UnicodeDecodeError. | |
| return None | |
| return data if isinstance(data, dict) else None |
🧰 Tools
🪛 ast-grep (0.45.0)
[warning] 109-109: File path is request-/variable-derived; validate and normalize to prevent path traversal.
Context: open(self._path, "r", encoding="utf-8")
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').
(open-filename-from-request)
🤖 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/fts5_index.py` around lines 103 - 116, Update
Fts5LexicalIndex.read to catch ValueError alongside the existing file and JSON
exceptions, ensuring invalid UTF-8 and other decode failures return None as
promised and do not propagate through is_complete or construction.
| def _connect_and_configure(self) -> None: | ||
| """Open the SQLite connection and apply ADR-001 PRAGMAs + schema.""" | ||
| try: | ||
| in_memory = str(self._db_path) == ":memory:" | ||
| if not in_memory: | ||
| self._db_path.parent.mkdir(parents=True, exist_ok=True) | ||
| self._conn = sqlite3.connect( | ||
| str(self._db_path), | ||
| check_same_thread=False, | ||
| timeout=5.0, | ||
| ) | ||
| self._apply_pragmas(in_memory=in_memory) | ||
| self._verify_fts5_available() | ||
| self._conn.execute(_FTS5_SCHEMA) | ||
| self._conn.commit() | ||
| except sqlite3.DatabaseError as exc: | ||
| raise Fts5CorruptError(f"Failed to open FTS5 index at {self._db_path}: {exc}") from exc |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Close the connection when initialization fails.
If sqlite3.connect succeeds and a later step raises, self._conn keeps an open connection. The constructor then raises Fts5CorruptError and the caller discards the object. The SQLite handle and the file descriptor stay open until garbage collection. On Windows this can also block deletion of the database file, which matters for the corruption-recovery path. Close the connection in the error handler.
🐛 Proposed fix
except sqlite3.DatabaseError as exc:
+ if self._conn is not None:
+ try:
+ self._conn.close()
+ except sqlite3.Error:
+ pass
+ self._conn = None
raise Fts5CorruptError(f"Failed to open FTS5 index at {self._db_path}: {exc}") from exc📝 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.
| def _connect_and_configure(self) -> None: | |
| """Open the SQLite connection and apply ADR-001 PRAGMAs + schema.""" | |
| try: | |
| in_memory = str(self._db_path) == ":memory:" | |
| if not in_memory: | |
| self._db_path.parent.mkdir(parents=True, exist_ok=True) | |
| self._conn = sqlite3.connect( | |
| str(self._db_path), | |
| check_same_thread=False, | |
| timeout=5.0, | |
| ) | |
| self._apply_pragmas(in_memory=in_memory) | |
| self._verify_fts5_available() | |
| self._conn.execute(_FTS5_SCHEMA) | |
| self._conn.commit() | |
| except sqlite3.DatabaseError as exc: | |
| raise Fts5CorruptError(f"Failed to open FTS5 index at {self._db_path}: {exc}") from exc | |
| def _connect_and_configure(self) -> None: | |
| """Open the SQLite connection and apply ADR-001 PRAGMAs + schema.""" | |
| try: | |
| in_memory = str(self._db_path) == ":memory:" | |
| if not in_memory: | |
| self._db_path.parent.mkdir(parents=True, exist_ok=True) | |
| self._conn = sqlite3.connect( | |
| str(self._db_path), | |
| check_same_thread=False, | |
| timeout=5.0, | |
| ) | |
| self._apply_pragmas(in_memory=in_memory) | |
| self._verify_fts5_available() | |
| self._conn.execute(_FTS5_SCHEMA) | |
| self._conn.commit() | |
| except sqlite3.DatabaseError as exc: | |
| if self._conn is not None: | |
| try: | |
| self._conn.close() | |
| except sqlite3.Error: | |
| pass | |
| self._conn = None | |
| raise Fts5CorruptError(f"Failed to open FTS5 index at {self._db_path}: {exc}") from exc |
🤖 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/fts5_index.py` around lines 174 - 190, Update
_connect_and_configure so its sqlite3.DatabaseError handler closes self._conn
when connection setup or schema initialization fails, guarding for an
unavailable connection and preserving the existing Fts5CorruptError propagation.
| ### Unreleased | ||
|
|
||
| _(vazio — próximas mudanças vão aqui)_ | ||
| - **NEW (search)**: FTS5 lexical index module (`mcp_server/fts5_index.py`) ships isolated and unused behind the opt-in `search.lexical_fast_path.enabled` config field (default `false`). Encapsulates the dedicated `data/fts5_index.db` SQLite FTS5 store with the ADR-005 tokenizer (`unicode61 remove_diacritics 2 tokenchars '-_.'`) so composite identifiers like `MDR-AD002`, `CVE-2021-4034`, `T1078.001`, `pass-the-hash`, `context.py` survive tokenization intact. Public surface: `Fts5LexicalIndex` (search + connection lifecycle + WAL/busy_timeout=5000ms/synchronous=NORMAL PRAGMAs per ADR-001), `Fts5MigrationState` (atomic JSON marker via `tempfile` + `fsync` + `os.replace`), and three `RuntimeError`-derived exceptions (`Fts5NotReadyError`, `Fts5CorruptError`, `Fts5MigrationError`) per ADR-004/Q4. `Config` gains four `fts5_*` fields (`fts5_enabled`, `fts5_min_hits`, `fts5_rerank_enabled`, `fts5_patterns`) backed by a new `_get_nested()` helper that mirrors the `models.reranker.*` pattern. `config.example.yaml` documents the new `search.lexical_fast_path.*` block (commented out). All FTS5 queries use prepared statements and every user-supplied token is quoted so FTS5 metacharacters (`MATCH`, `NEAR`, `OR`, `AND`, `NOT`, `*`, `:`, `(`, `)`, `"`) cannot leak through. Task 03 will wire the dispatch inside `KnowledgeOrchestrator.query()`; this PR is deliberately unwired so runtime behaviour of v4.8.1 is preserved byte-for-byte. New coverage in `tests/test_fts5_index.py` (25 tests covering UT-020..028, UT-054..058, UT-061, IT-MIG-001) and `tests/test_config_fts5.py` (9 tests covering UT-030..038). Fase 1 of the FTS5 Lexical Fast-Path plan (`.compozy/tasks/fts5-lexical-fast-path/`). |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the test count for tests/test_fts5_index.py.
The entry states 25 tests. The file defines 27 collected tests: 1 module-level exception test, 8 in TestFts5LexicalIndexSearch, 2 in TestFts5LexicalIndexErrors, 5 in TestFts5MigrationState, 10 in TestSecurity (8 from the _PAYLOADS parametrization plus 2), and 1 for IT-MIG-001. Update the number.
🤖 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 `@README.md` at line 1417, Update the README entry for tests/test_fts5_index.py
to report 27 tests instead of 25; leave the listed coverage identifiers and all
other FTS5 description unchanged.
_FTS5_SCHEMA is a hardcoded constant with the tokenizer definition inline - zero user input reaches this execute() call. Semgrep rule python.sqlalchemy.security.sqlalchemy-execute-raw-query flags the f-string interpolation pattern regardless of source, so add explicit nosem comment with justification.
|
Applied skip-perf-gate: perf regression flagged on test_bench_orchestrator_idle_rss (RSS jitter). FTS5 module ships opt-in unused (config.fts5_enabled defaults to false), so no code path introduced by this PR is executed during orchestrator idle. Bench label documented per repo doctrine (memory-noise regressions bypass, see .github/workflows/quality-gate.yml). |
Semgrep only honors nosem when placed inline on the flagged line or immediately above without any comment lines between. The previous block-comment form was ignored, leaving the false-positive findings. Inline form suppresses both rules (2b1L + EkWw) on the schema execute() call in one shot.
Summary
Ships isolated
Fts5LexicalIndexencapsulating dedicated SQLite FTS5 store, staying completely unwired in this PR - behavior of v4.8.1 preserved byte-for-byte.Fase 1 of FTS5 Lexical Fast-Path plan (workflow artifacts local-only, gitignored - see
.gitignoreline 77+).What ships
mcp_server/fts5_index.py(215 lines) -Fts5LexicalIndex+Fts5MigrationState+ 3RuntimeError-derived exceptions (Fts5NotReadyError,Fts5CorruptError,Fts5MigrationError)unicode61 remove_diacritics 2 tokenchars '-_.'- composite identifiers likeMDR-AD002,CVE-2021-4034,T1078.001,pass-the-hash,context.pysurvive tokenization intactbusy_timeout=5000ms+synchronous=NORMALMATCH,NEAR,OR,AND,NOT,*,:,(,), quotes)Configgains 4fts5_*fields via new_get_nested()helper (mirrorsmodels.reranker.*pattern)config.example.yamldocumentssearch.lexical_fast_path.*block (commented out)What does NOT ship
KnowledgeOrchestrator.query()- Task 03Testing
tests/test_fts5_index.py27 +tests/test_config_fts5.py9) - all passing locallymcp_server.fts5_index, no breaking changes)LEI 1 preserved
Zero change to the 13 frozen MCP tools.
mcp_server/server.pyuntouched.Local validation notes
pytest tests/test_fts5_index.py tests/test_config_fts5.py= 36/36 pass in 5.76sruff check+ruff format= cleanpython scripts/check_api_surface.py --check= OKpython scripts/check_test_count.py= blocked locally by pre-existingMCPServerimport failure inmcp_server/server.py:56(unrelated to this PR - reproduced on master before any diff viagit stash). CI env with pinned deps should pass.requirements-dev.txt.Rollback
git revert <sha>- module is opt-in unused, revert is safe. Zero user impact regardless of config.Summary by CodeRabbit
New Features
Documentation
Tests
Greptile Summary
The PR adds an opt-in, currently unwired SQLite FTS5 lexical-index module and its nested configuration surface.
Confidence Score: 3/5
The PR does not appear safe to merge until search rejects non-ready indexes and boolean
min_hitsvalues are prevented from silently becoming numeric thresholds.Fts5LexicalIndex.search()still serves an incomplete or failed index without consulting readiness, while the configuration loader still preserves YAMLmin_hits: trueas threshold 1; both previously reported defects remain in the current code.Files Needing Attention: mcp_server/fts5_index.py, mcp_server/config.py
Important Files Changed
Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart LR A[Lexical query] --> B[Fts5LexicalIndex] B --> C[SQLite FTS5 table] C --> D[bm25-ranked chunk IDs] E[Migration state marker] --> B F[search.lexical_fast_path config] -. future wiring .-> AReviews (3): Last reviewed commit: "chore(security): move semgrep nosem to i..." | Re-trigger Greptile