Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport PR #2751 to release/v1.7 for Add rust-agent-qbg #2790

Merged

Conversation

vdaas-ci
Copy link
Collaborator

@vdaas-ci vdaas-ci commented Dec 25, 2024

Description

Related Issue

Versions

  • Vald Version: v1.7.14
  • Go Version: v1.23.3
  • Rust Version: v1.82.0
  • Docker Version: v27.3.1
  • Kubernetes Version: v1.31.2
  • Helm Version: v3.16.2
  • NGT Version: v2.3.4
  • Faiss Version: v1.9.0

Checklist

Special notes for your reviewer

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Introduced a new library for managing Quantized Binary Graph (QBG) construction and indexing.
    • Added functionality for creating and manipulating properties and indices related to QBG, including robust parameter management and lifecycle operations.
  • Bug Fixes
    • Enhanced error handling in index operations.
  • Documentation
    • Added comprehensive documentation for new classes and methods related to QBG.
  • Tests
    • Implemented tests to ensure the functionality of creating, appending, and searching indices.
  • Chores
    • Added a new GitHub Actions workflow for automating unit tests for the Rust project.
    • Updated the Makefile to include a target for running Rust tests.
    • Expanded workspace configuration to include the new qbg library.

* add rust-agent-qbg

* add unit-test-rust.yaml

---------

Signed-off-by: datelier <[email protected]>
Copy link
Contributor

coderabbitai bot commented Dec 25, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive implementation of a Rust-based QBG (Quantized Binary Graph) library with supporting infrastructure. The changes include adding a new GitHub Actions workflow for Rust unit testing, creating a Rust package for QBG algorithms, implementing C++ interoperability through the cxx crate, and integrating the new library into the project's workspace configuration. The implementation provides a robust interface for managing properties, building indices, and performing search operations on quantized graph data structures.

Changes

File Change Summary
.github/workflows/unit-test-rust.yaml New GitHub Actions workflow for running Rust unit tests
Makefile.d/test.mk Added new target .PHONY: test/rust/qbg for running Rust package tests
rust/Cargo.toml Added "libs/algorithms/qbg" to workspace members
rust/libs/algorithm/Cargo.toml Added qbg dependency with path reference
rust/libs/algorithms/qbg/Cargo.toml New package configuration with dependencies like anyhow, cxx
rust/libs/algorithms/qbg/build.rs Build script for configuring C++ library integration
rust/libs/algorithms/qbg/src/input.cpp C++ implementation of Property and Index classes
rust/libs/algorithms/qbg/src/input.h Header file defining SearchResult, Property, and Index structures
rust/libs/algorithms/qbg/src/lib.rs Rust FFI module for interacting with C++ QBG library

Sequence Diagram

sequenceDiagram
    participant Rust
    participant CxxBridge
    participant CPP
    participant NGT

    Rust->>CxxBridge: Create Property
    CxxBridge->>CPP: Initialize QBG Construction Parameters
    Rust->>CxxBridge: Configure Property Settings
    CxxBridge->>CPP: Set Dimensions, Subvectors

    Rust->>CxxBridge: Create Index
    CxxBridge->>CPP: Open/Build Index
    CPP->>NGT: Interact with NGT Library

    Rust->>CxxBridge: Perform Search
    CxxBridge->>CPP: Execute Search Operation
    CPP->>NGT: Query Index
    NGT-->>CPP: Return Search Results
    CPP-->>CxxBridge: Provide Search Results
    CxxBridge-->>Rust: Return Search Results
Loading

Possibly related PRs

Suggested Labels

type/feature, priority/medium, size/XXXL, area/agent/core/ngt, area/agent/core/faiss, area/sidecar, area/tools/cli/loadtest, area/discoverer, area/manager/index, area/gateway/lb, area/gateway/filter, area/gateway/mirror, area/index/job/correction, area/index/job/creation, area/index/job/save, area/index/job/readreplica

Suggested Reviewers

  • hlts2
  • vankichi
  • kmrmt

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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

Deploying vald with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3c8b68c
Status: ✅  Deploy successful!
Preview URL: https://18eb5ea8.vald.pages.dev
Branch Preview URL: https://backport-release-v1-7-featur-f4u5.vald.pages.dev

