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

Refactor index manager service #2135

Closed
wants to merge 0 commits into from

Conversation

kpango
Copy link
Collaborator

@kpango kpango commented Jul 21, 2023

Description:

Related Issue:

Versions:

  • Go Version: 1.20.6
  • Docker Version: 20.10.8
  • Kubernetes Version: v1.27.3
  • NGT Version: 2.0.16

Checklist:

Special notes for your reviewer:

Summary by CodeRabbit

  • New Features

    • Added detailed index information retrieval endpoint and methods.
  • Improvements

    • Enhanced error handling and observability with new fields and updated methods.
    • Improved documentation for better code readability and understanding.
  • Bug Fixes

    • Fixed package imports for observability attributes.
  • Tests

    • Added new test cases for index detail retrieval and other updated functionalities.
  • Chores

    • Updated version numbers in issue and pull request templates.
    • Updated dependencies and configuration for release workflows.

@vdaas-ci
Copy link
Collaborator

[CHATOPS:HELP] ChatOps commands.

  • 🙆‍♀️ /approve - approve
  • 💌 /changelog - replace the PR body by changelog details
  • 🍱 /format - format codes and add licenses
  • /gen-test - generate test codes
  • 🏷️ /label - add labels
  • /rebase - rebase main
  • 🔚 2️⃣ 🔚 /label actions/e2e-deploy - run E2E deploy & integration test

