Skip to content

Conversation

LinZhihao-723
Copy link
Member

@LinZhihao-723 LinZhihao-723 commented Feb 18, 2025

Description

This PR syncs with the latest CLP core to support auto-generated kv-pairs with the following changes:

  • Update StructuredIrUnitHandler signature to handle auto-generated key insertion.
    • Currently, auto-generated key insertion will be peacefully ignored. We will properly handle them in the future PRs.
    • As a result, the timestmap/loglevel filtering won't work for auto-generated keys. We will fix it in future PRs.
  • Update StructuredIrStreamReader::decode_range to return both auto-generated and user-generated kv-pairs.
    • Two kv-pairs are packed into one JSON string with the schema of {"auto-generated": {}, "user-generated": {}}

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

Use the following js script to read IR streams (modified from #30):

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

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

    console.time("perf")
    const Module = await ModuleInit()

    console.log(Module.MERGED_KV_PAIRS_AUTO_GENERATED_KEY);
    console.log(Module.MERGED_KV_PAIRS_USER_GENERATED_KEY);

    try {
        // const decoder = new Module.ClpStreamReader(new Uint8Array(file), {timestampKey: "@timestamp"})
        const decoder = new Module.ClpStreamReader(new Uint8Array(file), {timestampKey: "@t", logLevelKey: "@l"})
        console.log("type:", decoder.getIrStreamType() === Module.IrStreamType.STRUCTURED,
            decoder.getIrStreamType() === Module.IrStreamType.UNSTRUCTURED)
        const numEvents = decoder.deserializeStream()
        console.log(numEvents)
        const results = decoder.decodeRange(0, numEvents, false)
        console.log(results)
    } catch (e) {
        console.error("Exception caught:", e.stack)
    }
    console.timeEnd("perf")
}

void main()

Streams being tested:

  • test-irv2.clp.zip: An IR stream that contains no auto-generated kv-pairs.
  • test.clp.zip: An IR stream generated using clp-loglib-py, which structures all log-event-level metadata in auto-generated kv-pairs.

Ensured that both streams can be successfully read into expected JSON strings.

Summary by CodeRabbit

Summary by CodeRabbit

  • Refactor
    • Improved error handling for log event JSON responses, resulting in more consistent data outputs.
    • Enhanced the processing of log events and schema tree node insertions to better distinguish between auto-generated and user-provided information.
  • Chores
    • Updated an internal dependency to a new version, contributing to improved system stability.

Copy link

coderabbitai bot commented Feb 18, 2025

Walkthrough

This pull request refines methods in the IR handling components. In the StructuredIrStreamReader, the decode_range method has been updated to streamline error handling and JSON serialization by removing an intermediate variable and using has_error(). In the StructuredIrUnitHandler, the handle_log_event method now processes user-generated node data, while the handle_schema_tree_node_insertion method is enhanced with a boolean parameter to manage auto-generated keys. Additionally, the submodule commit reference for the CLP subproject has been updated.

Changes

Files Change Summary
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp Modified the decode_range method: removed the temporary JSON string variable, replaced the error check with has_error(), and now combines "auto-generated" and "user-generated" components into a JSON object serialized using dump_json_with_replace. Added constants for merged JSON keys.
src/clp_ffi_js/ir/StructuredIrUnitHandler.cpp Updated handle_log_event to use user-generated node ID-value pairs; modified handle_schema_tree_node_insertion to include a new is_auto_generated parameter that bypasses processing for auto-generated nodes.
src/clp_ffi_js/ir/StructuredIrUnitHandler.hpp Updated the method signature of handle_schema_tree_node_insertion to add the boolean parameter is_auto_generated.
src/submodules/clp Updated the submodule commit from 31de766ecc3175b1fa472d12881587e3673294de to 2aa5c5c713b15f7b7dd911a746e386b306a95242.

Possibly related PRs

Suggested reviewers

  • junhaoliao
  • davemarco
  • kirkrodrigues
✨ 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
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.

See comments

auto const json_result{log_event.serialize_to_json()};
if (false == json_result.has_value()) {
auto error_code{json_result.error()};
auto json_result{log_event.serialize_to_json()};
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you refactor the loop in UnstructuredIrStreamReader.cpp to use has_error() as well? There is a very similar log_event_to_string function

Copy link
Member Author

Choose a reason for hiding this comment

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

I think we should do it in another PR though

Copy link
Member Author

Choose a reason for hiding this comment

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

Just double-checked. has_error has been used in other places correctly. In UnstructuredIrStreamReader.cpp, has_value() is used because the return type is std::optional.

davemarco
davemarco previously approved these changes Feb 19, 2025
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.

Look reasonable to me

Comment on lines 31 to 32
constexpr std::string_view cAutoGeneratedKey{"auto-generated"};
constexpr std::string_view cUserGeneratedKey{"user-generated"};
Copy link
Member

Choose a reason for hiding this comment

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

shall we export those two strings in the Emscripten binding at

EMSCRIPTEN_BINDINGS(ClpStreamReader) {

so that the Log Viewer can import those strings from clp-ffi-js?

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Contributor

@davemarco davemarco Feb 19, 2025

Choose a reason for hiding this comment

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

@junhaoliao, we aren't doing this for most constants, for example the strings above (ReaderOptionsKeys) are duplicates

Copy link
Member

Choose a reason for hiding this comment

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

The ReaderOptionsKeys are fine not to be exported because we do have those specified in the TypeScript definitions:

"{logLevelKey: string, timestampKey: string} | null"

however, if we need to parse the string as a JSON from the decoded results, i think it's better if we can avoid using magic strings as keys to extract the two objects.

Copy link
Contributor

Choose a reason for hiding this comment

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

I dont really have a preference @LinZhihao-723 can do what he prefers

Copy link
Member Author

Choose a reason for hiding this comment

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

fixed

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/StructuredIrStreamReader.cpp (1)

153-168: Consider extracting the JSON merging logic into a separate function.

The JSON merging logic could be moved to a dedicated function to improve readability and reusability. This would also make the lambda function more focused on its primary responsibility.

Here's a suggested refactor:

+    auto merge_kv_pairs = [](auto&& auto_generated, auto&& user_generated) {
+        return nlohmann::json{
+            {std::string{cMergedKvPairsAutoGeneratedKey}, std::forward<decltype(auto_generated)>(auto_generated)},
+            {std::string{cMergedKvPairsUserGeneratedKey}, std::forward<decltype(user_generated)>(user_generated)}
+        };
+    };
+
     auto log_event_to_string = [](StructuredLogEvent const& log_event) -> std::string {
         auto json_pair_result{log_event.serialize_to_json()};
         if (json_pair_result.has_error()) {
             auto const error_code{json_pair_result.error()};
             SPDLOG_ERROR(
                     "Failed to deserialize log event to JSON: {}:{}",
                     error_code.category().name(),
                     error_code.message()
             );
             return std::string{cEmptyJsonStr};
         }

         auto& [auto_generated, user_generated] = json_pair_result.value();
-        nlohmann::json const merged_kv_pairs
-                = {{std::string{cMergedKvPairsAutoGeneratedKey}, std::move(auto_generated)},
-                   {std::string{cMergedKvPairsUserGeneratedKey}, std::move(user_generated)}};
-        return dump_json_with_replace(merged_kv_pairs);
+        return dump_json_with_replace(merge_kv_pairs(std::move(auto_generated), std::move(user_generated)));
     };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd923c9 and a6b70c5.

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}`: - Prefer `false == ...

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

  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp
🪛 Cppcheck (2.10-2)
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp

[error] 48-48: syntax error

(syntaxError)

⏰ 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/StructuredIrStreamReader.cpp (2)

32-33: LGTM! Well-defined constants.

The constants follow the project's naming convention and are properly defined as constexpr std::string_view.


48-57: LGTM! Well-implemented Emscripten bindings.

The constants are properly exported and converted to std::string, which will help avoid magic strings in the JavaScript code.

🧰 Tools
🪛 Cppcheck (2.10-2)

[error] 48-48: syntax error

(syntaxError)

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/StructuredIrStreamReader.cpp (1)

153-169: LGTM! The decode_range changes effectively handle auto-generated key-value pairs.

The implementation correctly:

  • Uses structured binding to unpack the auto-generated and user-generated pairs
  • Handles errors appropriately
  • Creates a well-structured JSON output

Consider extracting the JSON structure creation into a separate function for better reusability:

 auto log_event_to_string = [](StructuredLogEvent const& log_event) -> std::string {
     auto json_pair_result{log_event.serialize_to_json()};
     if (json_pair_result.has_error()) {
         auto const error_code{json_pair_result.error()};
         SPDLOG_ERROR(
                 "Failed to deserialize log event to JSON: {}:{}",
                 error_code.category().name(),
                 error_code.message()
         );
         return std::string{cEmptyJsonStr};
     }

-    auto& [auto_generated, user_generated] = json_pair_result.value();
-    nlohmann::json const merged_kv_pairs
-            = {{std::string{cMergedKvPairsAutoGeneratedKey}, std::move(auto_generated)},
-               {std::string{cMergedKvPairsUserGeneratedKey}, std::move(user_generated)}};
-    return dump_json_with_replace(merged_kv_pairs);
+    return create_merged_kv_pairs_json(json_pair_result.value());
 };

+auto create_merged_kv_pairs_json(auto const& [auto_generated, user_generated]) -> std::string {
+    nlohmann::json const merged_kv_pairs
+            = {{std::string{cMergedKvPairsAutoGeneratedKey}, std::move(auto_generated)},
+               {std::string{cMergedKvPairsUserGeneratedKey}, std::move(user_generated)}};
+    return dump_json_with_replace(merged_kv_pairs);
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a6b70c5 and bbf7340.

📒 Files selected for processing (1)
  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,tpp,ts,tsx}`: - Prefer `false == ...

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

  • src/clp_ffi_js/ir/StructuredIrStreamReader.cpp
🪛 Cppcheck (2.10-2)
src/clp_ffi_js/ir/StructuredIrStreamReader.cpp

[error] 48-48: syntax error

(syntaxError)

⏰ 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/StructuredIrStreamReader.cpp (2)

16-16: LGTM! The new include and constants are well-defined.

The new constants follow the existing naming convention and are appropriately scoped.

Also applies to: 32-33


48-57: LGTM! The Emscripten bindings are correctly implemented.

The constants are properly exported for use in JavaScript/TypeScript, which aligns with the discussion in past review comments about making these keys available to the Log Viewer.

🧰 Tools
🪛 Cppcheck (2.10-2)

[error] 48-48: syntax error

(syntaxError)

@davemarco
Copy link
Contributor

title: feat: Add support to decode auto-generated kv-pairs in Structured IR streams.

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.

Latest changes look reasonable - see title

@LinZhihao-723
Copy link
Member Author

Latest changes look reasonable - see title

Shall we call it "deserialize" to match our glossary?

@davemarco
Copy link
Contributor

davemarco commented Feb 20, 2025

Shall we call it "deserialize" to match our glossary?

We are using deserialize ("to load into c++ objects") and decode ("to string") in this lib. I feel like we are doing both in this PR.
feat: Add support for deserializing and decoding auto-generated keys in Structured IR streams.

@LinZhihao-723 LinZhihao-723 changed the title feat: Add support for reading auto-generated kv-pairs using StructuredIrStreamReader. feat: Add support for deserializing and decoding auto-generated keys in Structured IR streams. Feb 20, 2025
@LinZhihao-723 LinZhihao-723 merged commit 983da6f into y-scope:main Feb 20, 2025
4 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.

4 participants