Skip to content

[score boosting] Only accept finite numbers#6092

Merged
coszio merged 4 commits intodevfrom
only-finite-numbers
Mar 4, 2025
Merged

[score boosting] Only accept finite numbers#6092
coszio merged 4 commits intodevfrom
only-finite-numbers

Conversation

@coszio
Copy link
Copy Markdown
Contributor

@coszio coszio commented Mar 3, 2025

We decided to only handle finite numbers in the formula evaluation.

With these changes, we now return a new bad request error when the evaluation leads to infinite or NaN.

Test cases were added to assert the errors

@coszio coszio added this to the score boosting milestone Mar 3, 2025
@coszio coszio requested review from generall and timvisee March 3, 2025 15:52
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 3, 2025

📝 Walkthrough

Walkthrough

This pull request modifies error handling and expression parsing for mathematical operations across several modules. Key changes include updating the by_zero_default field in the ParsedExpression::Div variant to allow it to be optional, eliminating the previous requirement for it to be wrapped in Some(). A new variant, NonFiniteNumber, has been added to the OperationError enum to handle cases where non-finite numbers are produced, and corresponding match arms have been introduced in the CollectionError type. The formula evaluation logic has been revised to return explicit errors for operations such as division, square root, power, and logarithm when non-finite results occur. Additionally, new constructor methods for power, square root, logarithm base 10, and natural logarithm have been added to the ParsedExpression enum.

Possibly related PRs

  • [score boosting] add more expressions #6054: This PR is related as it involves modifications to mathematical operations, specifically addressing the handling of the by_zero_default field in the ParsedExpression::Div variant and the introduction of new mathematical expressions.

Suggested Reviewers

  • generall
  • timvisee

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90ad6ce and 266c34d.

📒 Files selected for processing (1)
  • lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test-consistency
  • GitHub Check: test-consensus-compose
  • GitHub Check: test (macos-latest)
  • GitHub Check: test
  • GitHub Check: test (windows-latest)
  • GitHub Check: test
  • GitHub Check: test-consensus
  • GitHub Check: test
  • GitHub Check: test (ubuntu-latest)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs (1)

182-184: Consider adding finite check for exponential function.

While the exponential function typically produces finite results for most reasonable inputs, it can overflow for large input values. For consistency with other mathematical operations, consider adding a similar finite check for exp operations.

let value = self.eval_expression(parsed_expression, point_id)?;
- Ok(value.exp())
+ let exp_value = value.exp();
+ if exp_value.is_finite() {
+     Ok(exp_value)
+ } else {
+     Err(OperationError::NonFiniteNumber {
+         expression: format!("exp({value})"),
+     })
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0686d09 and 90ad6ce.

📒 Files selected for processing (5)
  • lib/api/src/grpc/conversions.rs (1 hunks)
  • lib/collection/src/operations/types.rs (1 hunks)
  • lib/segment/src/common/operation_error.rs (1 hunks)
  • lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs (4 hunks)
  • lib/segment/src/index/query_optimization/rescore_formula/parsed_formula.rs (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • lib/api/src/grpc/conversions.rs
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test (macos-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: test (windows-latest)
  • GitHub Check: test-consensus
  • GitHub Check: test (ubuntu-latest)
  • GitHub Check: test
  • GitHub Check: test
🔇 Additional comments (13)
lib/segment/src/common/operation_error.rs (1)

70-71: Good addition of a dedicated error type for non-finite numbers.

This new error variant will appropriately handle cases where mathematical operations produce non-finite results (infinity, NaN), making it easier to debug formula evaluation issues and provide better error messages to users.

lib/collection/src/operations/types.rs (1)

1247-1247: Appropriate error mapping for non-finite numbers.

This change correctly maps the new OperationError::NonFiniteNumber to CollectionError::BadInput, which is the right categorization since non-finite results are typically caused by invalid input data rather than system failures.

lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs (7)

147-149: Improved error handling for division by zero.

Instead of silently returning a default value for division by zero, the code now properly returns an error with a descriptive message when no default value is provided. This makes the behavior more explicit and helps identify formula issues.


161-167: Better error handling for square root of negative numbers.

This change ensures that non-finite results from square root operations (like trying to take the square root of a negative number) are properly handled with a descriptive error rather than returning NaN or infinity.


173-179: Enhanced error detection for power operations.

Power operations can produce non-finite results in various scenarios (negative base with non-integer exponent, large values causing overflow, etc.). This change ensures these cases are properly detected and reported with clear error messages.


187-194: Proper handling of logarithm domain errors.

Logarithm operations on non-positive numbers now properly return an error with a descriptive message instead of producing Infinity or NaN values that could silently propagate through calculations.


198-205: Consistent error handling for natural logarithm.

Similar to the base-10 logarithm, the natural logarithm function now properly handles non-finite results with clear error messages.


308-310: Updated test case for division with optional default.

The test case correctly reflects the API change where by_zero_default is now an Option<ScoreType> instead of ScoreType.


320-336: Good test coverage for non-finite error cases.

The added test cases ensure that non-finite error conditions are properly tested. This is essential for validating the new error handling behavior for mathematical operations.

lib/segment/src/index/query_optimization/rescore_formula/parsed_formula.rs (4)

41-41: Enhanced the Div expression to support optional default values.

Changing by_zero_default from ScoreType to Option<ScoreType> provides more flexibility in handling division by zero cases. It allows the caller to either specify a default value or request an error to be returned.


88-88: Updated constructor to use optional default value.

The new_div constructor method has been correctly updated to directly use the by_zero_default parameter without applying a default value.


100-118: Good addition of constructor methods for mathematical operations.

Adding constructor methods for power, square root, logarithm (base 10), and natural logarithm operations improves code readability and consistency. These methods encapsulate the boilerplate of wrapping expressions in Box.


81-89:

Details

✅ Verification successful

Verify existing callers of new_div are updated.

Make sure that all existing callers of new_div have been updated to handle the change from ScoreType to Option<ScoreType> for the by_zero_default parameter. This API change could cause compilation errors if not all callers are updated.


🏁 Script executed:

#!/bin/bash
# Search for all calls to new_div that might need updating
rg -p "new_div\(" --type rust

Length of output: 391


Caller Updates Verified – No Further Changes Needed

After running a repository-wide search, we confirmed that all existing callers of ParsedExpression::new_div have been updated to match the new signature using an Option<ScoreType>. The search revealed calls in the following files:

  • lib/collection/src/operations/universal_query/formula.rs (line 89)
  • lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs (lines 308 and 326)

Please review these locations to ensure the optional parameter is correctly passed (e.g., using Some(...) or None as appropriate). No additional modifications appear necessary.

Comment thread lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs Outdated
@coszio coszio merged commit 6873ed6 into dev Mar 4, 2025
@coszio coszio deleted the only-finite-numbers branch March 4, 2025 19:25
timvisee pushed a commit that referenced this pull request Mar 21, 2025
* return error for non-finite numbers in expression

* no internal default for division by zero

* add tests

* review suggestions
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.

2 participants