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

feat: Support search logs by timestamp for structured and unstructured logs. #42

Open
wants to merge 20 commits into
base: main
Choose a base branch
from

Conversation

Henry8192
Copy link
Collaborator

@Henry8192 Henry8192 commented Dec 19, 2024

Description

Adds getLogEventIndexByTimestamp API in clp_ffi_js/ir/StreamReader.cpp for ClpStreamReader. It returns null only if there are no log events. Otherwise, it would search logs in "best effort", which means it returns the last index smaller than the timestamp if no exact timestamp match, unless all log event timestamps are larger than the target. In that case, return the first log event index.

In clp_ffi_js/ir/StreamReader.hpp, implements generic_get_log_event_index_by_timestamp(), the core logic (basically just binary search) for finding log events by timestamp.
This function is called both by StructuredIrStreamReader and UnstructuredIrStreamReader's get_log_event_index_by_timestamp.

Validation performed

Use the following javascript for testing structured and unstructured logs:

import ModuleInit from "./cmake-build-debug/ClpFfiJs-node.js"
import fs from "node:fs"

const main = async () => {
    const file = fs.readFileSync("./test-1K.clp.zst")

    console.time("perf")
    const Module = await ModuleInit()
    try {
        const decoder = new Module.ClpStreamReader(new Uint8Array(file), {logLevelKey: "$log_level", timestampKey: "$timestamp"})
        console.log("type:", decoder.getIrStreamType() === Module.IrStreamType.STRUCTURED ? "structured" : "unstructured")
        const numEvents = decoder.deserializeStream()
        console.log(numEvents)
        const results = decoder.decodeRange(0, numEvents, false)
        console.log(results)
        const logEventIdx = decoder.getLogEventIndexByTimestamp(1736183181284)
        console.log(logEventIdx)
    } catch (e) {
        console.error("Exception caught:", e.stack)
    }
    console.timeEnd("perf")
}

void main()

Summary by CodeRabbit

  • New Features

    • Added a new method to retrieve log event indices based on timestamps across multiple stream reader classes.
    • Enhanced log event searching and indexing functionality.
  • Technical Improvements

    • Registered a new type for improved type handling.
    • Implemented a generic mechanism for timestamp-based log event index retrieval.

Copy link

coderabbitai bot commented Dec 19, 2024

Walkthrough

The pull request introduces a new method get_log_event_index_by_timestamp across multiple stream reader classes in the CLP (Compressed Log Processing) project. This method allows for retrieving the index of a log event based on a specified timestamp. The changes are consistently implemented in the StructuredIrStreamReader and UnstructuredIrStreamReader classes, enhancing their functionality to locate log events by their temporal position. The implementation leverages a generic function generic_get_log_event_idx_by_timestamp for efficient index retrieval.

Changes

File Change Summary
src/clp_ffi_js/ir/StreamReader.hpp Added virtual method get_log_event_idx_by_timestamp and generic template method generic_get_log_event_idx_by_timestamp
src/clp_ffi_js/ir/StreamReader.cpp Added new function binding for get_log_event_idx_by_timestamp and registered LogEventIdxTsType
src/clp_ffi_js/ir/StructuredIrStreamReader.hpp Added get_log_event_idx_by_timestamp method with [[nodiscard]] attribute
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp Implemented get_log_event_idx_by_timestamp method using the generic function
src/clp_ffi_js/ir/UnstructuredIrStreamReader.hpp Added get_log_event_idx_by_timestamp method with [[nodiscard]] attribute
src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp Implemented get_log_event_idx_by_timestamp method using the generic function

Sequence Diagram

sequenceDiagram
    participant Client
    participant StreamReader
    participant LogEvents
    
    Client->>StreamReader: get_log_event_idx_by_timestamp(timestamp)
    StreamReader->>LogEvents: generic_get_log_event_idx_by_timestamp(log_events, timestamp)
    LogEvents-->>StreamReader: return log event index
    StreamReader-->>Client: return index or null
Loading

Finishing Touches

  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Member

@junhaoliao junhaoliao left a comment

Choose a reason for hiding this comment

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

