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 24 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_idx_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 StreamReader, 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, declared new type LogEventIdxTsType
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 (Beta)

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) {

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
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.

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

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

49-64: Consider extracting the timestamp comparison lambda into the concept.

The concepts are well-defined, but the timestamp comparison lambda in generic_get_log_event_idx_by_timestamp could be moved into the GetLogEventIdxInterface concept for better reusability and consistency.

 template <typename LogEvent>
 concept GetLogEventIdxInterface = requires(
         LogEventWithFilterData<LogEvent> const& event,
         clp::ir::epoch_time_ms_t timestamp
 ) {
     {
         event.get_timestamp()
     } -> std::convertible_to<clp::ir::epoch_time_ms_t>;
+    {
+        timestamp < event.get_timestamp()
+    } -> std::convertible_to<bool>;
 };

298-324: Consider using std::prev for better readability.

The implementation is efficient and handles all edge cases correctly. However, the index calculation could be more concise using std::prev.

-    auto const upper_index{std::distance(log_events.begin(), upper)};
-    auto const index{upper_index - 1};
-
-    return LogEventIdxTsType{emscripten::val(index)};
+    return LogEventIdxTsType{emscripten::val(
+        std::distance(log_events.begin(), std::prev(upper))
+    )};
📜 Review details

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

📥 Commits

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

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StreamReader.hpp (8 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] 192-192: Code formatting violation detected. The code should be clang-formatted.

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

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

The addition of <clp/ir/types.hpp> and the declaration of LogEventIdxTsType properly support the new timestamp-based search functionality.

Also applies to: 33-33


145-156: LGTM! The method declaration and documentation are comprehensive.

The virtual method is well-defined with clear documentation covering all edge cases and return values.

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)

49-64: LGTM with a suggestion for improvement!

The concepts are well-defined and improve code organization. The GetLogEventIdxInterface concept correctly ensures timestamp compatibility, and the DecodeRangeInterface concept effectively replaces the previous requires clause.

Consider moving these concepts to a separate header file for better reusability across the codebase, as suggested in the past review comments. This would align with the example in clp/components/core/src/clp/ffi/ir_stream/IrUnitHandlerInterface.hpp.


203-214: Improve method documentation.

The documentation is incomplete and contains a misplaced comment about returning the first log event index.

Consider updating the documentation to match the virtual method's documentation style, or simply reference the virtual method's documentation to avoid duplication, as suggested in past review comments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9443ba3 and db60efd.

📒 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 (5)
src/clp_ffi_js/ir/StreamReader.hpp (5)

14-14: LGTM!

The include statement for clp/ir/types.hpp is correctly added as suggested in the past review comments.


33-33: LGTM!

The declaration of LogEventIdxTsType follows the established pattern for TypeScript type declarations.


145-156: LGTM!

The virtual method declaration is well-documented with clear return value cases and proper [[nodiscard]] attribute.


298-324: LGTM!

The implementation is efficient and handles edge cases properly. The code follows the formatting and naming conventions suggested in past review comments.


177-177: LGTM!

The requires clauses consistently use the new DecodeRangeInterface concept, improving code maintainability.

Also applies to: 218-218

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)

200-211: Improve method documentation.

The documentation is missing important details:

  • Add @param log_events description
  • Clarify the return value documentation
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db60efd and 0e3e21b.

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StreamReader.hpp (6 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)

14-14: LGTM! The include statement for clp/ir/types.hpp is correctly added.


33-33: LGTM! The LogEventIdxTsType declaration is correctly added and follows the established pattern.


49-57: Consider storing the concept requirements as a constant.

The concept definition is well-structured and type-safe. However, as suggested in past review comments, consider storing these requirements in an std::concept constant to avoid repetition.


138-149: LGTM! The virtual method declaration is well-documented and properly designed.


299-325: LGTM! The implementation is efficient and handles all edge cases correctly.

The binary search approach using std::upper_bound is an excellent choice for performance, and the logic for finding the closest index is well-implemented.

junhaoliao
junhaoliao previously approved these changes Jan 10, 2025
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.

lgtm. Please wait for @davemarco 's approval before merging.

@junhaoliao junhaoliao requested a review from davemarco January 10, 2025 22:26
@junhaoliao junhaoliao dismissed their stale review January 10, 2025 22:27

Waiting for other approvers

Copy link
Contributor

@davemarco davemarco left a comment

Choose a reason for hiding this comment

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