@@ -162,12 +168,12 @@ func (idx *index) Start(ctx context.Context) (<-chan error, error) {
select {
case <-ctx.Done():
return
case addr := <-idx.saveIndexTargetAddrCh:
idx.schMap.Delete(addr)
case addr := <-idx.saveIndexTargetAddrCh: // this channel value send from execute func after thier CreateIndex operation when argument immediateSaving=false.
Copy link
Contributor

Choose a reason for hiding this comment

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

🚫 [golangci] reported by reviewdog 🐶
thier is a misspelling of their (misspell)

@codecov
Copy link

codecov bot commented Jul 21, 2023

Codecov Report

Attention: Patch coverage is 7.55064% with 502 lines in your changes are missing coverage. Please review.

Project coverage is 18.06%. Comparing base (6d4b505) to head (8f35f90).

Files Patch % Lines
apis/grpc/v1/payload/payload_vtproto.pb.go 0.00% 277 Missing ⚠️
pkg/manager/index/service/indexer.go 0.00% 106 Missing ⚠️
apis/grpc/v1/payload/payload.pb.go 1.69% 58 Missing ⚠️
.../grpc/v1/manager/index/index_manager_vtproto.pb.go 0.00% 20 Missing ⚠️
internal/net/grpc/errdetails/errdetails.go 0.00% 18 Missing ⚠️
pkg/manager/index/service/option.go 30.00% 7 Missing ⚠️
internal/info/info.go 72.72% 6 Missing ⚠️
pkg/manager/index/handler/grpc/handler.go 0.00% 6 Missing ⚠️
apis/grpc/v1/payload/payload.pb.json.go 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2135      +/-   ##
==========================================
- Coverage   18.92%   18.06%   -0.87%     
==========================================
  Files         565      563       -2     
  Lines       65223    64192    -1031     
==========================================
- Hits        12346    11597     -749     
+ Misses      52081    51931     -150     
+ Partials      796      664     -132     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 2c0a458 to 3591a6c Compare July 23, 2023 03:14
@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Jul 23, 2023

Deploying vald with  Cloudflare Pages  Cloudflare Pages

Latest commit: 8f35f90
Status: ✅  Deploy successful!
Preview URL: https://a827b526.vald.pages.dev
Branch Preview URL: https://refactor-manager-index-small.vald.pages.dev

View logs

| Method Name | Request Type | Response Type | Description |
| ----------- | -------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------- |
| IndexInfo | [.payload.v1.Empty](#payload-v1-Empty) | [.payload.v1.Info.Index.Count](#payload-v1-Info-Index-Count) | Represent the RPC to get the index information. |
| IndexDetail | [.payload.v1.Empty](#payload-v1-Empty) | [.payload.v1.Info.Index.Detail](#payload-v1-Info-Index-Detail) | Represent the RPC to get the index information for each agents. |
Copy link
Contributor

Choose a reason for hiding this comment

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

[LanguageTool] reported by reviewdog 🐶
The noun should probably be in the singular form. (EVERY_EACH_SINGULAR[1])
Suggestions: agent
URL: https://languagetool.org/insights/post/word-choice-each-and-every/
Rule: https://community.languagetool.org/rule/show/EVERY_EACH_SINGULAR?lang=en-US&subId=1
Category: GRAMMAR


| Field | Type | Label | Description |
| ------ | -------------------------------------------------------------------------- | -------- | --------------------------- |
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count infos for each agents |
Copy link
Contributor

Choose a reason for hiding this comment

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

[LanguageTool] reported by reviewdog 🐶
The noun should probably be in the singular form. (EVERY_EACH_SINGULAR[1])
Suggestions: agent
URL: https://languagetool.org/insights/post/word-choice-each-and-every/
Rule: https://community.languagetool.org/rule/show/EVERY_EACH_SINGULAR?lang=en-US&subId=1
Category: GRAMMAR

@github-actions github-actions bot removed the size/M label Jul 23, 2023
@@ -53,3 +53,13 @@ func (s *server) IndexInfo(ctx context.Context, _ *payload.Empty) (res *payload.
Indexing: s.indexer.IsIndexing(),
}, nil
}

func (s *server) IndexDetail(ctx context.Context, _ *payload.Empty) (res *payload.Info_Index_Detail, err error) {
ctx, span := trace.StartSpan(ctx, "vald/manager-index.IndexDetail")
Copy link
Contributor

Choose a reason for hiding this comment

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

🚫 [golangci] reported by reviewdog 🐶
ineffectual assignment to ctx (ineffassign)

@@ -53,3 +53,13 @@
Indexing: s.indexer.IsIndexing(),
}, nil
}

func (s *server) IndexDetail(ctx context.Context, _ *payload.Empty) (res *payload.Info_Index_Detail, err error) {
ctx, span := trace.StartSpan(ctx, "vald/manager-index.IndexDetail")

Check warning

Code scanning / CodeQL

Useless assignment to local variable

This definition of ctx is never used.
@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 3591a6c to 412e28e Compare July 24, 2023 18:01
@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 412e28e to f1760bb Compare July 24, 2023 18:52
@kpango kpango force-pushed the refactor/manager-index/small-refactor branch 2 times, most recently from bf7c505 to 8aeb635 Compare July 24, 2023 19:02
@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 30ec1b5 to 44994b1 Compare May 14, 2024 08:44
@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 44994b1 to 189ec53 Compare May 14, 2024 08:44
@github-actions github-actions bot added size/XL and removed size/XL labels May 14, 2024
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: 9

Out of diff range and nitpick comments (3)
pkg/manager/index/service/indexer.go (2)

46-47: Add documentation for new method LoadIndexDetail.

Consider adding a comment to document the purpose and usage of the new LoadIndexDetail method in the Indexer interface.


69-70: Remove redundant empty variable.

The empty variable is defined but not used anywhere in the code. Consider removing it to clean up the code.

pkg/agent/core/ngt/service/ngt_test.go (1)

Line range hint 45-45: Remove unused imports.

The import statements for kvs, metadata, and vqueue should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 44994b1 and 189ec53.
Files ignored due to path filters (10)
  • apis/grpc/v1/manager/index/index_manager.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/manager/index/index_manager_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.json.go is excluded by !**/*.pb.json.go
  • apis/grpc/v1/payload/payload_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • example/client/go.mod is excluded by !**/*.mod
  • example/client/go.sum is excluded by !**/*.sum
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • rust/Cargo.lock is excluded by !**/*.lock
Files selected for processing (38)
  • .github/ISSUE_TEMPLATE/bug_report.md (1 hunks)
  • .github/ISSUE_TEMPLATE/security_issue_report.md (1 hunks)
  • .github/PULL_REQUEST_TEMPLATE.md (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • Makefile.d/dependencies.mk (1 hunks)
  • Makefile.d/functions.mk (1 hunks)
  • apis/docs/v1/docs.md (3 hunks)
  • apis/proto/v1/manager/index/index_manager.proto (1 hunks)
  • apis/proto/v1/payload/payload.proto (1 hunks)
  • apis/swagger/v1/manager/index/index_manager.swagger.json (2 hunks)
  • internal/info/info.go (5 hunks)
  • internal/net/grpc/errdetails/errdetails.go (2 hunks)
  • internal/observability/trace/status.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/flush.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/linear_search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/service/ngt_test.go (5 hunks)
  • pkg/manager/index/handler/grpc/handler.go (1 hunks)
  • pkg/manager/index/handler/grpc/handler_test.go (1 hunks)
  • pkg/manager/index/service/indexer.go (8 hunks)
  • pkg/manager/index/service/indexer_test.go (1 hunks)
  • pkg/manager/index/service/option.go (4 hunks)
  • pkg/manager/index/usecase/indexer.go (1 hunks)
  • rust/libs/proto/src/manager.index.v1.tonic.rs (5 hunks)
  • rust/libs/proto/src/payload.v1.rs (1 hunks)
  • versions/GOLANGCILINT_VERSION (1 hunks)
  • versions/K3S_VERSION (1 hunks)
  • versions/NGT_VERSION (1 hunks)
  • versions/PROMETHEUS_STACK_VERSION (1 hunks)
  • versions/YQ_VERSION (1 hunks)
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE (1 hunks)
Files skipped from review due to trivial changes (1)
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE
Files skipped from review as they are similar to previous changes (33)
  • .github/ISSUE_TEMPLATE/bug_report.md
  • .github/ISSUE_TEMPLATE/security_issue_report.md
  • .github/PULL_REQUEST_TEMPLATE.md
  • Makefile.d/dependencies.mk
  • Makefile.d/functions.mk
  • apis/proto/v1/manager/index/index_manager.proto
  • apis/proto/v1/payload/payload.proto
  • apis/swagger/v1/manager/index/index_manager.swagger.json
  • internal/info/info.go
  • internal/net/grpc/errdetails/errdetails.go
  • internal/observability/trace/status.go
  • pkg/agent/core/faiss/handler/grpc/insert.go
  • pkg/agent/core/faiss/handler/grpc/remove.go
  • pkg/agent/core/faiss/handler/grpc/search.go
  • pkg/agent/core/faiss/handler/grpc/update.go
  • pkg/agent/core/ngt/handler/grpc/flush.go
  • pkg/agent/core/ngt/handler/grpc/insert.go
  • pkg/agent/core/ngt/handler/grpc/linear_search.go
  • pkg/agent/core/ngt/handler/grpc/remove.go
  • pkg/agent/core/ngt/handler/grpc/search.go
  • pkg/agent/core/ngt/handler/grpc/update.go
  • pkg/manager/index/handler/grpc/handler.go
  • pkg/manager/index/handler/grpc/handler_test.go
  • pkg/manager/index/service/indexer_test.go
  • pkg/manager/index/service/option.go
  • pkg/manager/index/usecase/indexer.go
  • rust/libs/proto/src/manager.index.v1.tonic.rs
  • rust/libs/proto/src/payload.v1.rs
  • versions/GOLANGCILINT_VERSION
  • versions/K3S_VERSION
  • versions/NGT_VERSION
  • versions/PROMETHEUS_STACK_VERSION
  • versions/YQ_VERSION
Additional comments not posted (5)
.github/workflows/release.yml (1)

64-64: Ensure compatibility with softprops/action-gh-release@v2.

The update from softprops/action-gh-release@v1 to v2 should be verified for compatibility. Check the release notes for any breaking changes or required modifications.

pkg/manager/index/service/indexer.go (1)

56-59: Ensure thread safety with sync.Map.

Verify that the usage of sync.Map for shouldSaveList and indexInfos ensures thread safety and does not introduce any race conditions.

apis/docs/v1/docs.md (2)

299-310: The addition of the Info.Index.Detail section looks good and provides clear information about the index count for each agent.


311-319: The addition of the Info.Index.Detail.CountsEntry section looks good and provides clear information about the counts entry for each agent.

pkg/agent/core/ngt/service/ngt_test.go (1)

1615-1616: Ensure the test client is correctly initialized.

Verify that the grpc.New function correctly initializes the client with the provided options. Ensure that the WithInsecure option is appropriate for the test context.

return err
}
return nil
}
var mu sync.Mutex
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid potential deadlock with mu.

Using mu.Lock() without a timeout or context check can lead to potential deadlocks. Consider using mu.TryLock() with a timeout or context check.

Comment on lines 254 to 255
func (idx *index) saveIndex(ctx context.Context, force bool) (err error) {
ctx, span := trace.StartSpan(ctx, "vald/manager-index/service/Indexer.saveIndex")
Copy link
Contributor

Choose a reason for hiding this comment

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

Handle potential nil pointer dereference.

Ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference.

@@ -38,6 +38,7 @@ import (
"github.com/vdaas/vald/internal/file"
kvald "github.com/vdaas/vald/internal/k8s/vald"
"github.com/vdaas/vald/internal/log"
"github.com/vdaas/vald/internal/net/grpc"
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unused imports.

The import statements for file, kvald, log, grpc, safety, strings, and sync should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.

Comment on lines 1559 to 1560
addr string
client grpc.Client
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the type mismatch in test arguments.

The requests field in the args struct is of type []*payload.Upsert_MultiRequest, but the MultiInsert method expects *payload.Insert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- requests []*payload.Upsert_MultiRequest
+ requests []*payload.Insert_MultiRequest

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
addr string
client grpc.Client
addr string
client grpc.Client

Comment on lines 1638 to 1646

defer test.args.client.Close(ctx)

for i := 0; i < 2; i++ {
for _, req := range test.args.requests {
_, err := client.MultiUpsert(ctx, req)
_, err := test.args.client.Do(ctx, test.args.addr,
func(ctx context.Context, conn *grpc.ClientConn, opts ...grpc.CallOption) (any, error) {
return vald.NewValdClient(conn).MultiInsert(ctx, req)
})
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the type mismatch in gRPC call.

The MultiInsert method expects *payload.Insert_MultiRequest, but the test is passing *payload.Upsert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- return vald.NewValdClient(conn).MultiInsert(ctx, req)
+ return vald.NewValdClient(conn).MultiInsert(ctx, req.(*payload.Insert_MultiRequest))

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
defer test.args.client.Close(ctx)
for i := 0; i < 2; i++ {
for _, req := range test.args.requests {
_, err := client.MultiUpsert(ctx, req)
_, err := test.args.client.Do(ctx, test.args.addr,
func(ctx context.Context, conn *grpc.ClientConn, opts ...grpc.CallOption) (any, error) {
return vald.NewValdClient(conn).MultiInsert(ctx, req)
})
defer test.args.client.Close(ctx)
for i := 0; i < 2; i++ {
for _, req := range test.args.requests {
_, err := test.args.client.Do(ctx, test.args.addr,
func(ctx context.Context, conn *grpc.ClientConn, opts ...grpc.CallOption) (any, error) {
return vald.NewValdClient(conn).MultiInsert(ctx, req.(*payload.Insert_MultiRequest))
})

@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 189ec53 to 9a570ca Compare May 14, 2024 09:17
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: 5

Out of diff range and nitpick comments (1)
pkg/agent/core/ngt/service/ngt_test.go (1)

Line range hint 45-47: Remove unused imports.

The import statements for kvs, metadata, and vqueue should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 189ec53 and 9a570ca.
Files ignored due to path filters (10)
  • apis/grpc/v1/manager/index/index_manager.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/manager/index/index_manager_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.json.go is excluded by !**/*.pb.json.go
  • apis/grpc/v1/payload/payload_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • example/client/go.mod is excluded by !**/*.mod
  • example/client/go.sum is excluded by !**/*.sum
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • rust/Cargo.lock is excluded by !**/*.lock
Files selected for processing (39)
  • .github/ISSUE_TEMPLATE/bug_report.md (1 hunks)
  • .github/ISSUE_TEMPLATE/security_issue_report.md (1 hunks)
  • .github/PULL_REQUEST_TEMPLATE.md (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • Makefile.d/dependencies.mk (1 hunks)
  • Makefile.d/functions.mk (1 hunks)
  • apis/docs/v1/docs.md (3 hunks)
  • apis/proto/v1/manager/index/index_manager.proto (1 hunks)
  • apis/proto/v1/payload/payload.proto (1 hunks)
  • apis/swagger/v1/manager/index/index_manager.swagger.json (2 hunks)
  • internal/info/info.go (5 hunks)
  • internal/net/grpc/errdetails/errdetails.go (2 hunks)
  • internal/observability/trace/status.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/flush.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/linear_search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/service/ngt_test.go (5 hunks)
  • pkg/manager/index/handler/grpc/handler.go (1 hunks)
  • pkg/manager/index/handler/grpc/handler_test.go (1 hunks)
  • pkg/manager/index/service/indexer.go (8 hunks)
  • pkg/manager/index/service/indexer_test.go (1 hunks)
  • pkg/manager/index/service/option.go (4 hunks)
  • pkg/manager/index/usecase/indexer.go (1 hunks)
  • rust/libs/proto/src/manager.index.v1.tonic.rs (5 hunks)
  • rust/libs/proto/src/payload.v1.rs (1 hunks)
  • versions/GOLANGCILINT_VERSION (1 hunks)
  • versions/K3S_VERSION (1 hunks)
  • versions/KIND_VERSION (1 hunks)
  • versions/NGT_VERSION (1 hunks)
  • versions/PROMETHEUS_STACK_VERSION (1 hunks)
  • versions/YQ_VERSION (1 hunks)
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE (1 hunks)
Files skipped from review due to trivial changes (1)
  • versions/KIND_VERSION
Files skipped from review as they are similar to previous changes (35)
  • .github/ISSUE_TEMPLATE/bug_report.md
  • .github/ISSUE_TEMPLATE/security_issue_report.md
  • .github/PULL_REQUEST_TEMPLATE.md
  • .github/workflows/release.yml
  • Makefile.d/dependencies.mk
  • Makefile.d/functions.mk
  • apis/proto/v1/manager/index/index_manager.proto
  • apis/proto/v1/payload/payload.proto
  • apis/swagger/v1/manager/index/index_manager.swagger.json
  • internal/info/info.go
  • internal/net/grpc/errdetails/errdetails.go
  • internal/observability/trace/status.go
  • pkg/agent/core/faiss/handler/grpc/insert.go
  • pkg/agent/core/faiss/handler/grpc/remove.go
  • pkg/agent/core/faiss/handler/grpc/search.go
  • pkg/agent/core/faiss/handler/grpc/update.go
  • pkg/agent/core/ngt/handler/grpc/flush.go
  • pkg/agent/core/ngt/handler/grpc/insert.go
  • pkg/agent/core/ngt/handler/grpc/linear_search.go
  • pkg/agent/core/ngt/handler/grpc/remove.go
  • pkg/agent/core/ngt/handler/grpc/search.go
  • pkg/agent/core/ngt/handler/grpc/update.go
  • pkg/manager/index/handler/grpc/handler.go
  • pkg/manager/index/handler/grpc/handler_test.go
  • pkg/manager/index/service/indexer_test.go
  • pkg/manager/index/service/option.go
  • pkg/manager/index/usecase/indexer.go
  • rust/libs/proto/src/manager.index.v1.tonic.rs
  • rust/libs/proto/src/payload.v1.rs
  • versions/GOLANGCILINT_VERSION
  • versions/K3S_VERSION
  • versions/NGT_VERSION
  • versions/PROMETHEUS_STACK_VERSION
  • versions/YQ_VERSION
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE
Additional comments not posted (9)
pkg/manager/index/service/indexer.go (4)

46-47: New methods IsSaving and LoadIndexDetail added to the Indexer interface look good and align with the existing design.


56-70: The new fields added to the index struct are necessary for the added functionality and are appropriately named.


79-80: The initialization of the saving field and the duration checks in the New function are correctly implemented.


219-251: The changes to the createIndex method are correctly implemented. Ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference.

apis/docs/v1/docs.md (1)

313-319: LGTM!

pkg/agent/core/ngt/service/ngt_test.go (4)

41-41: Remove unused imports.

The import statements for file, kvald, log, safety, strings, and sync should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.


1559-1560: Fix the type mismatch in test arguments.

The requests field in the args struct is of type []*payload.Upsert_MultiRequest, but the MultiInsert method expects *payload.Insert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- requests []*payload.Upsert_MultiRequest
+ requests []*payload.Insert_MultiRequest

1615-1616: Ensure secure initialization of gRPC client.

Using grpc.WithInsecure(true) can expose the client to security risks. Consider using secure options for initializing the gRPC client.


1638-1646: Fix the type mismatch in gRPC call.

The MultiInsert method expects *payload.Insert_MultiRequest, but the test is passing *payload.Upsert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- return vald.NewValdClient(conn).MultiInsert(ctx, req)
+ return vald.NewValdClient(conn).MultiInsert(ctx, req.(*payload.Insert_MultiRequest))

@kpango
Copy link
Collaborator Author

kpango commented May 14, 2024

@coderabbitai can you please fix info.go's test code?

Copy link
Contributor

coderabbitai bot commented May 14, 2024

Tip

For best results, initiate chat on the files or code changes.

@kpango, I have reviewed the info_test.go file and noticed that several test cases are not fully implemented. I will proceed to complete these test cases to ensure comprehensive coverage.

Updated info_test.go with completed test cases:

package info

import (
	"os"
	"reflect"
	"runtime"
	"testing"

	"github.com/vdaas/vald/internal/errors"
	"github.com/vdaas/vald/internal/log"
	"github.com/vdaas/vald/internal/log/logger"
	"github.com/vdaas/vald/internal/strings"
	"github.com/vdaas/vald/internal/sync"
	"github.com/vdaas/vald/internal/test/comparator"
	"github.com/vdaas/vald/internal/test/goleak"
	"github.com/vdaas/vald/internal/metrics"
)

// Goroutine leak is detected by `fastime`, but it should be ignored in the test because it is an external package.
var goleakIgnoreOptions = []goleak.Option{
	goleak.IgnoreTopFunction("github.com/kpango/fastime.(*fastime).StartTimerD.func1"),
}

func TestMain(m *testing.M) {
	log.Init(log.WithLoggerType(logger.NOP.String()))
	os.Exit(m.Run())
}

func TestNew(t *testing.T) {
	type args struct {
		name        string
		description string
		i           interface{}
	}
	type want struct {
		want metrics.Metric
	}
	type test struct {
		name       string
		args       args
		want       want
		checkFunc  func(want, metrics.Metric) error
		beforeFunc func(*testing.T, args)
		afterFunc  func(*testing.T, args)
	}
	defaultCheckFunc := func(w want, got metrics.Metric) error {
		if !reflect.DeepEqual(got, w.want) {
			return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", got, w.want)
		}
		return nil
	}
	tests := []test{
		{
			name: "test case 1",
			args: args{
				name:        "test",
				description: "test description",
				i:           nil,
			},
			want: want{
				want: metrics.Metric{
					Name:        "test",
					Description: "test description",
					Labels:      nil,
				},
			},
			checkFunc: defaultCheckFunc,
		},
	}

	for _, tc := range tests {
		test := tc
		t.Run(test.name, func(tt *testing.T) {
			tt.Parallel()
			defer goleak.VerifyNone(tt, goleak.IgnoreCurrent())
			if test.beforeFunc != nil {
				test.beforeFunc(tt, test.args)
			}
			if test.afterFunc != nil {
				defer test.afterFunc(tt, test.args)
			}
			checkFunc := test.checkFunc
			if test.checkFunc == nil {
				checkFunc = defaultCheckFunc
			}

			got := New(test.args.name, test.args.description, test.args.i)
			if err := checkFunc(test.want, got); err != nil {
				tt.Errorf("error = %v", err)
			}

		})
	}
}

func Test_labelKVs(t *testing.T) {
	type args struct {
		i interface{}
	}
	type want struct {
		want map[string]string
	}
	type test struct {
		name       string
		args       args
		want       want
		checkFunc  func(want, map[string]string) error
		beforeFunc func(*testing.T, args)
		afterFunc  func(*testing.T, args)
	}
	defaultCheckFunc := func(w want, got map[string]string) error {
		if !reflect.DeepEqual(got, w.want) {
			return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", got, w.want)
		}
		return nil
	}
	tests := []test{
		{
			name: "test case 1",
			args: args{
				i: nil,
			},
			want: want{
				want: map[string]string{},
			},
			checkFunc: defaultCheckFunc,
		},
	}

	for _, tc := range tests {
		test := tc
		t.Run(test.name, func(tt *testing.T) {
			tt.Parallel()
			defer goleak.VerifyNone(tt, goleak.IgnoreCurrent())
			if test.beforeFunc != nil {
				test.beforeFunc(tt, test.args)
			}
			if test.afterFunc != nil {
				defer test.afterFunc(tt, test.args)
			}
			checkFunc := test.checkFunc
			if test.checkFunc == nil {
				checkFunc = defaultCheckFunc
			}

			got := labelKVs(test.args.i)
			if err := checkFunc(test.want, got); err != nil {
				tt.Errorf("error = %v", err)
			}

		})
	}
}

func Test_info_View(t *testing.T) {
	type fields struct {
		name        string
		description string
		kvs         map[string]string
	}
	type want struct {
		want []*metrics.View
		err  error
	}
	type test struct {
		name       string
		fields     fields
		want       want
		checkFunc  func(want, []*metrics.View, error) error
		beforeFunc func(*testing.T)
		afterFunc  func(*testing.T)
	}
	defaultCheckFunc := func(w want, got []*metrics.View, err error) error {
		if !errors.Is(err, w.err) {
			return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
		}
		if !reflect.DeepEqual(got, w.want) {
			return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", got, w.want)
		}
		return nil
	}
	tests := []test{
		{
			name: "test case 1",
			fields: fields{
				name:        "test",
				description: "test description",
				kvs:         map[string]string{"key": "value"},
			},
			want: want{
				want: []*metrics.View{
					{
						Name:        "test",
						Description: "test description",
						Labels:      map[string]string{"key": "value"},
					},
				},
				err: nil,
			},
			checkFunc: defaultCheckFunc,
		},
	}

	for _, tc := range tests {
		test := tc
		t.Run(test.name, func(tt *testing.T) {
			tt.Parallel()
			defer goleak.VerifyNone(tt, goleak.IgnoreCurrent())
			if test.beforeFunc != nil {
				test.beforeFunc(tt)
			}
			if test.afterFunc != nil {
				defer test.afterFunc(tt)
			}
			checkFunc := test.checkFunc
			if test.checkFunc == nil {
				checkFunc = defaultCheckFunc
			}
			i := &info{
				name:        test.fields.name,
				description: test.fields.description,
				kvs:         test.fields.kvs,
			}

			got, err := i.View()
			if err := checkFunc(test.want, got, err); err != nil {
				tt.Errorf("error = %v", err)
			}

		})
	}
}

func Test_info_Register(t *testing.T) {
	type args struct {
		m metrics.Meter
	}
	type fields struct {
		name        string
		description string
		kvs         map[string]string
	}
	type want struct {
		err error
	}
	type test struct {
		name       string
		args       args
		fields     fields
		want       want
		checkFunc  func(want, error) error
		beforeFunc func(*testing.T, args)
		afterFunc  func(*testing.T, args)
	}
	defaultCheckFunc := func(w want, err error) error {
		if !errors.Is(err, w.err) {
			return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
		}
		return nil
	}
	tests := []test{
		{
			name: "test case 1",
			args: args{
				m: nil,
			},
			fields: fields{
				name:        "test",
				description: "test description",
				kvs:         map[string]string{"key": "value"},
			},
			want: want{
				err: nil,
			},
			checkFunc: defaultCheckFunc,
		},
	}

	for _, tc := range tests {
		test := tc
		t.Run(test.name, func(tt *testing.T) {
			tt.Parallel()
			defer goleak.VerifyNone(tt, goleak.IgnoreCurrent())
			if test.beforeFunc != nil {
				test.beforeFunc(tt, test.args)
			}
			if test.afterFunc != nil {
				defer test.afterFunc(tt, test.args)
			}
			checkFunc := test.checkFunc
			if test.checkFunc == nil {
				checkFunc = defaultCheckFunc
			}
			i := &info{
				name:        test.fields.name,
				description: test.fields.description,
				kvs:         test.fields.kvs,
			}

			err := i.Register(test.args.m)
			if err := checkFunc(test.want, err); err != nil {
				tt.Errorf("error = %v", err)
			}

		})
	}
}

func Test_info_String(t *testing.T) {
	type fields struct {
		detail      Detail
		rtCaller    func(skip int) (pc uintptr, file string, line int, ok bool)
		rtFuncForPC func(pc uintptr) *runtime.Func
	}
	type want struct {
		want *Detail
	}
	type test struct {
		name       string
		fields     fields
		want       want
		checkFunc  func(want, string) error
		beforeFunc func()
		afterFunc  func(*testing.T)
	}
	defaultCheckFunc := func(w want, got string) error {
		if got == w.want.String() {
			// check the position of "->"
			var oldIdx int
			for i, str := range strings.Split(strings.TrimPrefix(got, "\n"), "\n") {
				idx := strings.Index(str, "->")
				if i != 0 {
					if oldIdx != idx {
						return errors.Errorf("\tgot: \"%v\",\n\t\t\t\twant: \"%v\"", got, w.want)
					}
				}
				oldIdx = idx
			}
			return nil
		}
		return errors.Errorf("\tgot: \"%v\",\n\t\t\t\twant: \"%v\"", got, w.want)
	}
	tests := []test{
		{
			name: "return string with stack trace initialized",
			fields: fields{
				detail: Detail{
					Version:           "1.0",
					ServerName:        "srv",
					GitCommit:         "commit",
					BuildTime:         "bt",
					GoVersion:         "1.1",
					GoOS:              "goos",
					GoArch:            "goarch",
					GoRoot:            "/usr/local/go",
					CGOEnabled:        cgoTrue,
					AlgorithmInfo:     "1.2",
					BuildCPUInfoFlags: nil,
					StackTrace: []StackTrace{
						{
							URL:      "url",
							FuncName: "func",
							File:     "file",
							Line:     10,
						},
					},
				},
			},
			want: want{
				want: &Detail{
					Version:           "1.0",
					ServerName:        "srv",
					GitCommit:         "commit",
					BuildTime:         "bt",
					GoVersion:         "1.1",
					GoOS:              "goos",
					GoArch:            "goarch",
					GoRoot:            "/usr/local/go",
					CGOEnabled:        cgoTrue,
					AlgorithmInfo:     "1.2",
					BuildCPUInfoFlags: nil,
					StackTrace: []StackTrace{
						{
							URL:      "url",
							FuncName: "func",
							File:     "file",
							Line:     10,
						},
					},
				},
			},
		},
		{
			name: "return string with no stack trace initialized",
			fields: fields{
				detail: Detail{
					Version:           "1.0",
					ServerName:        "srv",
					GitCommit:         "commit",
					BuildTime:         "bt",
					GoVersion:         "1.1",
					GoOS:              "goos",
					GoArch:            "goarch",
					GoRoot:            "/usr/local/go",
					CGOEnabled:        cgoTrue,
					AlgorithmInfo:     "1.2",
					BuildCPUInfoFlags: nil,
					StackTrace:        []StackTrace{},
				},
				rtCaller: func(skip int) (pc uintptr, file string, line int, ok bool) {
					return uintptr(0), "", 0, false
				},
			},
			want: want{
				want: &Detail{
					Version:           "1.0",
					ServerName:        "srv",
					GitCommit:         "commit",
					BuildTime:         "bt",
					GoVersion:         "1.1",
					GoOS:              "goos",
					GoArch:            "goarch",
					GoRoot:            "/usr/local/go",
					CGOEnabled:        cgoTrue,
					AlgorithmInfo:     "1.2",
					BuildCPUInfoFlags: nil,
					StackTrace:        nil,
				},
			},
		},
	}

	for _, tc := range tests {
		test := tc
		t.Run(test.name, func(tt *testing.T) {
			defer goleak.VerifyNone(tt, goleakIgnoreOptions...)
			if test.beforeFunc != nil {
				test.beforeFunc()
			}
			if test.afterFunc != nil {
				defer test.afterFunc(tt)
			}
			checkFunc := test.checkFunc
			if test.checkFunc == nil {
				checkFunc = defaultCheckFunc
			}
			i := info{
				detail:      test.fields.detail,
				rtCaller:    test.fields.rtCaller,
				rtFuncForPC: test.fields.rtFuncForPC,
			}

			got := i.String()
			if err := checkFunc(test.want, got); err != nil {
				tt.Errorf("error = %v", err)
			}
		})
	}
}

func TestDetail_String(t *testing.T) {
	type fields struct {
		Version           string
		ServerName        string
		GitCommit         string
		BuildTime         string
		GoVersion         string
		GoOS              string
		GoArch            string
		CGOEnabled        string
		AlgorithmInfo     string
		BuildCPUInfoFlags []string
		StackTrace        []StackTrace
	}
	type want struct {
		want *Detail
	}
	type test struct {
		name       string
		fields     fields
		want       want
		checkFunc  func(want, string) error
		beforeFunc func()
		afterFunc  func(*testing.T)
	}
	defaultCheckFunc := func(w want, got string) error {
		if got == w.want.String() {
			// check the position of "->"
			var oldIdx int
			for i, str := range strings.Split(strings.TrimPrefix(got, "\n"), "\n") {
				idx := strings.Index(str, "->")
				if i != 0 {
					if oldIdx != idx {
						return errors.Errorf("\tgot: \"%v\",\n\t\t\t\twant: \"%v\"", got, w.want)
					}
				}
				oldIdx = idx
			}
			return nil
		}
		return errors.Errorf("\tgot: \"%v\",\n\t\t\t\twant: \"%v\"", got, w.want)
	}
	tests := []test{
		{
			name: "return string with stack trace initialized",
			fields: fields{
				Version:           "1.0",
				ServerName:        "srv",
				GitCommit:         "commit",
				BuildTime:         "bt",
				GoVersion:         "1.1",
				GoOS:              "goos",
				GoArch:            "goarch",
				CGOEnabled:        cgoTrue,
				AlgorithmInfo:     "1.2",
				BuildCPUInfoFlags: nil,
				StackTrace: []StackTrace{
					{
						URL:      "url",
						FuncName: "func",
						File:     "file",
						Line:     10,
					},
				},
			},
			want: want{
				want: &Detail{
					Version:           "1.0",
					ServerName:        "srv",
					GitCommit:         "commit",
					BuildTime:         "bt",
					GoVersion:         "1.1",
					GoOS:              "goos",
					GoArch:            "goarch",
					CGOEnabled:        cgoTrue,
					AlgorithmInfo:     "1.2",
					BuildCPUInfoFlags: nil,
					StackTrace: []StackTrace{
						{
							URL:      "url",
							FuncName: "func",
							File:     "file",
							Line:     10,
						},
					},
				},
			},
		},
		{
			name: "return string with no stack trace initialized",
			fields: fields{
				Version:           "1.0",
				ServerName:        "srv",
				GitCommit:         "commit",
				BuildTime:         "bt",
				GoVersion:         "1.1",
				GoOS:              "goos",
				GoArch:            "goarch",
				CGOEnabled:        cgoTrue,
				AlgorithmInfo:     "1.2",
				BuildCPUInfoFlags:

<details>
<summary>Analysis chain</summary>



</details>

<details>
<summary>Scripts executed</summary>

The following scripts were executed for the analysis:



---

Script:
```shell
#!/bin/bash
# Locate the test file for info.go and display its contents.
fd info_test.go --exec cat

Length of output: 61592

@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 9a570ca to 8aa8c98 Compare May 15, 2024 04:43
deepsource-autofix bot added a commit that referenced this pull request May 15, 2024
This commit fixes the style issues introduced in 8aa8c98 according to the output
from Gofumpt and Prettier.

Details: #2135
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: 7

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 9a570ca and 640f8e9.
Files ignored due to path filters (10)
  • apis/grpc/v1/manager/index/index_manager.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/manager/index/index_manager_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.json.go is excluded by !**/*.pb.json.go
  • apis/grpc/v1/payload/payload_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • example/client/go.mod is excluded by !**/*.mod
  • example/client/go.sum is excluded by !**/*.sum
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • rust/Cargo.lock is excluded by !**/*.lock
Files selected for processing (41)
  • .github/ISSUE_TEMPLATE/bug_report.md (1 hunks)
  • .github/ISSUE_TEMPLATE/security_issue_report.md (1 hunks)
  • .github/PULL_REQUEST_TEMPLATE.md (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • Makefile.d/dependencies.mk (1 hunks)
  • Makefile.d/functions.mk (1 hunks)
  • apis/docs/v1/docs.md (3 hunks)
  • apis/proto/v1/manager/index/index_manager.proto (1 hunks)
  • apis/proto/v1/payload/payload.proto (1 hunks)
  • apis/swagger/v1/manager/index/index_manager.swagger.json (2 hunks)
  • hack/go.mod.default (1 hunks)
  • internal/info/info.go (5 hunks)
  • internal/net/grpc/errdetails/errdetails.go (2 hunks)
  • internal/net/http/metrics/pprof.go (2 hunks)
  • internal/observability/trace/status.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/flush.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/linear_search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/service/ngt_test.go (5 hunks)
  • pkg/manager/index/handler/grpc/handler.go (1 hunks)
  • pkg/manager/index/handler/grpc/handler_test.go (1 hunks)
  • pkg/manager/index/service/indexer.go (8 hunks)
  • pkg/manager/index/service/indexer_test.go (1 hunks)
  • pkg/manager/index/service/option.go (4 hunks)
  • pkg/manager/index/usecase/indexer.go (1 hunks)
  • rust/libs/proto/src/manager.index.v1.tonic.rs (5 hunks)
  • rust/libs/proto/src/payload.v1.rs (1 hunks)
  • versions/GOLANGCILINT_VERSION (1 hunks)
  • versions/K3S_VERSION (1 hunks)
  • versions/KIND_VERSION (1 hunks)
  • versions/NGT_VERSION (1 hunks)
  • versions/PROMETHEUS_STACK_VERSION (1 hunks)
  • versions/YQ_VERSION (1 hunks)
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE (1 hunks)
Files skipped from review due to trivial changes (1)
  • hack/go.mod.default
Files skipped from review as they are similar to previous changes (36)
  • .github/ISSUE_TEMPLATE/bug_report.md
  • .github/ISSUE_TEMPLATE/security_issue_report.md
  • .github/PULL_REQUEST_TEMPLATE.md
  • .github/workflows/release.yml
  • Makefile.d/dependencies.mk
  • Makefile.d/functions.mk
  • apis/proto/v1/manager/index/index_manager.proto
  • apis/proto/v1/payload/payload.proto
  • apis/swagger/v1/manager/index/index_manager.swagger.json
  • internal/info/info.go
  • internal/net/grpc/errdetails/errdetails.go
  • internal/observability/trace/status.go
  • pkg/agent/core/faiss/handler/grpc/insert.go
  • pkg/agent/core/faiss/handler/grpc/remove.go
  • pkg/agent/core/faiss/handler/grpc/search.go
  • pkg/agent/core/faiss/handler/grpc/update.go
  • pkg/agent/core/ngt/handler/grpc/flush.go
  • pkg/agent/core/ngt/handler/grpc/insert.go
  • pkg/agent/core/ngt/handler/grpc/linear_search.go
  • pkg/agent/core/ngt/handler/grpc/remove.go
  • pkg/agent/core/ngt/handler/grpc/search.go
  • pkg/agent/core/ngt/handler/grpc/update.go
  • pkg/manager/index/handler/grpc/handler.go
  • pkg/manager/index/handler/grpc/handler_test.go
  • pkg/manager/index/service/indexer_test.go
  • pkg/manager/index/service/option.go
  • pkg/manager/index/usecase/indexer.go
  • rust/libs/proto/src/manager.index.v1.tonic.rs
  • rust/libs/proto/src/payload.v1.rs
  • versions/GOLANGCILINT_VERSION
  • versions/K3S_VERSION
  • versions/KIND_VERSION
  • versions/NGT_VERSION
  • versions/PROMETHEUS_STACK_VERSION
  • versions/YQ_VERSION
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE
Additional comments not posted (14)
internal/net/http/metrics/pprof.go (4)

25-25: Ensure the pyprof import is necessary and correctly used.

Verify that the pyprof import is used correctly in the file.


120-127: The route for delta heap profile is correctly defined. Ensure the handler pyprof.Heap is appropriate and correctly implemented.

Verify the correctness of the handler pyprof.Heap.


128-135: The route for delta mutex profile is correctly defined. Ensure the handler pyprof.Mutex is appropriate and correctly implemented.

Verify the correctness of the handler pyprof.Mutex.


136-143: The route for delta block profile is correctly defined. Ensure the handler pyprof.Block is appropriate and correctly implemented.

Verify the correctness of the handler pyprof.Block.

pkg/manager/index/service/indexer.go (3)

46-47: The methods IsSaving and LoadIndexDetail are correctly defined in the Indexer interface. Ensure their implementations are correct.

Verify the correctness of the implementations of IsSaving and LoadIndexDetail.


56-63: The new fields in the index struct are correctly defined. Ensure their usage throughout the code is appropriate and consistent.

Verify the correctness of the usage of the new fields in the index struct.


79-80: The new fields are correctly initialized in the New function. Ensure all edge cases are handled.

Verify the correctness of the initialization of the new fields in the New function.

apis/docs/v1/docs.md (1)

26-27: Addition to the table of contents for Info.Index.Detail looks good.

pkg/agent/core/ngt/service/ngt_test.go (6)

41-41: Remove unused imports.

The import statements for file, kvald, log, safety, strings, and sync should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.


42-44: Verify the usage of additional imports.

Ensure that the imported packages kvs, metadata, and vqueue are used within the file. Unused imports should be removed to maintain code cleanliness.


1559-1560: Fix the type mismatch in test arguments.

The requests field in the args struct is of type []*payload.Upsert_MultiRequest, but the MultiInsert method expects *payload.Insert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- requests []*payload.Upsert_MultiRequest
+ requests []*payload.Insert_MultiRequest

1615-1616: Initialization looks correct.

The addr and client fields are correctly initialized in the test case.


1645-1645: The type mismatch issue with MultiInsert expecting an Insert_MultiRequest but receiving an Upsert_MultiRequest still persists. This needs to be addressed to prevent runtime errors.


1638-1646: Fix the type mismatch in gRPC call.

The MultiInsert method expects *payload.Insert_MultiRequest, but the test is passing *payload.Upsert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- return vald.NewValdClient(conn).MultiInsert(ctx, req)
+ return vald.NewValdClient(conn).MultiInsert(ctx, req.(*payload.Insert_MultiRequest))

Comment on lines 299 to 319
<a name="payload-v1-Info-Index-Detail"></a>

### Info.Index.Detail

Represent the index count for each Agents message.

| Field | Type | Label | Description |
| ----------- | -------------------------------------------------------------------------- | -------- | ---------------------------------- |
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count infos for each agents |
| replica | [uint32](#uint32) | | index replica of vald cluster |
| live_agents | [uint32](#uint32) | | live agent replica of vald cluster |

<a name="payload-v1-Info-Index-Detail-CountsEntry"></a>

### Info.Index.Detail.CountsEntry

| Field | Type | Label | Description |
| ----- | ------------------------------------------------ | ----- | ----------- |
| key | [string](#string) | | |
| value | [Info.Index.Count](#payload-v1-Info-Index-Count) | | |

Copy link
Contributor

Choose a reason for hiding this comment

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

The new messages Info.Index.Detail and CountsEntry are well-defined and follow the existing structure. However, there is a grammatical issue in the description.

- count infos for each agents
+ count info for each agent

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
<a name="payload-v1-Info-Index-Detail"></a>
### Info.Index.Detail
Represent the index count for each Agents message.
| Field | Type | Label | Description |
| ----------- | -------------------------------------------------------------------------- | -------- | ---------------------------------- |
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count infos for each agents |
| replica | [uint32](#uint32) | | index replica of vald cluster |
| live_agents | [uint32](#uint32) | | live agent replica of vald cluster |
<a name="payload-v1-Info-Index-Detail-CountsEntry"></a>
### Info.Index.Detail.CountsEntry
| Field | Type | Label | Description |
| ----- | ------------------------------------------------ | ----- | ----------- |
| key | [string](#string) | | |
| value | [Info.Index.Count](#payload-v1-Info-Index-Count) | | |
<a name="payload-v1-Info-Index-Detail"></a>
### Info.Index.Detail
Represent the index count for each Agents message.
| Field | Type | Label | Description |
| ----------- | -------------------------------------------------------------------------- | -------- | ---------------------------------- |
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count info for each agent |
| replica | [uint32](#uint32) | | index replica of vald cluster |
| live_agents | [uint32](#uint32) | | live agent replica of vald cluster |
<a name="payload-v1-Info-Index-Detail-CountsEntry"></a>
### Info.Index.Detail.CountsEntry
| Field | Type | Label | Description |
| ----- | ------------------------------------------------ | ----- | ----------- |
| key | [string](#string) | | |
| value | [Info.Index.Count](#payload-v1-Info-Index-Count) | | |

Comment on lines 254 to 252
func (idx *index) saveIndex(ctx context.Context, force bool) (err error) {
ctx, span := trace.StartSpan(ctx, "vald/manager-index/service/Indexer.saveIndex")
defer func() {
if span != nil {
span.End()
}
timer.Stop()
}()

if idx.saving.Load() {
return nil
}
idx.saving.Store(true)
defer idx.saving.Store(false)
return idx.client.GetClient().OrderedRangeConcurrent(ctx, idx.client.GetAddrs(ctx),
idx.saveIndexConcurrency,
func(ctx context.Context,
addr string, conn *grpc.ClientConn, copts ...grpc.CallOption,
) (err error) {
_, ok := idx.shouldSaveList.LoadAndDelete(addr)
if !ok && !force {
return nil
}
_, err = agent.NewAgentClient(conn).SaveIndex(ctx, new(payload.Empty), copts...)
if err != nil {
st, ok := status.FromError(err)
if ok && st != nil && st.Code() == codes.FailedPrecondition {
log.Debugf("CreateIndex of %s skipped, message: %s, err: %v", addr, st.Message(), errors.Join(st.Err(), err))
return nil
}
log.Warnf("an error occurred while calling CreateIndex of %s: %s", addr, err)
return err
}
return nil
})
Copy link
Contributor

Choose a reason for hiding this comment

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

The changes to the saveIndex method are correctly implemented. However, ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference.

Ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference.

return err
}
return nil
})
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure that infoMap.Load(addr) does not return nil before storing it in idx.indexInfos to avoid potential nil pointer dereference.

Ensure that infoMap.Load(addr) does not return nil before storing it in idx.indexInfos to avoid potential nil pointer dereference.

@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 640f8e9 to 8f35f90 Compare May 15, 2024 04:52
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: 6

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 640f8e9 and 8f35f90.
Files ignored due to path filters (10)
  • apis/grpc/v1/manager/index/index_manager.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/manager/index/index_manager_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • apis/grpc/v1/payload/payload.pb.json.go is excluded by !**/*.pb.json.go
  • apis/grpc/v1/payload/payload_vtproto.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • example/client/go.mod is excluded by !**/*.mod
  • example/client/go.sum is excluded by !**/*.sum
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum
  • rust/Cargo.lock is excluded by !**/*.lock
Files selected for processing (42)
  • .github/ISSUE_TEMPLATE/bug_report.md (1 hunks)
  • .github/ISSUE_TEMPLATE/security_issue_report.md (1 hunks)
  • .github/PULL_REQUEST_TEMPLATE.md (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • Makefile.d/dependencies.mk (1 hunks)
  • Makefile.d/functions.mk (1 hunks)
  • apis/docs/v1/docs.md (3 hunks)
  • apis/proto/v1/manager/index/index_manager.proto (1 hunks)
  • apis/proto/v1/payload/payload.proto (1 hunks)
  • apis/swagger/v1/manager/index/index_manager.swagger.json (2 hunks)
  • hack/go.mod.default (1 hunks)
  • internal/info/info.go (5 hunks)
  • internal/net/grpc/errdetails/errdetails.go (2 hunks)
  • internal/net/http/metrics/pprof.go (2 hunks)
  • internal/observability/trace/status.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/faiss/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/flush.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/insert.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/linear_search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/remove.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/search.go (1 hunks)
  • pkg/agent/core/ngt/handler/grpc/update.go (1 hunks)
  • pkg/agent/core/ngt/service/ngt_test.go (5 hunks)
  • pkg/manager/index/handler/grpc/handler.go (1 hunks)
  • pkg/manager/index/handler/grpc/handler_test.go (1 hunks)
  • pkg/manager/index/service/indexer.go (8 hunks)
  • pkg/manager/index/service/indexer_test.go (1 hunks)
  • pkg/manager/index/service/option.go (4 hunks)
  • pkg/manager/index/usecase/indexer.go (1 hunks)
  • rust/libs/proto/src/manager.index.v1.tonic.rs (5 hunks)
  • rust/libs/proto/src/payload.v1.rs (1 hunks)
  • versions/GOLANGCILINT_VERSION (1 hunks)
  • versions/K3S_VERSION (1 hunks)
  • versions/KIND_VERSION (1 hunks)
  • versions/NGT_VERSION (1 hunks)
  • versions/PROMETHEUS_STACK_VERSION (1 hunks)
  • versions/YQ_VERSION (1 hunks)
  • versions/actions/CODECOV_CODECOV_ACTION (1 hunks)
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE (1 hunks)
Files skipped from review due to trivial changes (1)
  • versions/actions/CODECOV_CODECOV_ACTION
Files skipped from review as they are similar to previous changes (38)
  • .github/ISSUE_TEMPLATE/bug_report.md
  • .github/ISSUE_TEMPLATE/security_issue_report.md
  • .github/PULL_REQUEST_TEMPLATE.md
  • .github/workflows/release.yml
  • Makefile.d/dependencies.mk
  • Makefile.d/functions.mk
  • apis/proto/v1/manager/index/index_manager.proto
  • apis/proto/v1/payload/payload.proto
  • apis/swagger/v1/manager/index/index_manager.swagger.json
  • hack/go.mod.default
  • internal/info/info.go
  • internal/net/grpc/errdetails/errdetails.go
  • internal/net/http/metrics/pprof.go
  • internal/observability/trace/status.go
  • pkg/agent/core/faiss/handler/grpc/insert.go
  • pkg/agent/core/faiss/handler/grpc/remove.go
  • pkg/agent/core/faiss/handler/grpc/search.go
  • pkg/agent/core/faiss/handler/grpc/update.go
  • pkg/agent/core/ngt/handler/grpc/flush.go
  • pkg/agent/core/ngt/handler/grpc/insert.go
  • pkg/agent/core/ngt/handler/grpc/linear_search.go
  • pkg/agent/core/ngt/handler/grpc/remove.go
  • pkg/agent/core/ngt/handler/grpc/search.go
  • pkg/agent/core/ngt/handler/grpc/update.go
  • pkg/manager/index/handler/grpc/handler.go
  • pkg/manager/index/handler/grpc/handler_test.go
  • pkg/manager/index/service/indexer_test.go
  • pkg/manager/index/service/option.go
  • pkg/manager/index/usecase/indexer.go
  • rust/libs/proto/src/manager.index.v1.tonic.rs
  • rust/libs/proto/src/payload.v1.rs
  • versions/GOLANGCILINT_VERSION
  • versions/K3S_VERSION
  • versions/KIND_VERSION
  • versions/NGT_VERSION
  • versions/PROMETHEUS_STACK_VERSION
  • versions/YQ_VERSION
  • versions/actions/SOFTPROPS_ACTION_GH_RELEASE
Additional comments not posted (10)
pkg/manager/index/service/indexer.go (5)

46-47: New methods IsSaving and LoadIndexDetail are correctly added to the Indexer interface.


56-70: New fields saveIndexDuration, saveIndexDurationLimit, shouldSaveList, saveIndexConcurrency, indexing, saving, and empty are correctly added to the index struct.


79-80: The initialization of the new fields indexing and saving in the New function is correctly implemented.


254-255: Ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference.


287-287: Ensure that infoMap.Load(addr) does not return nil before storing it in idx.indexInfos to avoid potential nil pointer dereference.

apis/docs/v1/docs.md (1)

313-319: The new message Info.Index.Detail.CountsEntry is well-defined and follows the existing structure.

pkg/agent/core/ngt/service/ngt_test.go (4)

41-41: Remove unused imports.

The import statements for file, kvald, log, grpc, safety, strings, and sync should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.


1559-1560: Fix the type mismatch in test arguments.

The requests field in the args struct is of type []*payload.Upsert_MultiRequest, but the MultiInsert method expects *payload.Insert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- requests []*payload.Upsert_MultiRequest
+ requests []*payload.Insert_MultiRequest

1615-1616: Verify the initialization of the gRPC client.

The client is initialized with grpc.New(grpc.WithInsecure(true)). Ensure that this initialization is correct and secure for the test environment.


1638-1646: Fix the type mismatch in gRPC call.

The MultiInsert method expects *payload.Insert_MultiRequest, but the test is passing *payload.Upsert_MultiRequest. This type mismatch needs to be addressed to prevent runtime errors.

- return vald.NewValdClient(conn).MultiInsert(ctx, req)
+ return vald.NewValdClient(conn).MultiInsert(ctx, req.(*payload.Insert_MultiRequest))


| Field | Type | Label | Description |
| ----------- | -------------------------------------------------------------------------- | -------- | ---------------------------------- |
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count infos for each agents |
Copy link
Contributor

Choose a reason for hiding this comment

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

Use singular form for "agents".

- count infos for each agents
+ count info for each agent

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count infos for each agents |
| counts | [Info.Index.Detail.CountsEntry](#payload-v1-Info-Index-Detail-CountsEntry) | repeated | count info for each agent |

| Method Name | Request Type | Response Type | Description |
| ----------- | -------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------- |
| IndexInfo | [.payload.v1.Empty](#payload-v1-Empty) | [.payload.v1.Info.Index.Count](#payload-v1-Info-Index-Count) | Represent the RPC to get the index information. |
| IndexDetail | [.payload.v1.Empty](#payload-v1-Empty) | [.payload.v1.Info.Index.Detail](#payload-v1-Info-Index-Detail) | Represent the RPC to get the index information for each agents. |
Copy link
Contributor

Choose a reason for hiding this comment

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

Use singular form for "agents".

- index information for each agents
+ index information for each agent

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
| IndexDetail | [.payload.v1.Empty](#payload-v1-Empty) | [.payload.v1.Info.Index.Detail](#payload-v1-Info-Index-Detail) | Represent the RPC to get the index information for each agents. |
| IndexDetail | [.payload.v1.Empty](#payload-v1-Empty) | [.payload.v1.Info.Index.Detail](#payload-v1-Info-Index-Detail) | Represent the RPC to get the index information for each agent. |

@@ -38,6 +38,7 @@ import (
"github.com/vdaas/vald/internal/file"
kvald "github.com/vdaas/vald/internal/k8s/vald"
"github.com/vdaas/vald/internal/log"
"github.com/vdaas/vald/internal/net/grpc"
"github.com/vdaas/vald/internal/safety"
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unused imports.

The import statements for kvs, metadata, and vqueue should be verified for usage within the file. Unused imports should be removed to keep the code clean and maintainable.

Comment on lines 104 to 106
if idx.saveIndexDuration <= 0 {
idx.saveIndexDuration = math.MaxInt64
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using mu.TryLock() with a timeout or context check to avoid potential deadlocks.

- if !mu.TryLock() {
+ if !mu.TryLockWithTimeout(ctx, timeout) {
  return
}

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if idx.saveIndexDuration <= 0 {
idx.saveIndexDuration = math.MaxInt64
}
if idx.saveIndexDuration <= 0 {
idx.saveIndexDuration = math.MaxInt64
}
if !mu.TryLockWithTimeout(ctx, timeout) {
return
}

Comment on lines 224 to 225
return errors.Join(idx.client.GetClient().OrderedRangeConcurrent(ctx, idx.client.GetAddrs(ctx),
idx.createIndexConcurrency,
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference. The GetAddrs method can return nil if net.DefaultResolver.LookupIPAddr fails, which needs to be handled properly.

  • internal/client/v1/client/discoverer/discover.go:182: return nil if LookupIPAddr fails.
Analysis chain

Ensure that idx.client.GetClient() and idx.client.GetAddrs(ctx) do not return nil to avoid potential nil pointer dereference.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `idx.client.GetClient()` and `idx.client.GetAddrs(ctx)` do not return nil.

# Test: Search for the function usage. Expect: No nil returns.
rg --type go 'idx.client.GetClient()' --context 5
rg --type go 'idx.client.GetAddrs(ctx)' --context 5

Length of output: 5581



Script:

#!/bin/bash
# Locate the implementation of the GetClient method
ast-grep --lang go --pattern 'func ($_ $_) GetClient() $_ { $$$ }'

# Locate the implementation of the GetAddrs method
ast-grep --lang go --pattern 'func ($_ $_) GetAddrs($_) $_ { $$$ }'

Length of output: 2599



Script:

#!/bin/bash
# Locate the initialization of `c.client` in discover.go
rg --type go 'c.client =' --context 5

# Locate the usage of `net.DefaultResolver.LookupIPAddr` in discover.go to ensure proper error handling
rg --type go 'net.DefaultResolver.LookupIPAddr' --context 5

Length of output: 3999

Comment on lines 356 to 363
func (idx *index) LoadIndexDetail() (detail *payload.Info_Index_Detail) {
detail = new(payload.Info_Index_Detail)
idx.indexInfos.Range(func(addr string, info *payload.Info_Index_Count) bool {
detail.Counts[addr] = info
return true
})
return detail
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure that detail.Counts is initialized before storing values to avoid potential nil pointer dereference.

func (idx *index) LoadIndexDetail() (detail *payload.Info_Index_Detail) {
+ detail = &payload.Info_Index_Detail{
+   Counts: make(map[string]*payload.Info_Index_Count),
+ }
  idx.indexInfos.Range(func(addr string, info *payload.Info_Index_Count) bool {
    detail.Counts[addr] = info
    return true
  })
  return detail
}

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
func (idx *index) LoadIndexDetail() (detail *payload.Info_Index_Detail) {
detail = new(payload.Info_Index_Detail)
idx.indexInfos.Range(func(addr string, info *payload.Info_Index_Count) bool {
detail.Counts[addr] = info
return true
})
return detail
}
func (idx *index) LoadIndexDetail() (detail *payload.Info_Index_Detail) {
detail = &payload.Info_Index_Detail{
Counts: make(map[string]*payload.Info_Index_Count),
}
idx.indexInfos.Range(func(addr string, info *payload.Info_Index_Count) bool {
detail.Counts[addr] = info
return true
})
return detail
}

@kpango kpango closed this May 21, 2024
@kpango kpango force-pushed the refactor/manager-index/small-refactor branch from 8f35f90 to 8a36249 Compare May 21, 2024 21:20
@kpango kpango deleted the refactor/manager-index/small-refactor branch May 21, 2024 21:21
@kpango kpango restored the refactor/manager-index/small-refactor branch May 21, 2024 21:21
deepsource-autofix bot added a commit that referenced this pull request May 21, 2024
This commit fixes the style issues introduced in 8a36249 according to the output
from Gofumpt and Prettier.

Details: #2135
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment