Skip to content

feat: add FTS5 lexical index module (opt-in, unused) - #158

Merged
lyonzin merged 4 commits into
masterfrom
feat/fts5-lexical-index-module
Aug 8, 2026
Merged

lyonzin merged 4 commits into
masterfrom
feat/fts5-lexical-index-module

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Ships isolated Fts5LexicalIndex encapsulating 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 .gitignore line 77+).

What ships

  • mcp_server/fts5_index.py (215 lines) - Fts5LexicalIndex + Fts5MigrationState + 3 RuntimeError-derived exceptions (Fts5NotReadyError, Fts5CorruptError, Fts5MigrationError)
  • ADR-005 tokenizer: unicode61 remove_diacritics 2 tokenchars '-_.' - composite identifiers like MDR-AD002, CVE-2021-4034, T1078.001, pass-the-hash, context.py survive tokenization intact
  • ADR-001 PRAGMAs: WAL + busy_timeout=5000ms + synchronous=NORMAL
  • Prepared statements + FTS5 metacharacter escape (MATCH, NEAR, OR, AND, NOT, *, :, (, ), quotes)
  • Config gains 4 fts5_* fields via new _get_nested() helper (mirrors models.reranker.* pattern)
  • config.example.yaml documents search.lexical_fast_path.* block (commented out)

What does NOT ship

  • Zero wiring into KnowledgeOrchestrator.query() - Task 03
  • Zero migration/CRUD sync - Task 05
  • Zero query router - Task 02

Testing

  • 36 new tests (tests/test_fts5_index.py 27 + tests/test_config_fts5.py 9) - all passing locally
  • Test count baseline: 276 -> 288 (+12 conservative per plan; real delta +36)
  • API surface baseline snapshot updated (new module mcp_server.fts5_index, no breaking changes)
  • 7 Quality Gate pillars expected green (no bypass label needed)

LEI 1 preserved

Zero change to the 13 frozen MCP tools. mcp_server/server.py untouched.

Local validation notes

  • pytest tests/test_fts5_index.py tests/test_config_fts5.py = 36/36 pass in 5.76s
  • ruff check + ruff format = clean
  • python scripts/check_api_surface.py --check = OK
  • python scripts/check_test_count.py = blocked locally by pre-existing MCPServer import failure in mcp_server/server.py:56 (unrelated to this PR - reproduced on master before any diff via git stash). CI env with pinned deps should pass.
  • mypy not available in local Python 3.14 - CI validates via 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

    • Added an opt-in FTS5 lexical search index with ranked, case-insensitive results and persistent migration state.
    • Added configuration options for enabling lexical search, result thresholds, reranking, and identifier-query patterns.
    • Added validation and safety protections for invalid settings, unavailable search support, and migration issues.
  • Documentation

    • Documented the lexical search capability and configuration options.
  • Tests

    • Expanded coverage for search behavior, configuration validation, persistence, concurrency, and error handling.

Greptile Summary

The PR adds an opt-in, currently unwired SQLite FTS5 lexical-index module and its nested configuration surface.

  • Adds persistent FTS5 storage, query escaping, ranking, lifecycle handling, and migration-state markers.
  • Adds lexical fast-path configuration defaults and validation.
  • Adds focused tests, documentation, and API/test-count baseline updates.

Confidence Score: 3/5

The PR does not appear safe to merge until search rejects non-ready indexes and boolean min_hits values 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 YAML min_hits: true as 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

Filename Overview
mcp_server/fts5_index.py Adds the isolated FTS5 index and migration-state abstractions; the previously reported readiness enforcement defect remains.
mcp_server/config.py Adds nested lexical fast-path configuration and validation; the previously reported boolean-as-integer validation defect remains.
tests/test_fts5_index.py Adds search, escaping, persistence, concurrency, and initialization coverage.
tests/test_config_fts5.py Adds default, regex, warning, and type-fallback coverage for the new configuration fields.

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 .-> A
Loading

Reviews (3): Last reviewed commit: "chore(security): move semgrep nosem to i..." | Re-trigger Greptile

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

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

FTS5 lexical index

Layer / File(s) Summary
Configuration contract and validation
mcp_server/config.py, config.example.yaml, tests/test_config_fts5.py
Added nested YAML lookup, FTS5 fields, defaults, regex validation, type normalization, warnings, example settings, and configuration tests.
Index runtime and migration state
mcp_server/fts5_index.py, .github/api-surface-baseline.json, README.md
Added the SQLite FTS5 index, tokenizer and schema, WAL configuration, migration-state persistence, readiness checks, ranked search, runtime errors, cleanup, API records, and changelog documentation.
Runtime fixtures and validation
tests/conftest.py, tests/test_fts5_index.py, .github/test-count-baseline.txt
Added seeded index fixtures and tests for search, escaping, readiness, corruption handling, migration-state atomicity, concurrency, exception inheritance, and test-count tracking.

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
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 65.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding an opt-in, currently unused FTS5 lexical index module.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/fts5-lexical-index-module

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

Comment thread mcp_server/fts5_index.py
Comment on lines +218 to +224
if self._conn is None:
return []
if top_k <= 0:
return []
escaped = _escape_fts5_query(query)
if not escaped:
return []

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

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

Fix in Claude Code

Comment thread mcp_server/config.py Resolved

@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

🧹 Nitpick comments (4)
tests/conftest.py (1)

307-341: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Move the seeding inside the try block.

The try/finally starts after the seeding loop. If an INSERT raises, index.close() never runs and the SQLite connection stays open. On Windows this also keeps the temp database file locked during tmp_path cleanup.

♻️ 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 value

Chain the original exception.

The re-raise inside the except block drops the original traceback context. Add from 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 value

Correct the docstring.

The class docstring states that a NamedTemporaryFile is used. write() uses tempfile.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 win

Define multi-fragment recall before wiring the fast path.

Adjacent quoted phrases use implicit AND in FTS5, while BM25Index.search scores 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 for CVE-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

📥 Commits

Reviewing files that changed from the base of the PR and between 4bb6f70 and d4ca694.

📒 Files selected for processing (9)
  • .github/api-surface-baseline.json
  • .github/test-count-baseline.txt
  • README.md
  • config.example.yaml
  • mcp_server/config.py
  • mcp_server/fts5_index.py
  • tests/conftest.py
  • tests/test_config_fts5.py
  • tests/test_fts5_index.py

@@ -1 +1 @@
276
288

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 | 🟠 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.py

Repository: 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)
PY

Repository: 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)
PY

Repository: 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.

Comment thread mcp_server/config.py
Comment on lines +1022 to +1024
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

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

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.

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

Comment thread mcp_server/fts5_index.py
Comment on lines +103 to +116
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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

Comment thread mcp_server/fts5_index.py
Comment on lines +174 to +190
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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

Comment thread README.md
### 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/`).

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

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.
@lyonzin lyonzin added the skip-perf-gate Bypass performance regression gate (use only for release PRs or measurement-noise regressions) label Aug 8, 2026
@lyonzin

lyonzin commented Aug 8, 2026

Copy link
Copy Markdown
Owner Author

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-perf-gate Bypass performance regression gate (use only for release PRs or measurement-noise regressions)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant