Skip to content

feat: Enhance semantic search scoring with multi-chunk breadth boost - #781

Merged
malibio merged 3 commits into
mainfrom
feature/issue-778-semantic-search-scoring
Dec 23, 2025
Merged

malibio merged 3 commits into
mainfrom
feature/issue-778-semantic-search-scoring

Conversation

@malibio

@malibio malibio commented Dec 23, 2025

Copy link
Copy Markdown
Collaborator

Summary

Improves semantic search ranking by considering both chunk similarity and breadth of relevance. Documents with multiple relevant chunks now rank higher than those with a single high-scoring chunk (Issue #778).

  • New scoring formula: score = max_similarity * (1 + 0.3 * log10(matching_chunks))
  • Updated EmbeddingSearchResult: Now includes score, max_similarity, and matching_chunks fields
  • Enhanced SQL query: Counts matching chunks per node for breadth calculation
  • Comprehensive tests: New test validates multi-chunk scoring behavior

Example Results

Document Max Sim Chunks Score
Doc A 0.85 1 0.85
Doc B 0.80 5 0.97

Doc B ranks higher due to broader relevance.

Test plan

  • Run bun run rust:test - 674 tests passed
  • Run bun run test - 3431 tests passed
  • Verify new test_multi_chunk_scoring_breadth_boost test passes
  • Run cargo clippy - no warnings
  • Run bun run quality:fix - no issues

Closes #778

🤖 Generated with Claude Code

malibio and others added 2 commits December 23, 2025 17:08
…(Issue #778)

Improves semantic search ranking by considering both chunk similarity and
breadth of relevance. Documents with multiple relevant chunks now rank
higher than those with a single high-scoring chunk.

## Changes

### Scoring Algorithm (Issue #778)
- New composite score formula: `max_similarity * (1 + 0.3 * log10(matching_chunks))`
- Single-chunk documents score unchanged (log10(1) = 0)
- Multi-chunk documents get breadth boost (e.g., 5 chunks → 1.21x multiplier)

### Updated `EmbeddingSearchResult` Model
- Added `score`: Composite relevance score (primary ranking)
- Added `max_similarity`: Best chunk similarity (raw cosine)
- Added `matching_chunks`: Count of chunks above threshold
- Removed `similarity` field (replaced by `score` and `max_similarity`)

### Enhanced SQL Query
- Subquery calculates per-chunk similarity before grouping
- Counts chunks exceeding threshold per node
- Results sorted by composite score in Rust (DB pre-sorts by max_similarity)
- Increased KNN limit from 3x to 5x to capture more chunks per node

### Test Coverage
- New `test_multi_chunk_scoring_breadth_boost` validates ranking behavior
- Updated existing tests to use new field names
- Verifies breadth boost formula correctness

## Example Results

| Document | Max Sim | Chunks | Score |
|----------|---------|--------|-------|
| Doc A    | 0.85    | 1      | 0.85  |
| Doc B    | 0.80    | 5      | 0.97  |

Doc B now ranks higher due to broader relevance.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 23, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #781 - Semantic Search Multi-Chunk Scoring

Review Type: Initial Review


Requirements Check (Issue #778)

Acceptance Criterion Status
Semantic search scoring accounts for multiple relevant chunks ✅ Implemented via breadth boost formula
Documents with broader relevance rank higher than single-chunk matches ✅ Verified by comprehensive test
Performance remains acceptable ✅ Minimal overhead - in-memory sort of limited result set
Optional: expose scoring strategy as parameter ❌ Not implemented (optional criterion)

Summary: 3/3 required criteria met, 0/1 optional criteria implemented.


Architectural Assessment

The implementation follows a clean, well-documented approach:

  1. Scoring Formula: score = max_similarity * (1 + 0.3 * log10(matching_chunks))

    • Uses logarithmic scaling (diminishing returns) - prevents excessive boost for very high chunk counts
    • The 0.3 factor is a reasonable tuning parameter that balances breadth vs. similarity
    • Single-chunk documents get multiplier of 1.0 (no penalty)
    • 5-chunk documents get ~1.21x boost
    • 10-chunk documents get ~1.30x boost
  2. Database Query Enhancement: The SQL query is restructured to:

    • Calculate similarity per chunk in subquery
    • Filter by threshold before grouping
    • Aggregate max_similarity and count() per node
    • This is more correct than the previous approach (filters BEFORE grouping)
  3. API Extension: EmbeddingSearchResult now exposes:

    • score - composite ranking score
    • max_similarity - raw cosine similarity
    • matching_chunks - number of relevant chunks

Code Review Findings

🟢 Positive Observations

  1. Excellent Documentation (surreal_store.rs:4756-4772, embedding.rs:196-221)

    • Clear docstrings explaining the scoring formula with examples
    • Well-commented code explaining the algorithm rationale
  2. Comprehensive Testing (embedding_service_test.rs:699-829)

    • New test_multi_chunk_scoring_breadth_boost test validates the core behavior
    • Test verifies exact formula calculation, not just relative ordering
    • Existing tests updated to use new field names
  3. Clean API Evolution (embedding.rs:224-237)

    • Breaking change handled cleanly (old similarity field replaced with score, max_similarity, matching_chunks)
    • All consumers updated appropriately
  4. Performance Consideration (surreal_store.rs:4808)

    • KNN limit increased from 3x to 5x to capture more chunks per node
    • Re-sort in Rust is O(n log n) on a small result set - negligible overhead

🟡 Suggested Improvements

  1. [Improvement] surreal_store.rs:4754 - Consider making BREADTH_BOOST configurable

    • Currently hardcoded as const BREADTH_BOOST: f64 = 0.3
    • For future flexibility, this could be passed as a parameter or stored in config
    • Rationale: Different use cases may benefit from different boost factors (e.g., code search vs. document search)
    • Priority: Low - current value is well-reasoned
  2. Nit: surreal_store.rs:4850-4851 - Consider extracting breadth factor calculation

    let breadth_factor = 1.0 + Self::BREADTH_BOOST * (r.matching_chunks as f64).max(1.0).log10();
    • The .max(1.0) guard is defensive (prevents log10(0) = -inf)
    • Since matching_chunks comes from count() in SQL, it should always be >= 1
    • Could document this invariant more explicitly
  3. Nit: Frontend integration note

    • embeddings.rs (Tauri commands) returns only Vec<Node> without scores
    • The new rich scoring data (score, max_similarity, matching_chunks) is available in the backend but not exposed to frontend
    • Future enhancement: Consider returning Vec<(Node, SearchScore)> for UI relevance indicators

Security Review

✅ No security concerns identified:

  • No user input directly interpolated into SQL (uses bind parameters)
  • The knn_limit interpolation is safe (derived from validated limit parameter)
  • No new dependencies or external calls introduced

Performance Analysis

✅ Performance impact is minimal:

  • Database: Single query with subquery (similar complexity to before)
  • KNN limit: Increased from 3x to 5x - retrieves more candidates but still bounded
  • Post-processing: O(n log n) sort on small result set (typically < 100 items)
  • Memory: Additional fields add ~24 bytes per result (negligible)

The PR description confirms tests passed with acceptable performance.


Recommendation

✅ APPROVE

This is a well-designed enhancement that:

  1. Correctly implements all required acceptance criteria
  2. Follows established patterns and coding standards
  3. Includes comprehensive test coverage
  4. Has minimal performance impact
  5. Is well-documented

The change is a clear net positive for the codebase and improves semantic search quality by rewarding broader document relevance.


Principal Engineer AI Review

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review complete: APPROVE recommended. Clean, well-tested implementation of multi-chunk breadth scoring. All required acceptance criteria met. See detailed review in comments above.

Address code review feedback: document the invariant that matching_chunks
from SQL count() is always >= 1, and explain why the .max(1.0) guard exists
as defensive programming against edge cases.

Addresses reviewer recommendation from PR #781.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 23, 2025

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

✅ Addressed (1 recommendation)

Recommendation Action
Document matching_chunks >= 1 invariant ✅ Added clarifying comment explaining the SQL count() invariant and defensive .max(1.0) guard

⏭️ Skipped (2 recommendations)

Recommendation Reason
Make BREADTH_BOOST configurable Premature optimization - No current use case requires different values. The hardcoded 0.3 is well-reasoned and can be made configurable when an actual need arises.
Expose scores to frontend (Tauri commands) Scope creep - This is a separate feature enhancement that should be tracked as its own issue, not addressed in this PR focused on backend scoring improvements.

📊 Summary

  • Commits created: 1
  • Files changed: 1 (surreal_store.rs)
  • Tests: All passing (verified via pre-commit hooks)
  • Quality checks: ✅ Passed (cargo fmt, clippy, eslint, svelte-check)

Review feedback addressed by Claude Code

@malibio
malibio merged commit 0b17970 into main Dec 23, 2025
@malibio
malibio deleted the feature/issue-778-semantic-search-scoring branch December 23, 2025 16:19
malibio added a commit that referenced this pull request Feb 4, 2026
…781)

* feat: Enhance semantic search scoring with multi-chunk breadth boost (Issue #778)

Improves semantic search ranking by considering both chunk similarity and
breadth of relevance. Documents with multiple relevant chunks now rank
higher than those with a single high-scoring chunk.

## Changes

### Scoring Algorithm (Issue #778)
- New composite score formula: `max_similarity * (1 + 0.3 * log10(matching_chunks))`
- Single-chunk documents score unchanged (log10(1) = 0)
- Multi-chunk documents get breadth boost (e.g., 5 chunks → 1.21x multiplier)

### Updated `EmbeddingSearchResult` Model
- Added `score`: Composite relevance score (primary ranking)
- Added `max_similarity`: Best chunk similarity (raw cosine)
- Added `matching_chunks`: Count of chunks above threshold
- Removed `similarity` field (replaced by `score` and `max_similarity`)

### Enhanced SQL Query
- Subquery calculates per-chunk similarity before grouping
- Counts chunks exceeding threshold per node
- Results sorted by composite score in Rust (DB pre-sorts by max_similarity)
- Increased KNN limit from 3x to 5x to capture more chunks per node

### Test Coverage
- New `test_multi_chunk_scoring_breadth_boost` validates ranking behavior
- Updated existing tests to use new field names
- Verifies breadth boost formula correctness

## Example Results

| Document | Max Sim | Chunks | Score |
|----------|---------|--------|-------|
| Doc A    | 0.85    | 1      | 0.85  |
| Doc B    | 0.80    | 5      | 0.97  |

Doc B now ranks higher due to broader relevance.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* style: Apply cargo fmt formatting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* docs: Add clarifying comment for matching_chunks guard

Address code review feedback: document the invariant that matching_chunks
from SQL count() is always >= 1, and explain why the .max(1.0) guard exists
as defensive programming against edge cases.

Addresses reviewer recommendation from PR #781.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
…781)

* feat: Enhance semantic search scoring with multi-chunk breadth boost (Issue #778)

Improves semantic search ranking by considering both chunk similarity and
breadth of relevance. Documents with multiple relevant chunks now rank
higher than those with a single high-scoring chunk.

## Changes

### Scoring Algorithm (Issue #778)
- New composite score formula: `max_similarity * (1 + 0.3 * log10(matching_chunks))`
- Single-chunk documents score unchanged (log10(1) = 0)
- Multi-chunk documents get breadth boost (e.g., 5 chunks → 1.21x multiplier)

### Updated `EmbeddingSearchResult` Model
- Added `score`: Composite relevance score (primary ranking)
- Added `max_similarity`: Best chunk similarity (raw cosine)
- Added `matching_chunks`: Count of chunks above threshold
- Removed `similarity` field (replaced by `score` and `max_similarity`)

### Enhanced SQL Query
- Subquery calculates per-chunk similarity before grouping
- Counts chunks exceeding threshold per node
- Results sorted by composite score in Rust (DB pre-sorts by max_similarity)
- Increased KNN limit from 3x to 5x to capture more chunks per node

### Test Coverage
- New `test_multi_chunk_scoring_breadth_boost` validates ranking behavior
- Updated existing tests to use new field names
- Verifies breadth boost formula correctness

## Example Results

| Document | Max Sim | Chunks | Score |
|----------|---------|--------|-------|
| Doc A    | 0.85    | 1      | 0.85  |
| Doc B    | 0.80    | 5      | 0.97  |

Doc B now ranks higher due to broader relevance.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* style: Apply cargo fmt formatting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* docs: Add clarifying comment for matching_chunks guard

Address code review feedback: document the invariant that matching_chunks
from SQL count() is always >= 1, and explain why the .max(1.0) guard exists
as defensive programming against edge cases.

Addresses reviewer recommendation from PR #781.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
…781)

* feat: Enhance semantic search scoring with multi-chunk breadth boost (Issue #778)

Improves semantic search ranking by considering both chunk similarity and
breadth of relevance. Documents with multiple relevant chunks now rank
higher than those with a single high-scoring chunk.

## Changes

### Scoring Algorithm (Issue #778)
- New composite score formula: `max_similarity * (1 + 0.3 * log10(matching_chunks))`
- Single-chunk documents score unchanged (log10(1) = 0)
- Multi-chunk documents get breadth boost (e.g., 5 chunks → 1.21x multiplier)

### Updated `EmbeddingSearchResult` Model
- Added `score`: Composite relevance score (primary ranking)
- Added `max_similarity`: Best chunk similarity (raw cosine)
- Added `matching_chunks`: Count of chunks above threshold
- Removed `similarity` field (replaced by `score` and `max_similarity`)

### Enhanced SQL Query
- Subquery calculates per-chunk similarity before grouping
- Counts chunks exceeding threshold per node
- Results sorted by composite score in Rust (DB pre-sorts by max_similarity)
- Increased KNN limit from 3x to 5x to capture more chunks per node

### Test Coverage
- New `test_multi_chunk_scoring_breadth_boost` validates ranking behavior
- Updated existing tests to use new field names
- Verifies breadth boost formula correctness

## Example Results

| Document | Max Sim | Chunks | Score |
|----------|---------|--------|-------|
| Doc A    | 0.85    | 1      | 0.85  |
| Doc B    | 0.80    | 5      | 0.97  |

Doc B now ranks higher due to broader relevance.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* style: Apply cargo fmt formatting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* docs: Add clarifying comment for matching_chunks guard

Address code review feedback: document the invariant that matching_chunks
from SQL count() is always >= 1, and explain why the .max(1.0) guard exists
as defensive programming against edge cases.

Addresses reviewer recommendation from PR #781.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
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.

Enhance semantic search scoring to account for multiple matching chunks

1 participant