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 #2667 to release/v1.7 for modify ParseError to FromError for agent handler #2679

Merged

Conversation

vdaas-ci
Copy link
Collaborator

@vdaas-ci vdaas-ci commented Oct 8, 2024

Description

SSIA

Related Issue

Versions

  • Vald Version: v1.7.13
  • Go Version: v1.23.1
  • Rust Version: v1.81.0
  • Docker Version: v27.3.1
  • Kubernetes Version: v1.31.1
  • Helm Version: v3.16.1
  • NGT Version: v2.2.4
  • Faiss Version: v1.8.0

Checklist

Special notes for your reviewer

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling across multiple gRPC methods, enhancing clarity and consistency in error reporting.
    • Streamlined error parsing by adopting a direct approach to retrieve status information, reducing redundancy.
    • Enhanced logging mechanisms for better traceability of errors during operations.
    • Added specific error checks and detailed context for various error types, improving granularity in error reporting.

These changes collectively improve the reliability and maintainability of error handling within the application.

* modify ParseError to FromError

* fix typo

* fix typo

* fix typo

* fix typo

* fix imported and not used error

---------

Co-authored-by: Kosuke Morimoto <[email protected]>
Copy link

cloudflare-workers-and-pages bot commented Oct 8, 2024

Deploying vald with  Cloudflare Pages  Cloudflare Pages

Latest commit: ae506e1
Status: ✅  Deploy successful!
Preview URL: https://3bbccfb6.vald.pages.dev
Branch Preview URL: https://backport-release-v1-7-refact-vvwr.vald.pages.dev

View logs

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve significant modifications to the error handling and logging mechanisms in the grpc package. The updates streamline error handling by replacing status.ParseError with status.FromError, ensuring consistency across various methods. Additionally, enhancements to logging improve clarity by preserving error context. Minor code cleanups were also performed to enhance readability and maintainability without altering any exported or public entity declarations.

Changes

File Path Change Summary
pkg/agent/core/ngt/handler/grpc/insert.go Improved error handling and logging; replaced status.ParseError with status.FromError.
pkg/agent/core/ngt/handler/grpc/linear_search.go Streamlined error handling and logging; ensured consistency across methods.
pkg/agent/core/ngt/handler/grpc/object.go Enhanced error handling and logging; simplified logic and improved clarity.
pkg/agent/core/ngt/handler/grpc/remove.go Updated error handling; improved logging context.
pkg/agent/core/ngt/handler/grpc/search.go Consistent error handling and logging enhancements.
pkg/agent/core/ngt/handler/grpc/update.go Streamlined error handling; improved logging clarity.
pkg/agent/core/ngt/handler/grpc/upsert.go Enhanced error handling and logging; minor code cleanup.

Possibly related PRs

  • modify ParseError to FromError for agent handler #2667: This PR modifies error handling in the grpc package, specifically changing status.ParseError to status.FromError, which aligns directly with the changes made in the main PR regarding error handling improvements across multiple methods in the grpc package.

Suggested labels

priority/low, type/refactoring, area/internal, area/agent/core/ngt

Suggested reviewers

  • kmrmt
  • datelier
  • hlts2

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 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
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: 8

🧹 Outside diff range and nitpick comments (3)
pkg/agent/core/ngt/handler/grpc/object.go (2)

173-176: Consistent error handling improvement in StreamListObject

The change from status.ParseError to status.FromError in this method is consistent with the earlier modification in StreamGetObject. This improves the overall consistency of error handling in the file.

For even better consistency, consider updating the error handling in the StreamListObject method's loop (around line 250) to use status.FromError as well.


Line range hint 1-324: Overall improvement in error handling

The changes in this file successfully implement the PR objective of replacing ParseError with FromError for error handling in the agent handler. These modifications improve code consistency and simplify error processing across the StreamGetObject and StreamListObject methods.

To further enhance consistency, consider updating the error handling in the StreamListObject method's loop (around line 250) to use status.FromError as well. This would ensure uniform error handling throughout the file.

pkg/agent/core/ngt/handler/grpc/insert.go (1)

Line range hint 256-265: Improved error handling for already existing UUIDs in MultiInsert function

The changes to the error handling logic in the MultiInsert function, particularly for handling already existing UUIDs, are well-implemented. Encapsulating this logic into a separate anonymous function improves readability and maintainability.

For consistency with the other error handling cases in this function, consider extracting the anonymous function to a named function at the package level. This would further improve readability and make the error handling pattern more uniform across the function.

Consider refactoring the anonymous function to a named function at the package level:

func collectExistingIDs(uuids []string, err error) []string {
	aids := make([]string, 0, len(uuids))
	for _, id := range uuids {
		if errors.Is(err, errors.ErrUUIDAlreadyExists(id)) {
			aids = append(aids, id)
		}
	}
	return aids
}

Then use it in the MultiInsert function:

} else if alreadyExistsIDs := collectExistingIDs(uuids, err); len(alreadyExistsIDs) != 0 {
	// ... rest of the error handling ...
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between acd2f0a and ae506e1.

📒 Files selected for processing (7)
  • pkg/agent/core/ngt/handler/grpc/insert.go (2 hunks)
  • pkg/agent/core/ngt/handler/grpc/linear_search.go (8 hunks)
  • pkg/agent/core/ngt/handler/grpc/object.go (2 hunks)
  • pkg/agent/core/ngt/handler/grpc/remove.go (3 hunks)
  • pkg/agent/core/ngt/handler/grpc/search.go (8 hunks)
  • pkg/agent/core/ngt/handler/grpc/update.go (2 hunks)
  • pkg/agent/core/ngt/handler/grpc/upsert.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (18)
pkg/agent/core/ngt/handler/grpc/object.go (1)

154-157: Improved error handling in StreamGetObject

The change from status.ParseError to status.FromError is a good improvement. It simplifies the error handling logic while maintaining the existing functionality. This modification aligns well with the PR objective and should lead to more efficient error processing.

pkg/agent/core/ngt/handler/grpc/insert.go (2)

165-168: Improved error handling in StreamInsert function

The changes to the error handling logic in the StreamInsert function are well-implemented. The use of status.FromError instead of status.ParseError simplifies the code and makes it more consistent with other parts of the codebase. This approach directly uses the returned status to set span attributes and status, which is more efficient and less error-prone.

Also applies to: 184-187


Line range hint 1-324: Overall improvements in error handling and logging

The changes made to this file are well-implemented and align with the PR objectives. The error handling has been streamlined and made more consistent across the StreamInsert and MultiInsert functions. These improvements enhance the code's readability, maintainability, and error reporting capabilities.

pkg/agent/core/ngt/handler/grpc/search.go (7)

350-353: Improved error handling and span recording

The changes in this segment enhance the error handling process by replacing status.ParseError with status.FromError. This modification simplifies the code and potentially improves performance by avoiding unnecessary parsing. Additionally, the span recording logic is now more robust with proper nil checks.


369-372: Consistent error handling improvement

These changes align with the previous modifications, ensuring consistent error handling throughout the StreamSearch function. The use of status.FromError and the conditional span recording maintain the improved approach to error management.


397-400: Uniform error handling across search functions

The changes in the StreamSearchByID function mirror those in StreamSearch, demonstrating a consistent approach to error handling and span recording across different search operations. This uniformity enhances code maintainability and readability.


416-419: Consistent error handling at function level

These changes in the StreamSearchByID function's error handling section maintain the improved approach seen in previous modifications. The consistent application of status.FromError and conditional span recording across different parts of the function enhances overall code quality and error management.


457-460: Improved error handling in concurrent operations

The changes in the MultiSearch function apply the same improved error handling approach within a concurrent context. This ensures that the benefits of using status.FromError and conditional span recording are maintained even in parallel operations, contributing to more robust and consistent error management across different execution scenarios.


478-484: Consistent error handling with return statement modification

The changes in this segment of the MultiSearch function maintain the improved error handling approach seen throughout the file. Additionally, the return statement has been modified to return nil instead of res in case of errors. This change ensures that no partial results are returned when errors occur, which is a more appropriate behavior for error cases.


Line range hint 519-546: Uniform improvements across search functions

The changes in the MultiSearchByID function mirror those in MultiSearch, demonstrating a consistent approach to error handling, span recording, and result handling across different search operations. This uniformity extends to the modification of the return statement in error cases, ensuring that all search functions behave consistently when errors occur. Such consistency significantly enhances the maintainability and reliability of the codebase.

pkg/agent/core/ngt/handler/grpc/upsert.go (3)

153-156: Ensure complete error information is preserved when using status.FromError

The change from status.ParseError to status.FromError alters how error details are extracted. Verify that all necessary error information, such as custom messages and error codes, is still being captured and logged appropriately. This ensures that error handling remains robust and informative.


172-175: Confirm accurate span attributes after replacing status.ParseError with status.FromError

With the switch to status.FromError, please ensure that the span attributes set by trace.FromGRPCStatus(st.Code(), st.Message())... accurately reflect the error status. This is crucial for effective tracing and debugging.


319-322: Validate error handling logic in MultiUpsert after modifying error parsing

In the MultiUpsert function, the error parsing has been updated. Ensure that status.FromError(err) provides all the necessary error details for proper error handling and that the span records accurately represent any errors encountered.

pkg/agent/core/ngt/handler/grpc/linear_search.go (5)

346-349: Consistent error handling with status.FromError

The use of status.FromError(err) in the StreamLinearSearch function ensures consistent extraction of gRPC status from errors. The nil checks for st and sspan before accessing st.Code() and st.Message() prevent potential nil pointer dereferences.


365-368: Appropriate error handling in the outer scope

In the outer scope of StreamLinearSearch, the error handling correctly extracts the status from err and updates the span attributes accordingly. This maintains consistency with the inner function.


395-398: Error handling in StreamLinearSearchByID is well-implemented

The error extraction and span updates in StreamLinearSearchByID are correctly implemented. The checks for nil values ensure safe access to status codes and messages.


414-417: Consistent outer error handling in StreamLinearSearchByID

The outer error handling in StreamLinearSearchByID mirrors the pattern used elsewhere, ensuring consistent and reliable error reporting.


517-520: Proper error handling in MultiLinearSearchByID

The error extraction and tracing in MultiLinearSearchByID are correctly handled, ensuring that errors are appropriately recorded and statuses are set.

Comment on lines +178 to +181
st, _ := status.FromError(err)
if st != nil && span != nil {
span.RecordError(err)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check the ok value returned by status.FromError

In this error handling block, similar to the previous instance, the ok value returned from status.FromError(err) is ignored. It is important to verify that the error was successfully converted before using the status object.

Update the code as follows:

-st, _ := status.FromError(err)
+st, ok := status.FromError(err)
-if st != nil && span != nil {
+if ok && span != nil {

By checking ok, you ensure that st is a valid gRPC status, preventing potential issues arising from using an invalid status object.

📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
st, _ := status.FromError(err)
if st != nil && span != nil {
span.RecordError(err)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
st, ok := status.FromError(err)
if ok && span != nil {
span.RecordError(err)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)

Comment on lines +316 to +323
st, _ := status.FromError(errs)
log.Error(errs)
if st != nil && span != nil {
span.RecordError(errs)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, err
return nil, errs
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Verify successful conversion when using status.FromError

In the RemoveByTimestamp function, the code calls status.FromError(errs) but does not check the ok value. This could result in using an invalid status object if the conversion fails.

Please modify the code to include the ok check:

-st, _ := status.FromError(errs)
+st, ok := status.FromError(errs)
-if st != nil && span != nil {
+if ok && span != nil {

Ensuring that ok is true before using st helps maintain robust error handling and prevents potential nil pointer dereferences.

📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
st, _ := status.FromError(errs)
log.Error(errs)
if st != nil && span != nil {
span.RecordError(errs)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, err
return nil, errs
st, ok := status.FromError(errs)
log.Error(errs)
if ok && span != nil {
span.RecordError(errs)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, errs

Comment on lines +159 to +162
st, _ := status.FromError(err)
if st != nil && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure proper handling of status.FromError conversion

In the StreamRemove function, you are calling status.FromError(err) and assigning the result to st, _. The second return value indicates whether the error was successfully converted to a gRPC status. Currently, the code does not check this value, which could lead to incorrect behavior if the conversion fails.

Consider modifying the code to check the ok value before using st:

-st, _ := status.FromError(err)
+st, ok := status.FromError(err)
-if st != nil && sspan != nil {
+if ok && sspan != nil {

This change ensures that st is valid and prevents potential nil pointer dereferences.

📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
st, _ := status.FromError(err)
if st != nil && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
st, ok := status.FromError(err)
if ok && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)

Comment on lines +212 to +215
st, _ := status.FromError(err)
if st != nil && span != nil {
span.RecordError(err)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
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

Suggestion: Check the ok value from status.FromError(err)

Consistent with the previous change, use the ok boolean to verify if the error contains a gRPC status.

Apply this change:

-st, _ := status.FromError(err)
-if st != nil && span != nil {
+st, ok := status.FromError(err)
+if ok && span != nil {
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
st, _ := status.FromError(err)
if st != nil && span != nil {
span.RecordError(err)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
st, ok := status.FromError(err)
if ok && span != nil {
span.RecordError(err)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)

Comment on lines +193 to +196
st, _ := status.FromError(err)
if st != nil && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
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

Suggestion: Use the ok value from status.FromError(err)

When calling status.FromError(err), it returns (*status.Status, bool). The boolean ok indicates whether the error can be represented as a gRPC status. Checking ok is more reliable than checking if st is not nil.

Apply this change:

-st, _ := status.FromError(err)
-if st != nil && sspan != nil {
+st, ok := status.FromError(err)
+if ok && sspan != nil {
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
st, _ := status.FromError(err)
if st != nil && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
st, ok := status.FromError(err)
if ok && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)

Comment on lines +538 to +544
st, _ := status.FromError(errs)
if st != nil && span != nil {
span.RecordError(errs)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, err
return nil, errs
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handling combined errors safely

Similar to MultiLinearSearch, when dealing with errs that may contain multiple errors, it's important to ensure that status.FromError(errs) correctly handles combined errors to prevent nil pointer dereferences.

Consider updating the error handling as suggested earlier to process individual errors within errs.

Comment on lines +455 to +458
st, _ := status.FromError(err)
if st != nil && sspan != nil {
sspan.RecordError(err)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), msg)...)
sspan.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential issue with error status extraction

When using errors.Join to accumulate errors into errs, calling status.FromError(errs) may not correctly extract the gRPC status, as errs could be a composite error. This might result in st being nil, leading to a potential nil pointer dereference when accessing st.Code() and st.Message().

Consider iterating over the individual errors within errs to extract and handle their statuses separately. Here's a possible fix:

 if err != nil {
     mu.Lock()
     if errs == nil {
         errs = err
     } else {
         errs = errors.Join(errs, err)
     }
     mu.Unlock()
 }

At the point of handling errs:

 if errs != nil {
-    st, _ := status.FromError(errs)
-    if st != nil && span != nil {
-        span.RecordError(errs)
-        span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
-        span.SetStatus(trace.StatusError, errs.Error())
-    }
+    if span != nil {
+        span.RecordError(errs)
+        var merr errors.ErrorList
+        if errors.As(errs, &merr) {
+            for _, e := range merr {
+                if st, _ := status.FromError(e); st != nil {
+                    span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
+                }
+            }
+        } else {
+            if st, _ := status.FromError(errs); st != nil {
+                span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
+            }
+        }
+        span.SetStatus(trace.StatusError, errs.Error())
+    }
     return nil, errs
 }

Committable suggestion was skipped due to low confidence.

Comment on lines +476 to +482
st, _ := status.FromError(errs)
if st != nil && span != nil {
span.RecordError(errs)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, err
return nil, errs
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential nil pointer dereference with combined errors

In the MultiLinearSearch function, using status.FromError(errs) on a combined error may not extract the proper status. This could result in st being nil, leading to a nil pointer dereference.

Modify the error handling to safely extract statuses from individual errors:

 if errs != nil {
-    st, _ := status.FromError(errs)
-    if st != nil && span != nil {
-        span.RecordError(errs)
-        span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
-        span.SetStatus(trace.StatusError, errs.Error())
-    }
+    if span != nil {
+        span.RecordError(errs)
+        var merr errors.ErrorList
+        if errors.As(errs, &merr) {
+            for _, e := range merr {
+                if st, _ := status.FromError(e); st != nil {
+                    span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
+                }
+            }
+        } else {
+            if st, _ := status.FromError(errs); st != nil {
+                span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
+            }
+        }
+        span.SetStatus(trace.StatusError, errs.Error())
+    }
     return nil, errs
 }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
st, _ := status.FromError(errs)
if st != nil && span != nil {
span.RecordError(errs)
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, err
return nil, errs
if errs != nil {
if span != nil {
span.RecordError(errs)
var merr errors.ErrorList
if errors.As(errs, &merr) {
for _, e := range merr {
if st, _ := status.FromError(e); st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
}
}
} else {
if st, _ := status.FromError(errs); st != nil {
span.SetAttributes(trace.FromGRPCStatus(st.Code(), st.Message())...)
}
}
span.SetStatus(trace.StatusError, errs.Error())
}
return nil, errs
}

@vdaas-ci
Copy link
Collaborator Author

vdaas-ci commented Oct 8, 2024

[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

@vankichi vankichi merged commit 4dc9354 into release/v1.7 Oct 8, 2024
48 of 50 checks passed
@vankichi vankichi deleted the backport/release/v1.7/refactor/pkg/fix-agent-handler branch October 8, 2024 06:08
Copy link

codecov bot commented Oct 8, 2024

Codecov Report

Attention: Patch coverage is 1.00000% with 99 lines in your changes missing coverage. Please review.

Please upload report for BASE (release/v1.7@acd2f0a). Learn more about missing BASE report.

Files with missing lines Patch % Lines
pkg/agent/core/ngt/handler/grpc/linear_search.go 0.00% 30 Missing ⚠️
pkg/agent/core/ngt/handler/grpc/search.go 0.00% 30 Missing ⚠️
pkg/agent/core/ngt/handler/grpc/remove.go 0.00% 13 Missing ⚠️
pkg/agent/core/ngt/handler/grpc/upsert.go 0.00% 9 Missing ⚠️
pkg/agent/core/ngt/handler/grpc/object.go 0.00% 6 Missing ⚠️
pkg/agent/core/ngt/handler/grpc/update.go 0.00% 6 Missing ⚠️
pkg/agent/core/ngt/handler/grpc/insert.go 16.66% 4 Missing and 1 partial ⚠️
Additional details and impacted files
@@               Coverage Diff               @@
##             release/v1.7    #2679   +/-   ##
===============================================
  Coverage                ?   24.02%           
===============================================
  Files                   ?      539           
  Lines                   ?    47117           
  Branches                ?        0           
===============================================
  Hits                    ?    11322           
  Misses                  ?    35026           
  Partials                ?      769           

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

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