From a high level, I noticed we aren't really considering the existing filter. Please feel free to disagree, but I think the function should only consider the filtered events more similiar to decode_range behaviour with use_filter set. This way it can be more efficient on smaller filtered logs. Secondly, also feel free to disagree. The function should probably return the ActiveLogEventIdx (see here and here) not the log event index. The log event idx isn't terrible, but now we have will need to convert it back to the active log event idx once it is returned to find the correct page. It is probably slightly more efficient to just get the activeLogEventIdx straight from the function. Anyways let me know your thoughts.

src/clp_ffi_js/ir/StreamReader.cpp Outdated Show resolved Hide resolved
@@ -44,6 +46,16 @@ using LogEvents = std::vector<LogEventWithFilterData<LogEvent>>;
*/
using FilteredLogEventsMap = std::optional<std::vector<size_t>>;

template <typename LogEvent>
Copy link
Contributor

@davemarco davemarco Jan 12, 2025

Choose a reason for hiding this comment

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

What is the difference between doing this with a concept and just having template <typename LogEvent> like the other generic functions?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Oh, this was suggested by zhihao, and one of the pros is simplify the require statement in function declaration.

We will populate this concept keyword in the next pr, since junhao wants only the necessary things to be changed

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

From a high level, I noticed we aren't really considering the existing filter. Please feel free to disagree, but I think the function should only consider the filtered events more similiar to decode_range behaviour with use_filter set. This way it can be more efficient on smaller filtered logs. Secondly, also feel free to disagree. The function should probably return the ActiveLogEventIdx (see here and here) not the log event index. The log event idx isn't terrible, but now we have will need to convert it back to the active log event idx once it is returned to find the correct page. It is probably slightly more efficient to just get the activeLogEventIdx straight from the function. Anyways let me know your thoughts.

Right, if we implement the first point, we will need the second point. Since this is only a performance optimization, it might be fine to leave that into a future PR when we have spare resources.

@Henry8192 if you think this is something quick (less than a morning) to implement, go for it

@davemarco
Copy link
Contributor

davemarco commented Jan 13, 2025

@junhaoliao Okay, Perhaps it can wait. With the binary search it probably decently fast anyways. I will review again now then with the PR as is.

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)

49-57: Add documentation for the GetLogEventIdxInterface concept.

The concept is well-defined, but it would benefit from documentation explaining its purpose and requirements.

Add a documentation block before the concept:

+/**
+ * Concept defining the requirements for log event types that can be searched by timestamp.
+ * Types satisfying this concept must provide a get_timestamp method that returns a value
+ * convertible to epoch_time_ms_t.
+ */
 template <typename LogEvent>
 concept GetLogEventIdxInterface = requires(

299-325: Consider optimizing and documenting the binary search implementation.

While the implementation is correct, consider these improvements:

  1. Add a comment explaining the binary search strategy
  2. Use std::prev for cleaner iterator manipulation

Apply this diff to improve the implementation:

 template <GetLogEventIdxInterface LogEvent>
 auto StreamReader::generic_get_log_event_idx_by_timestamp(
         LogEvents<LogEvent> const& log_events,
         clp::ir::epoch_time_ms_t timestamp
 ) -> LogEventIdxTsType {
     if (log_events.empty()) {
         return LogEventIdxTsType{emscripten::val::null()};
     }

+    // Use binary search to find the first element greater than the target timestamp
     auto upper{std::upper_bound(
             log_events.begin(),
             log_events.end(),
             timestamp,
             [](clp::ir::epoch_time_ms_t ts, LogEventWithFilterData<LogEvent> const& log_event) {
                 return ts < log_event.get_timestamp();
             }
     )};

     if (upper == log_events.begin()) {
         return LogEventIdxTsType{emscripten::val(0)};
     }

-    auto const upper_index{std::distance(log_events.begin(), upper)};
-    auto const index{upper_index - 1};
+    // Return the index of the previous element (last element <= timestamp)
+    auto const index{std::distance(log_events.begin(), std::prev(upper))};

     return LogEventIdxTsType{emscripten::val(index)};
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e3e21b and 412b96e.

📒 Files selected for processing (2)
  • src/clp_ffi_js/ir/StreamReader.cpp (2 hunks)
  • src/clp_ffi_js/ir/StreamReader.hpp (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/clp_ffi_js/ir/StreamReader.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 (2)
src/clp_ffi_js/ir/StreamReader.hpp (2)

14-14: LGTM! Type declarations and includes are well-organized.

The new include and type declaration follow the existing patterns in the codebase.

Also applies to: 33-33


138-149: LGTM! Well-documented virtual method declaration.

The method signature and documentation are clear and comprehensive.

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.

3 participants