View logs

@vdaas-ci
Copy link
Collaborator Author

[CHATOPS:HELP] ChatOps commands.

  • 🙆‍♀️ /approve - approve
  • 🍱 /format - format codes and add licenses
  • /gen-test - generate test codes
  • 🏷️ /label - add labels
  • 🔚 2️⃣ 🔚 /label actions/e2e-deploy - run E2E deploy & integration test

Copy link
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: 2

🧹 Nitpick comments (7)
rust/libs/algorithms/qbg/src/input.cpp (2)

210-225: Parameter validation is missing for path correctness.

While opening or creating an index, user-provided file paths may be invalid or malicious. Currently, the code only handles library-level or file-level errors. Consider adding param checks (e.g., preventing empty strings) or sanitizing path inputs to prevent unexpected behaviors.


390-404: Potential dangling pointer from get_object.

get_object returns a raw pointer that references data owned by the underlying C++ library. Storing or modifying this pointer beyond its immediate use can be risky. Consider copying the data or returning a safe wrapper object to avoid unexpected invalidation.

rust/libs/algorithms/qbg/src/lib.rs (1)

382-388: Be cautious with slice lifetime in get_object.

The returned slice is built from a raw pointer and dimension. If the underlying memory is freed or changed by C++ after this call, the slice can become invalid. Usually, copying into a Rust-owned buffer is safer.

rust/libs/algorithms/qbg/build.rs (1)

16-35: Consider environment detection for library paths.

Hardcoding /usr/local/lib might be limiting on some systems. If possible, consider letting library search paths be set via environment variables or build arguments. This will make the build more portable across diverse environments.

rust/libs/algorithms/qbg/src/input.h (1)

92-114: Index class manages raw pointer effectively, but consider RAII-friendly design.

The class uses a void* for the index and frees it using specific library calls. If the code grows more complex or requires safe concurrency, adopting a wrapper or more modern RAII approach can reduce risk of leaks and simplify error handling.

rust/libs/algorithms/qbg/Cargo.toml (1)

26-27: Review build dependency configuration.

The miette crate with fancy feature seems unnecessary as a build dependency since it's typically used for runtime error reporting. Consider:

  1. Moving it to regular dependencies if needed for runtime
  2. Removing it if not actively used in build.rs
.github/workflows/unit-test-rust.yaml (1)

45-51: Enhance the workflow configuration

  1. Add a newline at the end of file
  2. Consider adding these improvements:
    • Cache Rust dependencies using actions/cache
    • Upload test results as artifacts
    • Add timeout limits for the test job

Apply this diff to implement the suggestions:

       - name: Set Git config
         run: |
           git config --global --add safe.directory ${GITHUB_WORKSPACE}
+      - uses: actions/cache@v3
+        with:
+          path: |
+            ~/.cargo/registry
+            ~/.cargo/git
+            rust/target
+          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
       - name: Run tests for Rust / gotestfmt
         run: |
           TEST_RESULT_DIR=${GITHUB_WORKSPACE} make test/rust/qbg
+        timeout-minutes: 10
+      - name: Upload test results
+        if: always()
+        uses: actions/upload-artifact@v3
+        with:
+          name: rust-test-results
+          path: ${{ github.workspace }}/TEST_RESULT_DIR
+
🧰 Tools
🪛 yamllint (1.35.1)

[error] 51-51: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a989576 and 3c8b68c.