For future commits, you may follow https://github.com/y-scope/clp-ffi-js?tab=readme-ov-file#linting to run the linter

src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.cpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp Outdated Show resolved Hide resolved
@junhaoliao
Copy link
Member

This PR is blocking y-scope/yscope-log-viewer#152

src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
@Henry8192 Henry8192 marked this pull request as ready for review January 6, 2025 21:42
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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 32b1220 and 5221588.

📒 Files selected for processing (6)
  • src/clp_ffi_js/ir/StreamReader.cpp (2 hunks)
  • src/clp_ffi_js/ir/StreamReader.hpp (6 hunks)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp (2 hunks)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.hpp (2 hunks)
  • src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp (1 hunks)
  • src/clp_ffi_js/ir/UnstructuredIrStreamReader.hpp (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
src/clp_ffi_js/ir/UnstructuredIrStreamReader.hpp (1)

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

src/clp_ffi_js/ir/StructuredIrStreamReader.cpp (1)

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

src/clp_ffi_js/ir/StructuredIrStreamReader.hpp (1)

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

src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp (1)

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

src/clp_ffi_js/ir/StreamReader.cpp (1)

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

src/clp_ffi_js/ir/StreamReader.hpp (1)

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

🪛 GitHub Actions: lint
src/clp_ffi_js/ir/StreamReader.hpp

[error] 65-66: Code formatting violation: Static create method declaration is not properly formatted


[error] 126-126: Code formatting violation: DecodedResultsTsType return type declaration is not properly formatted


[error] 138-139: Code formatting violation: get_log_event_index_by_timestamp method declaration is not properly formatted


[error] 201-203: Code formatting violation: requires clause and its parameters are not properly formatted


[error] 301-303: Code formatting violation: requires clause and its parameters are not properly formatted

🔇 Additional comments (10)
src/clp_ffi_js/ir/UnstructuredIrStreamReader.hpp (1)

74-75: LGTM! Method declaration is well-defined.

The method signature is consistent with the base class and follows proper C++ practices with the [[nodiscard]] attribute.

src/clp_ffi_js/ir/StructuredIrStreamReader.hpp (2)

11-11: LGTM! Include directive is appropriately placed.

The addition of <clp/ir/types.hpp> provides the necessary type definitions.


78-79: LGTM! Method declaration is consistent.

The method signature matches the base class and follows the same pattern as UnstructuredIrStreamReader.

src/clp_ffi_js/ir/StructuredIrStreamReader.cpp (2)

14-14: LGTM! Include directive is appropriately placed.

The addition of <clp/ir/types.hpp> provides the necessary type definitions.


151-158: LGTM! Implementation is clean and efficient.

The implementation properly delegates to the generic function, promoting code reuse between different reader types.

src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp (1)

161-168: LGTM! Implementation is consistent with StructuredIrStreamReader.

The implementation properly uses the generic function, ensuring consistent behaviour across different reader types.

src/clp_ffi_js/ir/StreamReader.cpp (1)

132-132: LGTM! Type registration and function binding are properly implemented.

The new type registration and function binding follow the established patterns in the codebase.

Also applies to: 149-153

src/clp_ffi_js/ir/StreamReader.hpp (3)

14-14: LGTM! Include and type declaration are properly placed.

The additions follow the established patterns in the codebase.

Also applies to: 33-33


128-137: LGTM! Documentation is clear and comprehensive.

The documentation clearly explains the method's purpose, parameters, and return values.


313-331: LGTM! Implementation is efficient and handles edge cases properly.

The implementation:

  • Correctly handles empty log events
  • Uses std::upper_bound for efficient binary search
  • Properly handles the case when all timestamps are larger than the target

src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

312-312: Use Yoda condition for null check.

According to the coding guidelines, prefer false == <expression> over !<expression>.

Apply this diff:

-    if (log_events.empty()) {
+    if (true == log_events.empty()) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5221588 and abeb4f8.

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StreamReader.hpp (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

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

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: lint (ubuntu-latest)
  • GitHub Check: lint (macos-latest)
🔇 Additional comments (5)
src/clp_ffi_js/ir/StreamReader.hpp (5)

33-33: LGTM! Type declaration follows established pattern.

The declaration of LogEventIdxTsType aligns with other type declarations in the file and properly integrates with Emscripten's type system.


128-137: LGTM! Well-documented method declaration.

The documentation thoroughly explains all possible return scenarios and the method signature follows C++ best practices with appropriate use of [[nodiscard]].


138-139: Fix method declaration formatting.

The method declaration needs to be reformatted according to the linting rules.

Apply this diff:

-    [[nodiscard]] virtual auto get_log_event_index_by_timestamp(clp::ir::epoch_time_ms_t timestamp
-    ) -> LogEventIdxTsType = 0;
+    [[nodiscard]] virtual auto get_log_event_index_by_timestamp(
+            clp::ir::epoch_time_ms_t timestamp
+    ) -> LogEventIdxTsType = 0;

312-314: LGTM! Efficient implementation with proper edge case handling.

The implementation efficiently uses binary search via std::upper_bound and properly handles all edge cases:

  • Empty log events return null
  • No exact match returns the last smaller index
  • All larger timestamps return the first index

Also applies to: 315-322, 323-329


300-307: Fix requires clause formatting.

The requires clause needs to be reformatted according to the linting rules.

Apply this diff:

-requires requires(
-                 LogEventWithFilterData<LogEvent> const& event,
-                 clp::ir::epoch_time_ms_t timestamp
-         ) {
+    requires requires(LogEventWithFilterData<LogEvent> const& event,
+                     clp::ir::epoch_time_ms_t timestamp) {

@@ -129,6 +129,7 @@ EMSCRIPTEN_BINDINGS(ClpStreamReader) {
"Array<[string, bigint, number, number]>"
);
emscripten::register_type<clp_ffi_js::ir::FilteredLogEventMapTsType>("number[] | null");
emscripten::register_type<clp_ffi_js::ir::LogEventIdxTsType>("number | null");
Copy link
Member

Choose a reason for hiding this comment

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

Registering a type that is nullable is good for consistency with existing code like FilteredLogEventMapTsType.

That said, Embind seems to have added support for std::optional<> so we should look into converting functions that return nullable data into returning std::optional<> types.

https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#:~:text=For%20convenience%2C%20embind%20provides%20factory%20functions%20to%20register%20std%3A%3Avector%3CT%3E%20(register_vector())%2C%20std%3A%3Amap%3CK%2C%20V%3E%20(register_map())%2C%20and%20std%3A%3Aoptional%3CT%3E%20(register_optional())%20types%3A

For convenience, embind provides factory functions to register std::vector (register_vector()), std::map<K, V> (register_map()), and std::optional (register_optional()) types:

@coderabbitai create an issue to track this

Copy link

Choose a reason for hiding this comment

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

@junhaoliao I've created issue #51 to track this enhancement: #51

🔗 Analysis chain

@junhaoliao I've created a GitHub issue to track this enhancement. The issue has been assigned to you and includes details about the current state and the proposed changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Create a GitHub issue to track the conversion of nullable types to std::optional
gh issue create \
  --title "refactor: Convert nullable Embind types to use std::optional" \
  --body "## Background

Currently, we register nullable types in Embind using custom type definitions that map to 'T | null' in TypeScript. For example:
- \`FilteredLogEventMapTsType\` -> \`number[] | null\`
- \`LogEventIdxTsType\` -> \`number | null\`

Embind now provides built-in support for \`std::optional<T>\` through the \`register_optional()\` function, as documented [here](https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html).

## Proposed Changes
Convert all nullable type registrations to use \`std::optional<T>\` with \`register_optional()\`.

## References
- Discussion: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/42#discussion_r1905740583" \
  --assignee junhaoliao

Length of output: 792


✏️ Learnings added
Learnt from: junhaoliao
PR: y-scope/clp-ffi-js#42
File: src/clp_ffi_js/ir/StreamReader.cpp:132-132
Timestamp: 2025-01-07T16:26:06.449Z
Learning: Embind supports std::optional<T> through register_optional() function, which should be preferred over custom nullable type definitions (T | null) for better type safety and consistency.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Member

Choose a reason for hiding this comment

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

we should look into converting functions...

in a separate PR i meant, so we should create an issue to track the effort

Copy link

Choose a reason for hiding this comment

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

@junhaoliao I had already created issue #51 to track this effort in response to your previous comment. The issue will help track the conversion of nullable types to std::optional in a separate PR.

src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
@@ -163,7 +177,6 @@ class StreamReader {
* @tparam LogEvent
* @param log_level_filter
* @param log_events Derived class's log events.
* @param log_events
Copy link
Member

Choose a reason for hiding this comment

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

was it a mistake?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

isn't it duplicated?

Copy link
Member

Choose a reason for hiding this comment

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

Let's revert the change and fix it in another PR. I think we should also add docs for filtered_log_event_map.

src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
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: 2

🧹 Nitpick comments (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

196-203: Move requires clause to a concept.

The requires clause is duplicated. Consider moving it to a concept for better maintainability and reusability.

Create a new concept before the class definition:

template <typename T>
concept HasTimestamp = requires(T const& event, clp::ir::epoch_time_ms_t timestamp) {
    { event.get_timestamp() } -> std::convertible_to<clp::ir::epoch_time_ms_t>;
};

Then simplify the template declarations:

template <typename LogEvent>
requires HasTimestamp<LogEventWithFilterData<LogEvent>>

Also applies to: 296-303

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between abeb4f8 and 6647fbd.

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StreamReader.hpp (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

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

🪛 GitHub Actions: lint
src/clp_ffi_js/ir/StreamReader.hpp

[error] 133-133: Code formatting violation: incorrect formatting around timestamp parameter documentation


[error] 326-326: Code formatting violation: incorrect formatting in variable declaration and initialization

🔇 Additional comments (3)
src/clp_ffi_js/ir/StreamReader.hpp (3)

33-33: LGTM! Type declaration is well-placed and consistent.

The new type LogEventIdxTsType follows the established naming convention and is appropriately grouped with other output types.


137-138: LGTM! Method signature is well-defined.

The virtual method declaration follows the class's pattern and correctly specifies its pure virtual nature.


133-133: ⚠️ Potential issue

Fix documentation formatting.

The parameter documentation needs proper formatting according to the linting rules.

Apply this diff to fix the formatting:

-     * @param timestamp The timestamp to search for, in milliseconds since the Unix epoch.
+     * @param timestamp
+     *        The timestamp to search for, in milliseconds since the Unix epoch.

Likely invalid or redundant comment.

🧰 Tools
🪛 GitHub Actions: lint

[error] 133-133: Code formatting violation: incorrect formatting around timestamp parameter documentation

src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
src/clp_ffi_js/ir/StreamReader.hpp Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (2)
src/clp_ffi_js/ir/StreamReader.hpp (2)

145-156: Consider adding a usage example in the documentation.

The documentation is comprehensive but would benefit from a concrete example demonstrating the return values for different scenarios (exact match, approximate match, no match).

     * @return null if no log event exists in the stream.
+     *
+     * @example
+     * For a stream with events at timestamps [100, 200, 300]:
+     * get_log_event_index_by_timestamp(150) returns 0 (index of timestamp 100)
+     * get_log_event_index_by_timestamp(200) returns 1 (exact match)
+     * get_log_event_index_by_timestamp(400) returns 2 (index of timestamp 300)
     */

297-323: Add defensive checks for index calculations.

While the implementation is efficient using binary search, consider adding safety checks:

     auto const upper_index{std::distance(log_events.begin(), upper)};
+    // Check for potential overflow
+    if (upper_index == 0) {
+        return LogEventIdxTsType{emscripten::val::null()};
+    }
     auto const index{upper_index - 1};
+    // Validate index is within bounds
+    if (index >= log_events.size()) {
+        return LogEventIdxTsType{emscripten::val::null()};
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 046191e and c400361.

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StreamReader.hpp (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

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

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: lint (ubuntu-latest)
  • GitHub Check: lint (macos-latest)
🔇 Additional comments (3)
src/clp_ffi_js/ir/StreamReader.hpp (3)

14-14: LGTM! The new include and type declaration are well-placed.

The addition of <clp/ir/types.hpp> and LogEventIdxTsType declaration aligns with the PR's objective of supporting timestamp-based search functionality.

Also applies to: 33-33


49-64: Well-structured concept definitions!

The introduction of GetLogEventIdxInterface and DecodeRangeInterface concepts improves code clarity and maintainability. The concepts effectively encapsulate the requirements for timestamp operations and string conversion respectively.


310-312: Verify timestamp comparison edge cases.

The current comparison assumes timestamps are always valid. Consider verifying how the code handles:

  • Negative timestamps
  • Maximum timestamp values
  • Timestamp overflow scenarios
✅ Verification successful

Timestamp comparison implementation is verified safe

The current implementation correctly handles all edge cases:

  • Uses consistent type system across the codebase
  • Preserves ordering for all possible values including zero, negative, and maximum values
  • Handles missing timestamps gracefully by defaulting to zero
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for timestamp validation or handling in the codebase
rg -l "epoch_time_ms_t" | xargs rg -B2 -A2 "(numeric_limits|MAX|MIN|overflow|underflow)"

# Check if there are any existing test cases for timestamp edge cases
fd -e cpp -e hpp test_.*timestamp | xargs rg -A 5 "TEST.*timestamp"

Length of output: 160


Script:

#!/bin/bash
# Find timestamp type definition and usage
ast-grep --pattern 'using epoch_time_ms_t = $_'

# Find timestamp comparisons
ast-grep --pattern 'get_timestamp()'

# Look for test files that might contain timestamp tests
fd -e cpp -e hpp test_ | xargs rg -B2 -A2 "epoch_time_ms_t"

Length of output: 6520

@Henry8192 Henry8192 requested a review from junhaoliao January 9, 2025 18:45
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

🧹 Nitpick comments (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

202-213: Consider enhancing the documentation.

The documentation could be more comprehensive. Consider adding details about:

  • The algorithm used (binary search)
  • Edge cases handling
  • Performance characteristics
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c400361 and ca4a616.

📒 Files selected for processing (6)
  • src/clp_ffi_js/ir/StreamReader.cpp (2 hunks)
  • src/clp_ffi_js/ir/StreamReader.hpp (7 hunks)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp (2 hunks)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.hpp (2 hunks)
  • src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp (1 hunks)
  • src/clp_ffi_js/ir/UnstructuredIrStreamReader.hpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.hpp
  • src/clp_ffi_js/ir/StreamReader.cpp
  • src/clp_ffi_js/ir/UnstructuredIrStreamReader.hpp
  • src/clp_ffi_js/ir/UnstructuredIrStreamReader.cpp
  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp
🧰 Additional context used
📓 Path-based instructions (1)
src/clp_ffi_js/ir/StreamReader.hpp (1)

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

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: lint (ubuntu-latest)
  • GitHub Check: lint (macos-latest)
🔇 Additional comments (6)
src/clp_ffi_js/ir/StreamReader.hpp (6)

14-14: LGTM! Include statement added as suggested.

The addition of clp/ir/types.hpp is appropriate for using the clp::ir::epoch_time_ms_t type.


33-33: LGTM! Type declaration follows established pattern.

The declaration of LogEventIdxTsType aligns with the existing TypeScript type declarations in the file.


49-57: LGTM! Well-defined concept for timestamp retrieval.

The concept properly constrains the LogEvent type to ensure it provides a timestamp that's convertible to clp::ir::epoch_time_ms_t.


59-64: LGTM! Good refactoring to use a concept.

Moving the requirements to a named concept improves code organization and reusability.


145-156: LGTM! Well-documented method declaration.

The method declaration is properly marked as [[nodiscard]] and includes comprehensive documentation of parameters and return values.


297-323: LGTM! Efficient implementation with proper edge case handling.

The implementation uses std::upper_bound for efficient binary search and correctly handles all edge cases as documented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants