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(clp-s): Unescape string values during ingestion and fix support for search using escape sequences. #622

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

Conversation

gibber9809
Copy link
Contributor

@gibber9809 gibber9809 commented Dec 3, 2024

Description

This PR changes the archive format of clp-s to store the unescaped versions of string values instead of the escaped version of string values, and implements fixes and missing features for search involving escape sequences.

This change to the archive format both makes it more straightforward to support correct search on escape sequences and makes it so that the archive format is consistent between the JSON ingestion path and the soon-to-be-implemented kv-pair IR ingestion path.

Dataset (new compression time / old compression time)
cockroach 1.01
mongodb 1.09
elasticsearch 1.00
spark-event-logs 0.98
postgresql 0.97
---- ----
Avg 1.01

Compression ratio is effectively unchanged (1.002x improvement in compression ratio on average.

Dataset (new decompression time / old decompression time)
cockroach 1.26
mongodb 1.04
elasticsearch 1.36
spark-event-logs 1.15
postgresql 1.14
---- ----
Avg 1.19

Overall there is effectively no change in compression performance, and only a moderate decrease in decompression performance. This performance is achieved by getting rid of string copies during compression and implementing escape for JSON strings with a fast path for strings that largely don't have to be escaped.

On the search side the KQL escaping behaviour has been nailed down, support for the \KEYWORD (e.g. \and) escape sequences has been removed, and support for the \u unicode escape sequences has been added.

The full set of escape sequences are:

sequence raw required in quoted string
\\ \ Y
\" " Y
\{ { N
\} } N
\( ( N
\) ) N
\< < N
\> > N
\* LITERAL * Y
\? LITERAL ? Y (only values)
\. LITERAL . Y (only keys)
\r <cr> Y
\n <nl> Y
\t <tab> Y
\b <bs> Y
\f <ff> Y
\uXXXX utf-8 of hex XXXX Y

Note that the LITERAL escape sequences are for getting the literal version of a character as opposed to a special character that affects the semantics of search (wildcard "*", match any single character "?", and denote nested keys keys ".").

Validation performed

  • Validated that decompression re-escapes characters 0x00-0x1f, '"', and '' to generate valid JSON.
  • Benchmarked impact on compression and decompression performance.
  • Manually validated that this PR fixes every case in the attached github issue (except for 4002 and 4003 which appear to be encountering a CLP search bug).
  • Added unit tests for escaping behaviour

Summary by CodeRabbit

  • New Features

    • Enhanced string extraction capabilities with new methods for escaping string values.
    • Improved handling of Unicode in KQL grammar.
    • Added error handling for invalid literals in KQL parsing.
    • Introduced new methods for creating descriptor tokens from escaped values.
  • Bug Fixes

    • Streamlined error checks in expression handling to prevent empty expressions.
  • Documentation

    • Expanded documentation for utility methods related to JSON and KQL string handling.
  • Refactor

    • Updated method signatures across various components to reflect changes in handling escaped tokens.
    • Refined logic for handling unresolved descriptors in schema matching.

Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Warning

Rate limit exceeded

@gibber9809 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8508084 and 1483c35.

📒 Files selected for processing (2)
  • components/core/src/clp_s/Utils.hpp (3 hunks)
  • components/core/src/clp_s/search/kql/Kql.g4 (2 hunks)

Walkthrough

This pull request introduces comprehensive changes to string handling, token processing, and escape sequence management across multiple components in the CLP (Compressed Log Processing) system. The modifications primarily focus on enhancing string escaping capabilities, improving Unicode and KQL token processing, and refining column descriptor creation. Key areas of change include utility functions for JSON and KQL string handling, column reader enhancements, and updates to parsing and serialization mechanisms.

Changes

File Change Summary
components/core/src/clp_s/ColumnReader.cpp Added extract_escaped_string_value_into_buffer methods for ClpStringColumnReader and VariableStringColumnReader; modified extract_string_value_into_buffer in BooleanColumnReader.
components/core/src/clp_s/ColumnReader.hpp Introduced virtual method extract_escaped_string_value_into_buffer in BaseColumnReader; overridden in ClpStringColumnReader and VariableStringColumnReader.
components/core/src/clp_s/JsonParser.cpp Optimized string handling using std::string_view for cur_key and value.
components/core/src/clp_s/JsonSerializer.hpp Added methods for escaping keys and values, including append_escaped_key.
components/core/src/clp_s/Utils.cpp Implemented new string escaping and unescaping utilities, including escape_json_string.
components/core/src/clp_s/search/ColumnDescriptor.* Refined token and descriptor handling with new creation methods for escaped tokens.
components/core/src/clp_s/search/kql/Kql.g4 Enhanced Unicode and escape sequence grammar, added UNICODE fragment.
components/core/tests/test-kql.cpp Updated test cases to use create_descriptor_from_escaped_token for descriptor creation.

Sequence Diagram

sequenceDiagram
    participant ColumnReader
    participant StringUtils
    participant JsonSerializer
    
    ColumnReader->>StringUtils: extract_escaped_string_value
    StringUtils-->>ColumnReader: escaped string value
    ColumnReader->>JsonSerializer: append escaped value
    JsonSerializer-->>ColumnReader: JSON string updated
Loading

Possibly Related PRs

Suggested Reviewers

  • LinZhihao-723

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.

@gibber9809 gibber9809 changed the title [WIP] feat(clp-s): Store unescaped string values in archives and fix support for search using escape sequences. [WIP] feat(clp-s): Unescape string values during ingestion and fix support for search using escape sequences. Dec 4, 2024
@gibber9809 gibber9809 changed the title [WIP] feat(clp-s): Unescape string values during ingestion and fix support for search using escape sequences. feat(clp-s): Unescape string values during ingestion and fix support for search using escape sequences. Dec 16, 2024
@gibber9809 gibber9809 marked this pull request as ready for review December 16, 2024 19:11
@gibber9809 gibber9809 requested a review from wraymo December 16, 2024 19:12
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (6)
components/core/src/clp_s/JsonParser.cpp (2)

Line range hint 245-275: Consider refactoring timestamp matching logic

The timestamp matching logic contains multiple boolean flags and a complex state machine. This could be simplified for better maintainability.

Consider extracting the timestamp matching logic into a separate method:

+private:
+    struct TimestampMatchState {
+        bool can_match = false;
+        bool may_match = false;
+        bool matches = false;
+        int longest_matching_prefix = 0;
+    };
+    
+    TimestampMatchState update_timestamp_match(
+        const TimestampMatchState& state,
+        const std::string_view& key,
+        size_t depth) {
+        TimestampMatchState new_state = state;
+        if (!new_state.can_match) return new_state;
+        
+        if (new_state.may_match) {
+            if (depth <= m_timestamp_column.size() 
+                && key == m_timestamp_column[depth - 1]) {
+                new_state.matches = (depth == m_timestamp_column.size());
+            } else {
+                new_state.longest_matching_prefix = depth - 1;
+                new_state.may_match = false;
+            }
+        }
+        return new_state;
+    }

Line range hint 352-377: Consider consolidating string type determination logic

The logic for determining whether to use ClpString or VarString based on space character presence is repeated in multiple places. This could be extracted into a helper method.

+private:
+    NodeType determine_string_type(std::string_view value) const {
+        return value.find(' ') != std::string::npos
+            ? NodeType::ClpString
+            : NodeType::VarString;
+    }
components/core/src/clp_s/Utils.hpp (1)

308-308: Fix typo in documentation

There is a typo in the word "succesfully" in the documentation for unescape_kql_internal. It should be "successfully."

Apply this diff to correct the typo:

- * @return true if the value was unescaped succesfully and false otherwise.
+ * @return true if the value was unescaped successfully, false otherwise.
components/core/src/clp_s/search/SchemaMatch.cpp (1)

80-88: Consider inserting descriptors at the beginning to avoid reversing

Currently, descriptors are added to the vector and then reversed. Inserting descriptors at the beginning can improve performance by eliminating the need for the reverse operation.

Apply this diff to modify the code:

- descriptors.emplace_back(
+ descriptors.insert(descriptors.begin(),
    DescriptorToken::create_descriptor_from_literal_token(
        node->get_key_name()
    )
);

Remove the reverse operation:

- std::reverse(descriptors.begin(), descriptors.end());
components/core/src/clp_s/ColumnReader.cpp (1)

92-105: Consider optimizing escaping by performing it during decoding

The extract_escaped_string_value_into_buffer method could be optimized by escaping strings during decoding, as suggested by the TODO comment. This change could improve performance.

Would you like assistance in implementing this optimization or opening a GitHub issue to track it?

components/core/src/clp_s/search/ColumnDescriptor.hpp (1)

71-99: Consider providing a more descriptive error message

When throwing OperationFailed due to an incomplete escape sequence, including the problematic token or additional context in the exception message would aid in debugging.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 880a741 and 0b71b46.

📒 Files selected for processing (14)
  • components/core/src/clp_s/ColumnReader.cpp (3 hunks)
  • components/core/src/clp_s/ColumnReader.hpp (3 hunks)
  • components/core/src/clp_s/JsonParser.cpp (7 hunks)
  • components/core/src/clp_s/JsonSerializer.hpp (5 hunks)
  • components/core/src/clp_s/Utils.cpp (2 hunks)
  • components/core/src/clp_s/Utils.hpp (3 hunks)
  • components/core/src/clp_s/clp-s.cpp (1 hunks)
  • components/core/src/clp_s/search/AddTimestampConditions.cpp (1 hunks)
  • components/core/src/clp_s/search/ColumnDescriptor.cpp (4 hunks)
  • components/core/src/clp_s/search/ColumnDescriptor.hpp (4 hunks)
  • components/core/src/clp_s/search/SchemaMatch.cpp (1 hunks)
  • components/core/src/clp_s/search/kql/Kql.g4 (2 hunks)
  • components/core/src/clp_s/search/kql/kql.cpp (8 hunks)
  • components/core/tests/test-kql.cpp (7 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
components/core/src/clp_s/JsonParser.cpp (1)

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

components/core/src/clp_s/search/AddTimestampConditions.cpp (1)

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

components/core/src/clp_s/clp-s.cpp (1)

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

components/core/src/clp_s/ColumnReader.hpp (1)

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

components/core/tests/test-kql.cpp (1)

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

components/core/src/clp_s/ColumnReader.cpp (1)

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

components/core/src/clp_s/Utils.cpp (1)

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

components/core/src/clp_s/JsonSerializer.hpp (1)

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

components/core/src/clp_s/Utils.hpp (1)

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

components/core/src/clp_s/search/SchemaMatch.cpp (1)

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

components/core/src/clp_s/search/ColumnDescriptor.cpp (1)

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

components/core/src/clp_s/search/ColumnDescriptor.hpp (1)

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

components/core/src/clp_s/search/kql/kql.cpp (1)

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

🔇 Additional comments (38)
components/core/src/clp_s/search/AddTimestampConditions.cpp (3)

Line range hint 10-11: Excellent use of boolean expression style!

The code correctly follows the guideline of using false == <expression> rather than !<expression>.


Line range hint 17-18: Consistent boolean expression style maintained!

The code maintains consistency with the preferred false == <expression> pattern.


21-22: Verify consistent usage of new descriptor creation method

The change to create_from_escaped_tokens aligns with the PR's objective of improving string value handling. However, let's verify consistent usage across the codebase.

✅ Verification successful

Change to create_from_escaped_tokens is correctly implemented and used consistently

The verification shows that:

  • The new method create_from_escaped_tokens is used consistently across all relevant files
  • No instances of the old create method remain in the codebase
  • The header file confirms this is the intended API, with clear documentation and proper implementation of string escaping functionality
  • The change is used in all appropriate contexts: clp-s.cpp, kql.cpp, and AddTimestampConditions.cpp
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of new method and identify any remaining old usage
# Look for both old and new method calls to ensure complete migration

echo "Checking for new method usage:"
rg "ColumnDescriptor::create_from_escaped_tokens" -A 2

echo "Checking for potential remaining old method usage:"
rg "ColumnDescriptor::create\(" -A 2

# Check for any TODO or FIXME comments related to this change
rg -i "todo.*columndescriptor|fixme.*columndescriptor"

Length of output: 1428


Script:

#!/bin/bash
# Let's verify if there are any other methods in ColumnDescriptor class
# and check their implementation to understand the complete context

echo "Checking ColumnDescriptor class implementation:"
ast-grep --pattern 'class ColumnDescriptor {
  $$$
}'

echo "Checking for any tests using these methods:"
rg -l "ColumnDescriptor.*create" "*test*"

echo "Checking header file for method declarations:"
fd "ColumnDescriptor.h" --exec cat {}

Length of output: 10376

components/core/src/clp_s/clp-s.cpp (1)

209-209: Update to create_from_escaped_tokens enhances escaped token handling

The change to use ColumnDescriptor::create_from_escaped_tokens ensures that column descriptors are correctly created from escaped tokens, aligning with the improved handling of escaped strings throughout the codebase.

components/core/src/clp_s/JsonParser.cpp (3)

66-66: Efficient use of std::string_view for key handling

The change from std::string to std::string_view for cur_key and direct assignment from unescaped_key(true) is a good optimization that avoids unnecessary string copies.

Also applies to: 84-84


134-134: Verify error handling for malformed escape sequences

With the changes to use get_string(true) for unescaped strings, we should verify proper error handling for malformed escape sequences.

Also applies to: 210-210, 352-352

✅ Verification successful

Let me gather more context about the error handling in this file.


Let me check one more aspect about the error handling specifically around the string parsing.


Let me try one last search with corrected syntax.


Based on the gathered evidence, I can now provide the final response:

Error handling for malformed escape sequences is managed at a higher level

The error handling for malformed escape sequences is already handled by the simdjson library at the document parsing level through JsonFileIterator, which captures UTF8 errors and IO errors. The get_string(true) calls are made only after successful type checking and within the context of already validated JSON documents.

  • Error handling occurs in JsonFileIterator with specific handling for simdjson::error_code::UTF8_ERROR
  • The parser has top-level error handling for simdjson::error_code::SUCCESS validation
  • String parsing is done only after type validation via ondemand::json_type::string checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check error handling for malformed escape sequences

# Search for error handling around get_string calls
rg -B 2 -A 2 "get_string.*true"

# Search for try-catch blocks that might handle simdjson errors
ast-grep --pattern 'try {
  $$$
  $obj.get_string($$$)
  $$$
} catch'

Length of output: 1479


Script:

#!/bin/bash
# Check for try-catch blocks around the usage of these string values
rg -B 5 -A 5 "case ondemand::json_type::string:"

# Look for any error handling related to simdjson
rg -B 2 -A 2 "simdjson::error"

# Check the class definition and member declarations for error handling
ast-grep --pattern 'class JsonParser {
  $$$
}'

