Skip to content

Fix semantic search threshold to filter by composite score (#787) - #822

Merged
malibio merged 2 commits into
mainfrom
feature/issue-787-semantic-search-composite-threshold
Jan 26, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-787-semantic-search-composite-threshold

Conversation

@malibio

@malibio malibio commented Jan 26, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Fix threshold filtering to use composite score instead of raw similarity
  • Move composite score calculation into SQL using math::log10
  • Remove Rust-side breadth factor calculation and re-sorting
  • Add test case demonstrating the fix

Problem Solved

The semantic search threshold parameter was filtering based on raw cosine similarity, but users see a composite score that includes breadth boost for multi-chunk matching. This caused confusing behavior where documents with composite score above the threshold could be filtered out.

Example scenario (before fix):

  1. Document has raw max_similarity of 0.68 but matches in 3 chunks
  2. Composite score = 0.68 × (1 + 0.3 × log10(3)) ≈ 0.78
  3. User sets threshold to 0.7, expecting documents with score > 0.7
  4. Document was NOT returned (raw 0.68 < 0.7) ❌

After fix:

  • Document IS returned (composite 0.78 > 0.7) ✅

Changes

packages/core/src/db/surreal_store.rs

  • Updated SQL query to calculate composite score using math::log10
  • Changed filtering from WHERE similarity > $threshold to filter by composite score
  • Changed ordering from max_similarity to composite_score
  • Added composite_score field to RawSearchResult struct
  • Removed BREADTH_BOOST constant (now inlined in SQL as 0.3)
  • Simplified Rust code to use SQL-calculated composite score directly
  • Removed Rust-side re-sorting (SQL already sorts by composite_score)

packages/core/tests/embedding_service_test.rs

  • Added test_threshold_filters_by_composite_score_not_raw_similarity test

Test Plan

  • All 691 Rust tests pass
  • All 23 embedding service tests pass
  • New test verifies the fix: document with raw similarity ~0.68 and composite score ~0.82 is returned with threshold between them
  • Clippy passes with no warnings
  • Formatting passes

Test Results

Baseline: Rust: 691 passed, Frontend: 3468 passed
After changes: Rust: 691 passed, Frontend: 3468 passed (no regressions)

Closes #787

🤖 Generated with Claude Code

Previously, the threshold parameter filtered results based on raw cosine
similarity, but users saw composite scores (which include breadth boost).
This caused confusing behavior where documents with composite score above
the threshold could be filtered out.

Changes:
- Move composite score calculation into SQL using math::log10
- Filter by composite score instead of raw similarity
- Sort by composite score in SQL (remove Rust-side re-sorting)
- Remove BREADTH_BOOST constant (now inlined in SQL)
- Add test demonstrating the fix

Example: A document with raw similarity 0.68 and 3 matching chunks has
composite score ~0.78. With threshold 0.7, it now IS returned (composite
0.78 > 0.7) instead of being filtered out (raw 0.68 < 0.7).

Closes #787

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

malibio commented Jan 26, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: Fix Semantic Search Threshold to Filter by Composite Score (#787)

Review Type: Initial Review
Reviewer: Principal Engineer (Claude Code)
Branch: feature/issue-787-semantic-search-composite-threshold


Summary

This PR addresses a user-facing inconsistency in semantic search where the threshold parameter filtered by raw cosine similarity, but users observed composite scores (which include breadth boost). The fix correctly moves the composite score calculation into SQL, ensuring threshold filtering matches user expectations.

Verdict: APPROVE

The implementation is clean, well-documented, and correctly addresses the issue. The code follows project standards and improves both maintainability and correctness.


Requirements Validation (Issue #787)

Criterion Status
Composite score calculated in SQL using math::log10 ✅
Threshold filters by composite score, not raw similarity ✅
Documents with composite score > threshold are returned ✅
Remove Rust-side breadth factor calculation (SQL does it) ✅
Remove Rust-side re-sorting (SQL already sorts by composite_score) ✅
Existing tests updated to reflect new behavior ✅
Add test case demonstrating the fix ✅

All acceptance criteria satisfied.


Findings

Critical Issues

None.

Suggested Improvements

1. [Improvement] Redundant Composite Score Calculation in WHERE Clause

File: packages/core/src/db/surreal_store.rs:4181

The composite score is calculated twice: once in the SELECT (line 4166) and again in the WHERE clause (line 4181):

-- Line 4166: SELECT clause
max_similarity * (1.0 + 0.3 * math::log10(matching_chunks)) AS composite_score

-- Line 4181: WHERE clause (duplicate calculation)
WHERE max_similarity * (1.0 + 0.3 * math::log10(matching_chunks)) > $threshold

Principle: DRY (Don't Repeat Yourself)

Recommendation: This is a known SurrealDB limitation (no HAVING clause, cannot reference aliases in WHERE). The current implementation is the correct workaround. Consider adding a brief comment explaining this is intentional due to SurrealDB limitations:

// Note: composite_score calculated twice because SurrealDB doesn't support
// referencing SELECT aliases in WHERE clause (no HAVING support)
WHERE max_similarity * (1.0 + 0.3 * math::log10(matching_chunks)) > $threshold

Severity: Nit - the existing comment at line 4143-4144 already explains this. This is optional polish.

Nitpicks

Nit 1: Magic Number Documentation

File: packages/core/src/db/surreal_store.rs:4153

The comment says BREADTH_BOOST = 0.3 is inlined in SQL (previously was a Rust constant) which is good. However, the value 0.3 appears 3 times in the SQL query (lines 4166, 4181, and referenced in docs).

Consider adding a note about keeping these synchronized:

// BREADTH_BOOST = 0.3 inlined in SQL (appears at lines: SELECT composite_score, WHERE clause)
// If changing this value, update both occurrences

This is purely optional and the current implementation is acceptable.


Code Quality Assessment

Strengths

  1. Excellent Documentation: The docstrings are comprehensive, including the threshold behavior explanation and concrete examples (lines 4098-4108).

  2. Clean Refactoring: Removed BREADTH_BOOST constant and Rust-side calculations, reducing code complexity while maintaining behavior.

  3. Well-Structured SQL: The nested subquery approach is clear:

    • Inner: KNN search for candidate chunks
    • Middle: GROUP BY node with aggregates
    • Outer: Calculate composite score and filter
  4. Comprehensive Test: The new test (test_threshold_filters_by_composite_score_not_raw_similarity) is thorough:

    • Clear test setup with calculated similarity values
    • Verifies formula correctness
    • Tests the exact edge case that motivated the issue
    • Excellent inline documentation explaining the math
  5. Proper Issue Linking: Both code comments and commit message properly reference issues Enhance semantic search scoring to account for multiple matching chunks #778 and Fix semantic search threshold to filter by composite score instead of raw similarity #787.

Architecture

The design decision to move composite score calculation to SQL is sound:

  • Single source of truth for score calculation
  • Eliminates inconsistency between filtering and display
  • Reduces Rust-side complexity
  • Database handles both filtering and sorting efficiently

Security Assessment

No security concerns. The query uses parameterized bindings ($query_vector, $threshold, $limit) which prevents SQL injection.


Performance Assessment

The change is performance-neutral or slightly positive:

  • Removes Rust-side sort_by operation (line 4205-4210 in old code)
  • Database now handles sorting as part of query execution
  • One additional subquery level, but SurrealDB should optimize this

The knn_limit = limit * 5 strategy remains appropriate for capturing multiple chunks per node.


Test Coverage

New test added: test_threshold_filters_by_composite_score_not_raw_similarity

  • Located at packages/core/tests/embedding_service_test.rs:840-965
  • Directly tests the bug scenario from the issue
  • Verifies both formula correctness and threshold behavior

Existing tests: The PR confirms all 691 Rust tests pass, indicating no regressions.


Final Recommendation

APPROVE

This is a high-quality fix that:

  1. Correctly addresses the user-facing bug
  2. Simplifies the codebase by removing Rust-side calculations
  3. Includes comprehensive documentation and testing
  4. Follows project standards and conventions

The implementation is a net positive improvement to code health. The minor suggestions above are optional polish and do not block merging.


Reviewed using the Pragmatic Quality Framework
Co-Authored-By: Claude Opus 4.5 [email protected]

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

Code review completed. Recommendation: APPROVE. Clean implementation that correctly addresses Issue #787. All acceptance criteria met, comprehensive test coverage, and well-documented changes. See detailed review comment above.

Address code review suggestion by restructuring the nested subquery
to calculate composite_score once and filter on it in an outer query.

**Previous approach (duplicated expression):**
- Calculate composite_score in SELECT clause
- Repeat same calculation in WHERE clause (SurrealDB limitation)

**New approach (no duplication):**
- Add 4th nesting level to separate calculation from filtering
- Level 1: KNN search for candidate chunks
- Level 2: GROUP BY node with aggregates (max_similarity, matching_chunks)
- Level 3: Calculate composite_score from aggregates (defined once)
- Level 4: Filter by composite_score > threshold (references alias)

This works because SurrealDB allows referencing aliases from subqueries
in outer WHERE clauses (per GitHub Discussion #1434).

All embedding tests pass including test_knn_search_respects_threshold.

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

malibio commented Jan 26, 2026

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

🟢 SQL Duplication Eliminated

Commit: 230649c

Restructured the semantic search SQL query to eliminate the duplicate composite score calculation.

Before (3 levels, duplicated expression):

SELECT * FROM (
    SELECT node, max_similarity, matching_chunks,
           max_similarity * (1.0 + 0.3 * math::log10(matching_chunks)) AS composite_score  -- ①
    FROM (...)
    WHERE max_similarity * (1.0 + 0.3 * math::log10(matching_chunks)) > $threshold  -- ② DUPLICATE
)

After (4 levels, single definition):

SELECT * FROM (
    SELECT * FROM (
        SELECT node, max_similarity, matching_chunks,
               max_similarity * (1.0 + 0.3 * math::log10(matching_chunks)) AS composite_score  -- defined once
        FROM (...)
    )
    WHERE composite_score > $threshold  -- references alias from inner query
)

Why this works: SurrealDB allows referencing aliases from subqueries in outer WHERE clauses (per GitHub Discussion #1434).

Tests: All embedding tests pass including test_knn_search_respects_threshold.

@malibio
malibio merged commit ec9dfde into main Jan 26, 2026
@malibio
malibio deleted the feature/issue-787-semantic-search-composite-threshold branch January 26, 2026 11:56
malibio added a commit that referenced this pull request Feb 4, 2026
* Fix semantic search threshold to filter by composite score (Issue #787)

Previously, the threshold parameter filtered results based on raw cosine
similarity, but users saw composite scores (which include breadth boost).
This caused confusing behavior where documents with composite score above
the threshold could be filtered out.

Changes:
- Move composite score calculation into SQL using math::log10
- Filter by composite score instead of raw similarity
- Sort by composite score in SQL (remove Rust-side re-sorting)
- Remove BREADTH_BOOST constant (now inlined in SQL)
- Add test demonstrating the fix

Example: A document with raw similarity 0.68 and 3 matching chunks has
composite score ~0.78. With threshold 0.7, it now IS returned (composite
0.78 > 0.7) instead of being filtered out (raw 0.68 < 0.7).

Closes #787

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

* Refactor semantic search SQL to eliminate composite score duplication

Address code review suggestion by restructuring the nested subquery
to calculate composite_score once and filter on it in an outer query.

**Previous approach (duplicated expression):**
- Calculate composite_score in SELECT clause
- Repeat same calculation in WHERE clause (SurrealDB limitation)

**New approach (no duplication):**
- Add 4th nesting level to separate calculation from filtering
- Level 1: KNN search for candidate chunks
- Level 2: GROUP BY node with aggregates (max_similarity, matching_chunks)
- Level 3: Calculate composite_score from aggregates (defined once)
- Level 4: Filter by composite_score > threshold (references alias)

This works because SurrealDB allows referencing aliases from subqueries
in outer WHERE clauses (per GitHub Discussion #1434).

All embedding tests pass including test_knn_search_respects_threshold.

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

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
* Fix semantic search threshold to filter by composite score (Issue #787)

Previously, the threshold parameter filtered results based on raw cosine
similarity, but users saw composite scores (which include breadth boost).
This caused confusing behavior where documents with composite score above
the threshold could be filtered out.

Changes:
- Move composite score calculation into SQL using math::log10
- Filter by composite score instead of raw similarity
- Sort by composite score in SQL (remove Rust-side re-sorting)
- Remove BREADTH_BOOST constant (now inlined in SQL)
- Add test demonstrating the fix

Example: A document with raw similarity 0.68 and 3 matching chunks has
composite score ~0.78. With threshold 0.7, it now IS returned (composite
0.78 > 0.7) instead of being filtered out (raw 0.68 < 0.7).

Closes #787

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

* Refactor semantic search SQL to eliminate composite score duplication

Address code review suggestion by restructuring the nested subquery
to calculate composite_score once and filter on it in an outer query.

**Previous approach (duplicated expression):**
- Calculate composite_score in SELECT clause
- Repeat same calculation in WHERE clause (SurrealDB limitation)

**New approach (no duplication):**
- Add 4th nesting level to separate calculation from filtering
- Level 1: KNN search for candidate chunks
- Level 2: GROUP BY node with aggregates (max_similarity, matching_chunks)
- Level 3: Calculate composite_score from aggregates (defined once)
- Level 4: Filter by composite_score > threshold (references alias)

This works because SurrealDB allows referencing aliases from subqueries
in outer WHERE clauses (per GitHub Discussion #1434).

All embedding tests pass including test_knn_search_respects_threshold.

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

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
* Fix semantic search threshold to filter by composite score (Issue #787)

Previously, the threshold parameter filtered results based on raw cosine
similarity, but users saw composite scores (which include breadth boost).
This caused confusing behavior where documents with composite score above
the threshold could be filtered out.

Changes:
- Move composite score calculation into SQL using math::log10
- Filter by composite score instead of raw similarity
- Sort by composite score in SQL (remove Rust-side re-sorting)
- Remove BREADTH_BOOST constant (now inlined in SQL)
- Add test demonstrating the fix

Example: A document with raw similarity 0.68 and 3 matching chunks has
composite score ~0.78. With threshold 0.7, it now IS returned (composite
0.78 > 0.7) instead of being filtered out (raw 0.68 < 0.7).

Closes #787

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

* Refactor semantic search SQL to eliminate composite score duplication

Address code review suggestion by restructuring the nested subquery
to calculate composite_score once and filter on it in an outer query.

**Previous approach (duplicated expression):**
- Calculate composite_score in SELECT clause
- Repeat same calculation in WHERE clause (SurrealDB limitation)

**New approach (no duplication):**
- Add 4th nesting level to separate calculation from filtering
- Level 1: KNN search for candidate chunks
- Level 2: GROUP BY node with aggregates (max_similarity, matching_chunks)
- Level 3: Calculate composite_score from aggregates (defined once)
- Level 4: Filter by composite_score > threshold (references alias)

This works because SurrealDB allows referencing aliases from subqueries
in outer WHERE clauses (per GitHub Discussion #1434).

All embedding tests pass including test_knn_search_respects_threshold.

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.

Fix semantic search threshold to filter by composite score instead of raw similarity

1 participant