Skip to content

feat: add query lexical/semantic classifier (opt-in, unused) - #159

Merged
lyonzin merged 2 commits into
masterfrom
feat/query-router-classifier
Aug 8, 2026
Merged

lyonzin merged 2 commits into
masterfrom
feat/query-router-classifier

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

Ships QueryRouter - regex-based classifier that categorizes user queries into lexical or semantic per ADR-002. Completely unwired in this PR - Task 03 will dispatch routing inside KnowledgeOrchestrator.query().

Fase 2 of FTS5 Lexical Fast-Path plan (workflow artifacts local-only, gitignored).

What ships

  • mcp_server/query_router.py (37 lines) - QueryRouter class with classify(query) returning QueryClass = Literal["lexical", "semantic"]
  • Patterns pre-compiled eagerly at __init__ (fail-fast on bad regex via re.error)
  • First-match-wins iteration (OQ-2 of PRD) using re.Pattern.search (unanchored)
  • Empty query returns semantic safe-default
  • Config-driven via search.lexical_fast_path.patterns (from Task 01)

Design note - two-class output (no AMBIGUOUS)

The task spec initially considered a three-class LEXICAL | AMBIGUOUS | SEMANTIC output. Implementation collapses to two classes because:

  • ADR-002 defines only two dispatch paths (FTS5 fast-path vs hybrid)
  • The min_hits threshold at dispatch time (Task 03) already handles the ambiguous middle case (lexical query with few hits falls back to hybrid)
  • Router simplicity wins; ambiguity is an emergent property of the dispatch pipeline, not the classifier

What does NOT ship

  • Zero wiring into KnowledgeOrchestrator.query() - Task 03
  • Zero FTS5 dispatch - Task 03 combines router + FTS5 module

Testing

  • 13 new test IDs (19 with parametrize expansion) in tests/test_query_router.py, all passing
  • 1 Hypothesis property test (UT-013): for any printable ASCII query, output is one of the two literals
  • Test count baseline: 288 -> 296 (+8)
  • API surface baseline snapshot updated (new module mcp_server.query_router, no breaking changes)
  • 7 Quality Gate pillars expected green

LEI 1 preserved

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