Length of output: 10549


Script:

#!/bin/bash
# Check for any try-catch blocks in JsonParser.cpp
rg -B 3 -A 3 "try\s*{"  components/core/src/clp_s/JsonParser.cpp

# Look for string parsing related error handling
rg -B 3 -A 3 "ondemand::json_type::string.*get_string" components/core/src/clp_s/JsonParser.cpp

# Check if there's any specific string validation
rg -B 2 -A 2 "validate.*string" components/core/src/clp_s/JsonParser.cpp

Length of output: 316


Script:

#!/bin/bash
# Check for try-catch blocks with fixed regex
rg -B 3 -A 3 "try {" components/core/src/clp_s/JsonParser.cpp

# Look for error handling in the string parsing function
rg -B 3 -A 3 "get_string\(" components/core/src/clp_s/JsonParser.cpp

# Check the JsonFileIterator implementation for string handling
rg -B 3 -A 3 "parse.*string" components/core/src/clp_s/JsonFileIterator.cpp

Length of output: 1289


134-134: Verify string value lifetime management

The changes to use get_string(true) with std::string_view across multiple methods improve performance by avoiding copies. However, we should verify that the string views' lifetimes are properly managed.

Also applies to: 210-210, 352-352

✅ Verification successful

Let me analyze the string lifetime management in the codebase further by checking how the string views from get_string() are used.


Let me try a different approach to analyze the string lifetime management by checking the full context around these get_string() calls.


Let me check one more aspect to verify the simdjson string lifetime guarantees.


String lifetime management appears safe

The string_view values obtained from get_string(true) are used safely within their scope:

  • Values are immediately passed to add_node() for schema building
  • Values are stored in m_current_parsed_message which handles the string storage
  • No string_views are stored as class members in JsonParser
  • The true parameter in get_string() indicates the string memory is managed by simdjson

The current usage pattern ensures string_views don't outlive their source strings.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential string lifetime issues by finding all usages of string_view
# that might outlive the source string

# Search for string_view storage in class members or containers
rg -A 3 "string_view.*;" 

# Search for string_view being stored beyond the scope of get_string
ast-grep --pattern 'std::string_view $var = $obj.get_string($$$);
  $$$
  return $var;'

Length of output: 67062


Script:

#!/bin/bash
# Check how string_view values from get_string() are used
ast-grep --pattern 'std::string_view $var = $obj.get_string($$$);
  $$$'

# Check for any string_view member variables that might store these values
rg "string_view.*;" -A 2 "JsonParser"

Length of output: 163


Script:

#!/bin/bash
# Search for get_string usage with more context
rg -A 5 -B 5 "get_string\(true\)" components/core/src/clp_s/JsonParser.cpp