⛔ Files ignored due to path filters (1)
  • rust/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • .github/workflows/unit-test-rust.yaml (1 hunks)
  • Makefile.d/test.mk (1 hunks)
  • rust/Cargo.toml (1 hunks)
  • rust/libs/algorithm/Cargo.toml (1 hunks)
  • rust/libs/algorithms/qbg/Cargo.toml (1 hunks)
  • rust/libs/algorithms/qbg/build.rs (1 hunks)
  • rust/libs/algorithms/qbg/src/input.cpp (1 hunks)
  • rust/libs/algorithms/qbg/src/input.h (1 hunks)
  • rust/libs/algorithms/qbg/src/lib.rs (1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/unit-test-rust.yaml

23-23: could not parse as YAML: yaml: line 23: did not find expected '-' indicator

(syntax-check)

🪛 yamllint (1.35.1)
.github/workflows/unit-test-rust.yaml

[warning] 24-24: wrong indentation: expected 6 but found 5

(indentation)


[error] 25-25: syntax error: expected , but found ''

(syntax)


[error] 51-51: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (14)
rust/libs/algorithms/qbg/src/input.cpp (3)

27-31: Destructor logic looks correct for cleanup.

The destructor consistently releases both qbg_construction_parameters and qbg_build_parameters. Ensure no further usage of these pointers happens outside the destructor to avoid undefined behavior.


43-60: Repeated re-initialization might overwrite prior settings.

Calling qbg_initialize_construction_parameters again in this setter resets all previously set fields, which might be intentional. If partial updates are needed, consider removing the re-initialization or offering a separate method to preserve previously set values.


336-388: Zero search results trigger a runtime error.

Returning zero results is not always an error case. Some queries might not match anything. Verify whether rsize == 0 truly indicates an error or if returning an empty result set is more appropriate. Throwing an exception may block valid use cases where an empty result is acceptable.

rust/libs/algorithms/qbg/src/lib.rs (3)

16-106: FFI declarations look consistent with the C++ header.

The bridging definitions correctly match the C++ method signatures. The usage of Pin<&mut ...> and UniquePtr is appropriate for safe FFI interactions, preventing accidental moves of pinned data.


109-126: Property struct wraps the C++ resource effectively.

The Property struct is storing UniquePtr<ffi::Property> responsibly. Methods like get_property() use pin_mut() correctly to avoid accidental reallocation or moves. Good practice for bridging C++ and Rust.


374-380: Efficient search result mapping.

Mapping the FFI’s search results into a native Rust Vec<(u32, f32)> is a clear approach. This code is easy to maintain and leverages Rust's iteration safely. Good job.

rust/libs/algorithms/qbg/src/input.h (1)

23-30: Struct SearchResult is straightforward and safe.

Returning a simple struct with an ID and distance is understandable. The inline getters are trivial, but effective. This structure is well-defined for its purpose.

Makefile.d/test.mk (1)

287-296: Rust test target clarifies QBG tests well.

The added .PHONY: test/rust/qbg target is explicit about which tests to run for QBG. The removal of the index directory ensures a clean slate for each test phase.

rust/Cargo.toml (1)

24-24: LGTM! Workspace member addition follows conventions.

The new QBG algorithm package is properly integrated into the workspace following the established pattern for algorithm libraries.

rust/libs/algorithm/Cargo.toml (1)

25-25: LGTM! Dependency addition follows conventions.

The QBG dependency is properly configured with consistent versioning and path structure matching other algorithm dependencies.

rust/libs/algorithms/qbg/Cargo.toml (2)

29-29: Add test dependencies for unimplemented functions.

The empty [dev-dependencies] section and PR objectives mentioning unimplemented functions (_as_uint8 and _as_float16) suggest a need for test coverage. Consider adding test dependencies to support implementation of these functions.

Would you like me to suggest appropriate test dependencies and example test cases for the unimplemented functions?


23-23: Verify C++20 compatibility with NGT.

Since this is a backport to release/v1.7 and integrates with NGT v2.3.4, please verify that C++20 feature requirement is compatible with the target environments.

✅ Verification successful

Let me gather more information about NGT's C++ standard requirements.


Let me try a different approach to check NGT's C++ requirements.


Let me check the NGT version requirements and compatibility.


Let me check the NGT version requirements in the codebase.


Let me check the NGT version in the codebase.


Based on the findings, I can now provide a response about C++20 compatibility with NGT v2.3.4:

C++20 requirement is compatible with NGT v2.3.4 target environment

The codebase shows NGT v2.3.5 is used in the main branch, while this PR targets v2.3.4. Both versions are compatible with C++20 as:

  1. The build scripts explicitly set C++20 flags for NGT compilation
  2. NGT versions 2.3.x series support modern C++ standards
  3. The rust-ngt bindings are already configured to use C++20 features
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check NGT source for C++ standard requirements
rg -i "c\+\+|standard" $(fd -t f "CMakeLists.txt|\.cmake$")

Length of output: 71796


Script:

#!/bin/bash
# Check NGT source for C++ standard requirements in CMake files
fd -t f "CMakeLists.txt|\.cmake$" | xargs cat | grep -i "c++\|standard"

Length of output: 73


Script:

#!/bin/bash
# Check build files and source for C++ standard requirements
rg -i "std=c\+\+|CMAKE_CXX_STANDARD|CXX_STANDARD" 

Length of output: 201


Script:

#!/bin/bash
# Check NGT version requirements
rg -i "ngt.*version|version.*ngt" 

Length of output: 66975


Script:

#!/bin/bash
# Check NGT version requirements in code
rg -i "ngt.*version|version.*ngt|NGT_VERSION" 

Length of output: 66987


Script:

#!/bin/bash
# Check NGT version requirements in code
fd -t f "NGT_VERSION" | xargs cat

Length of output: 39

.github/workflows/unit-test-rust.yaml (2)

1-16: LGTM!

The license header and workflow name are properly formatted and follow best practices.


38-44: Verify test coverage for Rust QBG implementation

The workflow runs tests via the test/rust/qbg make target. Let's verify the test coverage configuration.

✅ Verification successful

Let me gather more information about the test coverage configuration.


Let me check one more thing about the test coverage configuration.


Test coverage appears adequate but could benefit from documentation

The Rust QBG implementation has comprehensive test coverage with four distinct test cases:

  • test_ffi_qbg: Tests FFI functionality
  • test_ffi_qbg_prebuilt: Tests pre-built FFI functionality
  • test_property: Tests property management
  • test_index: Tests index operations

The test execution is properly configured in the Makefile target test/rust/qbg with appropriate test filters and output settings. While there's no explicit coverage measurement tool configured (like tarpaulin), the test suite covers the main functional areas:

  • FFI interface
  • Property management
  • Index operations
  • Pre-built functionality

Suggestion: Consider adding test coverage measurement and documenting the test strategy in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the make target and test configuration

# Check the make target definition
fd -t f "test.mk" -x cat {} \; | grep -A 5 "test/rust/qbg"

# Check for test files in the Rust QBG implementation
fd -e rs -t f . rust/libs/algorithms/qbg/src -x echo "Test file: {}"

Length of output: 719


Script:

#!/bin/bash
# Check the test configuration in lib.rs
cat rust/libs/algorithms/qbg/src/lib.rs | grep -A 20 "#\[cfg(test)\]"

# Check Cargo.toml for test dependencies and coverage configuration
fd Cargo.toml -x cat {} \; | grep -A 10 "\[dev-dependencies\]"

Length of output: 1500


Script:

#!/bin/bash
# Check for test modules and test cases in lib.rs
rg "fn test_" rust/libs/algorithms/qbg/src/lib.rs -A 1

# Check if there's any tarpaulin or other coverage configuration
fd -t f ".*\.toml$" -x grep -l "coverage\|tarpaulin" {} \;

Length of output: 371

Comment on lines +19 to +25
Property::Property()
{
qbg_construction_parameters = new QBGConstructionParameters();
qbg_build_parameters = new QBGBuildParameters();
qbg_initialize_construction_parameters(qbg_construction_parameters);
qbg_initialize_build_parameters(qbg_build_parameters);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider safer memory ownership or smart pointers for better exception safety.

Currently, raw pointers are allocated and deallocated manually. If an exception occurs during construction, e.g., if new throws before finishing, the destructor may not be called, potentially leaking resources. Using smart pointers (e.g., std::unique_ptr) can improve exception safety and simplify memory management.

.github/workflows/unit-test-rust.yaml Show resolved Hide resolved
@kpango kpango merged commit e1f6a6b into release/v1.7 Dec 25, 2024
154 of 155 checks passed
@kpango kpango deleted the backport/release/v1.7/feature/agent/rust-agent-qbg branch December 25, 2024 12:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants