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

fix: Use std::nothrow to disable exceptions throwing in new operators (fixes #103). #105

Merged
merged 1 commit into from
Dec 8, 2024

Conversation

LinZhihao-723
Copy link
Member

@LinZhihao-723 LinZhihao-723 commented Dec 8, 2024

Description

This PR fixes #103.
For all new operators, we now use std::nothrow to explicitly disable exception throwing. As a result, we need to check manually whether the returned pointer is null and set out-of-memory errors accordingly.

Validation performed

  • Ensure workflows passed.

Summary by CodeRabbit

  • New Features

    • Enhanced memory management and error handling across various components, ensuring improved stability during memory allocation.
  • Bug Fixes

    • Implemented robust error handling for memory allocation failures, preventing potential crashes and ensuring appropriate error messages are raised.
  • Documentation

    • Updated comments and documentation strings for clarity regarding method parameters and expected behaviors.

Copy link

coderabbitai bot commented Dec 8, 2024

Walkthrough

The pull request introduces modifications across several files, primarily enhancing memory management and error handling by utilizing new (std::nothrow) for memory allocations. This approach allows for null pointer returns on allocation failures, enabling the implementation of appropriate error handling mechanisms, such as setting Python runtime errors. The changes affect various classes, including DeserializerBufferReader, PyDeserializer, PyKeyValuePairLogEvent, PyLogEvent, PyMetadata, PyQuery, and PySerializer, ensuring that memory allocation issues are managed more robustly.

Changes

File Path Change Summary
src/clp_ffi_py/ir/native/DeserializerBufferReader.cpp Enhanced error handling and memory management in the create method using new (std::nothrow).
src/clp_ffi_py/ir/native/PyDeserializer.cpp Updated memory allocation for m_deserializer and m_deserialized_log_event to use new (std::nothrow).
src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp Improved memory allocation in init and added exception handling in to_dict method.
src/clp_ffi_py/ir/native/PyLogEvent.cpp Modified memory allocation strategy in init method to use new (std::nothrow).
src/clp_ffi_py/ir/native/PyMetadata.cpp Enhanced error handling in init methods with new (std::nothrow) for memory allocation.
src/clp_ffi_py/ir/native/PyQuery.cpp Updated init method for m_query allocation to use new (std::nothrow) and improved error handling.
src/clp_ffi_py/ir/native/PySerializer.cpp Changed memory allocation in constructor for m_serializer to new (std::nothrow) and improved error handling.

Assessment against linked issues

Objective Addressed Explanation
Misuse of checking nullptr returned from new (103)

Possibly related PRs

Suggested reviewers

  • haiqi96

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.

@LinZhihao-723 LinZhihao-723 requested a review from haiqi96 December 8, 2024 03:15
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
src/clp_ffi_py/ir/native/PyDeserializer.cpp (1)

292-297: Consider tracking the TODO comment for future improvement.

While the implementation correctly uses std::nothrow, the TODO comment indicates that a more appropriate error code should be used when user-defined error codes are supported.

Would you like me to create a GitHub issue to track this TODO item for implementing proper error codes?

src/clp_ffi_py/ir/native/PyQuery.cpp (1)

Line range hint 632-644: LGTM! Proper handling of memory allocation failure.

The implementation correctly uses new (std::nothrow) and checks for allocation failure, setting an appropriate Python runtime error when allocation fails. This change aligns with the PR objectives to improve memory allocation failure handling.

However, the code readability could be improved by extracting the allocation into a separate function.

Consider extracting the allocation into a separate function to improve readability:

-        m_query = new (std::nothrow)
-                Query(search_time_lower_bound,
-                      search_time_upper_bound,
-                      wildcard_queries,
-                      search_time_termination_margin);
+        m_query = create_query(
+            search_time_lower_bound,
+            search_time_upper_bound,
+            wildcard_queries,
+            search_time_termination_margin);

Add this helper function:

private:
    static auto create_query(
        clp::ir::epoch_time_ms_t search_time_lower_bound,
        clp::ir::epoch_time_ms_t search_time_upper_bound,
        std::vector<WildcardQuery> const& wildcard_queries,
        clp::ir::epoch_time_ms_t search_time_termination_margin
    ) -> Query* {
        return new (std::nothrow) Query(
            search_time_lower_bound,
            search_time_upper_bound,
            wildcard_queries,
            search_time_termination_margin);
    }
src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp (1)

646-647: LGTM: Proper use of std::nothrow for memory allocation

The change correctly implements exception-free memory allocation with proper null pointer checking. This fixes the issue #103 by allowing proper handling of out-of-memory conditions.

Consider making the error message more specific:

-                get_c_str_from_constexpr_string_view(clp_ffi_py::cOutOfMemoryError)
+                "Failed to allocate memory for KeyValuePairLogEvent"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b15c040 and 43719c8.

📒 Files selected for processing (7)
  • src/clp_ffi_py/ir/native/DeserializerBufferReader.cpp (2 hunks)
  • src/clp_ffi_py/ir/native/PyDeserializer.cpp (4 hunks)
  • src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp (2 hunks)
  • src/clp_ffi_py/ir/native/PyLogEvent.cpp (2 hunks)
  • src/clp_ffi_py/ir/native/PyMetadata.cpp (3 hunks)
  • src/clp_ffi_py/ir/native/PyQuery.cpp (2 hunks)
  • src/clp_ffi_py/ir/native/PySerializer.cpp (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
src/clp_ffi_py/ir/native/DeserializerBufferReader.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

src/clp_ffi_py/ir/native/PyDeserializer.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

src/clp_ffi_py/ir/native/PyMetadata.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

src/clp_ffi_py/ir/native/PyQuery.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

src/clp_ffi_py/ir/native/PyLogEvent.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

src/clp_ffi_py/ir/native/PySerializer.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

📓 Learnings (4)
src/clp_ffi_py/ir/native/DeserializerBufferReader.cpp (1)
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#89
File: src/clp_ffi_py/ir/native/DeserializerBufferReader.hpp:57-58
Timestamp: 2024-11-16T03:46:52.844Z
Learning: In the `DeserializerBufferReader` class (`src/clp_ffi_py/ir/native/DeserializerBufferReader.hpp`), the `try_seek_from_begin` method should only be implemented when there is a specific use case requiring seek functionality.
src/clp_ffi_py/ir/native/PyDeserializer.cpp (4)
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#90
File: src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp:653-675
Timestamp: 2024-11-16T03:42:40.523Z
Learning: In `src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp`, within the function `PyKeyValuePairLogEvent::to_dict`, only `clp::TraceableException` needs to be caught, as no other `std::exception`s can be thrown.
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#94
File: src/clp_ffi_py/ir/native/PyDeserializer.cpp:218-242
Timestamp: 2024-11-23T05:55:57.106Z
Learning: In `src/clp_ffi_py/ir/native/PyDeserializer.cpp`, the `deserialize_log_event` method in the `PyDeserializer` class ensures proper loop termination and does not risk infinite loops, even when handling incomplete or corrupted streams.
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#94
File: src/clp_ffi_py/ir/native/PyDeserializer.cpp:206-208
Timestamp: 2024-11-23T05:55:08.019Z
Learning: In code interfacing with CPython (e.g., `src/clp_ffi_py/ir/native/PyDeserializer.cpp`), using raw pointers for memory management is acceptable due to CPython's memory management requirements.
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#94
File: src/clp_ffi_py/ir/native/PyDeserializer.hpp:246-248
Timestamp: 2024-11-23T05:54:37.767Z
Learning: In the `src/clp_ffi_py/ir/native` module, raw pointers with `gsl::owner` are intentionally used instead of `std::unique_ptr` to comply with CPython's memory management requirements.
src/clp_ffi_py/ir/native/PySerializer.cpp (1)
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#83
File: src/clp_ffi_py/ir/native/PySerializer.hpp:73-76
Timestamp: 2024-11-19T01:13:58.505Z
Learning: In the `PySerializer` class in `src/clp_ffi_py/ir/native/PySerializer.hpp`, the `close_serializer()` method never fails, so additional error handling in the `clean()` method is unnecessary.
src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp (2)
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#81
File: src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.hpp:0-0
Timestamp: 2024-11-14T06:30:18.577Z
Learning: In `PyKeyValuePairLogEvent`, we assume invalid objects will never be created, so null pointer checks in methods like `get_kv_pair_log_event()` are unnecessary, assuming CPython system runs correctly.
Learnt from: LinZhihao-723
PR: y-scope/clp-ffi-py#90
File: src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp:653-675
Timestamp: 2024-11-16T03:42:40.523Z
Learning: In `src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp`, within the function `PyKeyValuePairLogEvent::to_dict`, only `clp::TraceableException` needs to be caught, as no other `std::exception`s can be thrown.
🔇 Additional comments (7)
src/clp_ffi_py/ir/native/DeserializerBufferReader.cpp (1)

30-39: LGTM! Proper implementation of memory allocation failure handling.

The implementation correctly uses std::nothrow and handles allocation failures by setting an appropriate error message, which aligns with the PR objectives.

src/clp_ffi_py/ir/native/PyMetadata.cpp (2)

Line range hint 233-240: LGTM! Consistent error handling implementation.

The implementation correctly uses std::nothrow and follows the established pattern for handling allocation failures.


247-254: LGTM! Proper error handling within exception handling context.

The implementation correctly handles memory allocation failures while maintaining proper exception handling context.

src/clp_ffi_py/ir/native/PyDeserializer.cpp (1)

205-215: LGTM! Proper handling of complex type allocation.

The implementation correctly uses std::nothrow with template types and maintains consistent error handling patterns.

src/clp_ffi_py/ir/native/PyLogEvent.cpp (1)

Line range hint 499-507: LGTM! Proper handling of memory allocation failure.

The implementation correctly uses new (std::nothrow) and checks for allocation failure, setting an appropriate Python runtime error when allocation fails. This change aligns with the PR objectives to improve memory allocation failure handling.

src/clp_ffi_py/ir/native/PySerializer.cpp (1)

Line range hint 405-412: LGTM! Proper handling of memory allocation failure.

The implementation correctly uses new (std::nothrow) and checks for allocation failure, setting an appropriate Python runtime error when allocation fails. This change aligns with the PR objectives to improve memory allocation failure handling.

src/clp_ffi_py/ir/native/PyKeyValuePairLogEvent.cpp (1)

7-7: LGTM: Required header for std::nothrow

The addition of the <new> header is necessary for using std::nothrow in memory allocations.

= new (std::nothrow) clp::ffi::KeyValuePairLogEvent{std::move(log_event)};
if (nullptr == m_deserialized_log_event) {
// TODO: Set this to a proper error code when user-defined error code is supported.
return IRErrorCode::IRErrorCode_Eof;
Copy link
Contributor

Choose a reason for hiding this comment

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

maybe we should return IRErrorCode::NoMem.
Unfortuately it will require updating clp repo so obviously out of scope of this PR, lol

Copy link
Member Author

Choose a reason for hiding this comment

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

Sigh, correct. I'm trying to proceed error handling improvements. Hopefully we will have the user-defined user code supported soon.

Copy link
Contributor

@haiqi96 haiqi96 left a comment

Choose a reason for hiding this comment

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

The change looks reasonable.

Title is also good.

@LinZhihao-723 LinZhihao-723 merged commit 118b45d into y-scope:main Dec 8, 2024
63 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Misuse of checking nullptr returned from new.
2 participants