# Check for any string_view storage in the JsonParser class
rg "string_view" components/core/src/clp_s/JsonParser.hpp

Length of output: 1749


Script:

#!/bin/bash
# Check simdjson documentation/headers for string lifetime guarantees
rg -A 3 "get_string.*true" components/core/src/simdjson

# Check if the string_view values are used beyond their immediate scope
rg -A 10 "value = .*get_string\(true\)" components/core/src/clp_s/JsonParser.cpp

# Look for any string storage in the archive writer
rg "add_node.*NodeType::(ClpString|VarString|DateString)" components/core/src/clp_s/

Length of output: 2889

components/core/src/clp_s/Utils.hpp (2)

4-4: Inclusion of <array> is appropriate

The addition of <array> is necessary to support the use of std::array in the code.


213-214: Documentation update enhances clarity

The updated documentation for tokenize_column_descriptor provides clearer information about its functionality related to KQL columns.

components/core/src/clp_s/Utils.cpp (5)

4-4: Including <simdjson.h> for JSON parsing is appropriate

The addition of <simdjson.h> is necessary for efficient JSON parsing.


436-485: The tokenize_column_descriptor function correctly handles escaping and tokenization

The updated logic in tokenize_column_descriptor properly manages escape sequences and token boundaries, ensuring accurate tokenization of descriptors.


486-540: The escape_json_string method efficiently escapes JSON strings

The implementation using a lambda function and unescaped slices optimizes performance when processing JSON strings.


541-569: convert_four_byte_hex_to_utf8 correctly converts hex sequences to UTF-8

The function appropriately handles Unicode conversion using simdjson, ensuring correct interpretation of Unicode escape sequences.


571-674: The unescape_kql_value and unescape_kql_internal methods correctly unescape KQL values

The methods effectively manage various escape sequences, including Unicode characters, ensuring accurate unescaping of KQL values.

components/core/src/clp_s/JsonSerializer.hpp (5)

73-77: Special keys are properly escaped before being stored

The add_special_key method ensures that keys are correctly escaped using StringUtils::escape_json_string.


119-119: append_key correctly delegates to append_escaped_key

This change ensures that keys are appended with proper escaping.


123-123: Escaping keys before appending enhances JSON correctness

Using StringUtils::escape_json_string ensures keys are correctly escaped in the JSON output.


140-140: Values are properly escaped when appended with quotes

The use of extract_escaped_string_value_into_buffer guarantees that string values are correctly escaped before being added to the JSON string.


145-149: append_escaped_key correctly appends already escaped keys

As the keys are pre-escaped, this method correctly appends them to the JSON string without additional escaping.

components/core/src/clp_s/ColumnReader.cpp (2)

5-5: Including "Utils.hpp" is appropriate for utility functions

This inclusion allows the use of StringUtils methods within the file.


143-149: VariableStringColumnReader correctly escapes string values

The method ensures that string values are properly escaped before being appended, maintaining JSON validity.

components/core/src/clp_s/ColumnReader.hpp (3)

56-65: Well-structured virtual method addition!

The new virtual method follows good design practices with clear documentation and a sensible default implementation.


166-168: Correct override declaration!

The method is properly declared with the override specifier.


213-215: Correct override declaration!

The method is properly declared with the override specifier.

components/core/tests/test-kql.cpp (5)

6-6: Appropriate include addition!

The fmt library include is correctly placed and necessary for the new formatting functionality.


69-70: Good use of the new token creation method!

Using create_descriptor_from_escaped_token improves the handling of escape sequences in descriptors.


87-88: Consistent use of the new token creation method!

The change maintains consistency with other sections in handling escaped tokens.


133-134: Consistent token creation across expression types!

The changes maintain consistency in token creation across AND and OR expressions.

Also applies to: 183-184


243-267: Excellent test coverage for escape sequences!

The new test section provides comprehensive coverage of various escape sequences, including:

  • Backslashes and special characters
  • Unicode sequences
  • Control characters
  • Special KQL characters

The test structure using input/output pairs makes the expected behaviour clear and maintainable.

components/core/src/clp_s/search/ColumnDescriptor.hpp (3)

19-24: Good addition of custom exception class for improved error handling

The introduction of the OperationFailed exception class enhances error reporting by providing more specific context when token operations fail.


32-34: Refactoring with static factory methods enhances clarity

The use of static methods create_descriptor_from_escaped_token and create_descriptor_from_literal_token improves code readability and enforces consistent creation of DescriptorToken instances.

Also applies to: 40-41


124-130: New static methods improve ColumnDescriptor instantiation

Adding create_from_escaped_token, create_from_escaped_tokens, and create_from_descriptors methods enhances clarity and ensures consistent creation of ColumnDescriptor objects.

components/core/src/clp_s/search/kql/Kql.g4 (1)

61-61: Appropriate inclusion of UNICODE in UNQUOTED_CHARACTER

Adding UNICODE to UNQUOTED_CHARACTER fragment extends the grammar to support Unicode escape sequences in unquoted literals, enhancing the language's expressiveness.

components/core/src/clp_s/search/ColumnDescriptor.cpp (2)

9-9: Use of create_descriptor_from_escaped_token improves consistency

Replacing direct instantiation with create_descriptor_from_escaped_token ensures consistent token creation and proper handling of escaped tokens throughout the codebase.

Also applies to: 27-27


52-66: Renaming and updating create methods enhances clarity

Renaming the create methods to create_from_escaped_token, create_from_escaped_tokens, and create_from_descriptors clarifies their purpose and improves code readability, making the codebase more maintainable.

components/core/src/clp_s/search/kql/kql.cpp (3)

2-2: Include <stdexcept> for exception handling

Adding the <stdexcept> header allows the use of standard exceptions like std::runtime_error, ensuring proper error handling.


Line range hint 73-77: Fix potential out-of-bounds access by checking for empty string

Adding the check false == text.empty() before accessing text.at(0) prevents potential exceptions when text is empty, enhancing the robustness of the unquote_string function.


129-129: Update method calls to use new creation methods

Using create_from_escaped_tokens and create_from_escaped_token in visitColumn and visitValue_expression ensures proper handling of escaped tokens and aligns with the updated ColumnDescriptor interface.

Also applies to: 205-205

components/core/src/clp_s/Utils.hpp Outdated Show resolved Hide resolved
components/core/src/clp_s/Utils.hpp Outdated Show resolved Hide resolved
components/core/src/clp_s/Utils.hpp Outdated Show resolved Hide resolved
components/core/src/clp_s/search/kql/Kql.g4 Outdated Show resolved Hide resolved
components/core/src/clp_s/search/kql/kql.cpp Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
components/core/tests/test-kql.cpp (1)

243-270: LGTM: Comprehensive escape sequence test coverage with suggestion

The new test section thoroughly covers various escape sequences including Unicode, control characters, and special characters. The test structure is consistent with other sections and includes proper validation.

Consider adding these additional test cases:

 auto translated_pair = GENERATE(
     std::pair{"\\\\", "\\\\"},
+    std::pair{"\\u0000", "\0"},           // Null character
+    std::pair{"\\u0001\\u001F", "\1\37"}, // Control characters
+    std::pair{"香港", "香港"},             // Direct Unicode
     // ... existing cases ...
 );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b71b46 and 8508084.

📒 Files selected for processing (1)
  • components/core/tests/test-kql.cpp (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
components/core/tests/test-kql.cpp (1)

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

🔇 Additional comments (2)
components/core/tests/test-kql.cpp (2)

6-6: LGTM: fmt library inclusion

The addition of the fmt library is appropriate for safe string formatting in the new test cases.


69-70: LGTM: Consistent use of create_descriptor_from_escaped_token

The replacement of direct DescriptorToken instantiation with create_descriptor_from_escaped_token is consistent throughout the test file and aligns with the PR's objective of improving escape sequence handling.

Also applies to: 87-88, 133-134, 183-184, 214-217

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.

clp-s: Several issues searching for logs that contain escaped characters.
1 participant