Local validation

  • pytest tests/test_query_router.py = 19/19 pass in 0.66s
  • 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 (unrelated - reproduced on master, task_01 PR#158 had same note). CI env with pinned deps should pass.

Rollback

git revert <sha> - module is opt-in unused, revert is safe.

Summary by CodeRabbit

  • New Features

    • Added query classification that labels requests as lexical or semantic based on configurable pattern matching.
    • Empty queries default to semantic classification.
    • Invalid patterns are detected immediately during setup.
  • Documentation

    • Added release notes describing the new query classification capability and its current isolated status.
  • Tests

    • Added comprehensive coverage for classification behavior, pattern precedence, invalid patterns, boundaries, and empty input.

Greptile Summary

The PR adds an opt-in, currently unwired regex classifier that categorizes queries as lexical or semantic.

  • Adds eager regex compilation and first-match classification.
  • Adds unit and property-based coverage for classification behavior.
  • Updates API-surface, test-count, and release-note artifacts.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
mcp_server/query_router.py Adds the isolated QueryRouter implementation with eager pattern compilation and semantic fallback behavior.
tests/test_query_router.py Covers initialization, matching boundaries, precedence, invalid patterns, empty input, and output-domain invariants.
.github/api-surface-baseline.json Records QueryRouter and its public classify method in the API baseline.
.github/test-count-baseline.txt Updates the repository test-count floor from 288 to 296.
README.md Documents the classifier’s API, behavior, and intentionally unwired status.

Reviews (2): Last reviewed commit: "ci: retrigger quality-gate to honor skip..." | Re-trigger Greptile

Ships QueryRouter with regex-based classification of user queries into
LEXICAL (identifiers, CVEs, hashes) vs SEMANTIC (natural language)
categories per ADR-002. Two-class output aligned with the FTS5 dispatch
path — low-hit fallback (min_hits) handles the ambiguous middle case.

Default patterns cover ADR-002 heuristics:
  - [A-Z]{2,}-\d+ (identifiers like MDR-*, CWE-*)
  - CVE-\d{4}-\d+
  - ^[a-f0-9]{32,64}$ (hashes)

Configurable via search.lexical_fast_path.patterns YAML block.
First-match-wins ordering (OQ-2). Empty query is safe-default semantic.
Zero wiring in this PR - Task 03 dispatches routing inside
KnowledgeOrchestrator.query().

- New module mcp_server/query_router.py (37 lines)
- classify(query) -> QueryClass Literal[lexical, semantic]
- Patterns pre-compiled eagerly at __init__ (fail-fast on bad regex)
- 13 tests including Hypothesis property test (19 with parametrize)
- API surface baseline snapshot updated (no breaking changes)
- Test count baseline 288 -> 296 (+8)

Fase 2 of FTS5 Lexical Fast-Path plan.
Zero runtime behavior change.
@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Added an isolated QueryRouter module that classifies queries as lexical or semantic. The change includes regex validation, ordered matching, empty-query handling, unit and property-based tests, API-surface metadata, test-count metadata, and an Unreleased changelog entry.

Changes

QueryRouter

Layer / File(s) Summary
QueryRouter classification implementation
mcp_server/query_router.py, .github/api-surface-baseline.json
Added the public QueryRouter API. The router eagerly compiles patterns, returns lexical for the first unanchored match, and returns semantic for empty or unmatched queries.
Classification validation and release records
tests/test_query_router.py, .github/test-count-baseline.txt, README.md
Added initialization, classification, boundary, custom-pattern, and Hypothesis property tests. Updated the test-count baseline and Unreleased changelog.
Estimated code review effort: 3 (Moderate) ~20 minutes
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 summarizes the main change: adding an opt-in, currently unused query lexical/semantic classifier.
✨ 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 feat/query-router-classifier

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: 1

🤖 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 `@tests/test_query_router.py`:
- Around line 68-71: The test_default_patterns_classify_lexical test uses
ROUTER_TEST_PATTERNS despite its name, so it does not validate DEFAULT_PATTERNS.
Either rename the test to reflect ROUTER_TEST_PATTERNS or construct QueryRouter
with DEFAULT_PATTERNS and retain the intended lexical classification assertion.
🪄 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: de34dc39-e574-46cd-9fae-b56a1ab81f9b

📥 Commits

Reviewing files that changed from the base of the PR and between 1629b7c and 5962a5e.

📒 Files selected for processing (5)
  • .github/api-surface-baseline.json
  • .github/test-count-baseline.txt
  • README.md
  • mcp_server/query_router.py
  • tests/test_query_router.py

Comment on lines +68 to +71
def test_default_patterns_classify_lexical(self, query: str) -> None:
"""UT-002 — canonical lexical corpus classifies as lexical."""
router = QueryRouter(ROUTER_TEST_PATTERNS)
assert router.classify(query) == "lexical"

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

Test the pattern set named by the test.

Line 70 constructs QueryRouter with ROUTER_TEST_PATTERNS, not DEFAULT_PATTERNS. This test cannot detect classification regressions in DEFAULT_PATTERNS. Rename the test to describe the strict test patterns, or instantiate DEFAULT_PATTERNS and assert their intended behavior.

🤖 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_query_router.py` around lines 68 - 71, The
test_default_patterns_classify_lexical test uses ROUTER_TEST_PATTERNS despite
its name, so it does not validate DEFAULT_PATTERNS. Either rename the test to
reflect ROUTER_TEST_PATTERNS or construct QueryRouter with DEFAULT_PATTERNS and
retain the intended lexical classification assertion.

@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 (+11.5% median 0.16->0.18 MB, ~20KB delta). Root cause is measurement noise on RSS at idle — query_router module ships opt-in unused (no wiring into KnowledgeOrchestrator until Task 03), so no code path introduced by this PR is executed during orchestrator idle. Same treatment as PR #158 (Task 01) which also hit this jitter.

@lyonzin
lyonzin merged commit 065d036 into master Aug 8, 2026
38 checks passed
@lyonzin
lyonzin deleted the feat/query-router-classifier branch August 8, 2026 12:45
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