Skip to content

Conversation

visz11
Copy link

@visz11 visz11 commented Oct 15, 2025

Fixes elastic#135031

Summary by CodeRabbit

  • New Features

    • Introduced an index setting to enable LogsDB sorting by message template ID.
    • Updated default LogsDB index sort to optionally include host.name and message.template_id before @timestamp, with sensible orders, modes, and missing handling.
  • Tests

    • Added unit, REST, and integration tests covering message-template and hostname sorting combinations, default sort configurations, and rollover behavior.
    • Verified pattern_text fields under basic license with templating disabled and correct sort settings in standard and LogsDB data streams.

Copy link

Summary of Changes

Hello @visz11, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new capability for LogsDB indices, allowing users to configure a default sort order that includes the message.template_id field. This enhancement provides greater flexibility in organizing and querying log data, particularly when dealing with structured log messages. By enabling sorting on message.template_id, users can improve the efficiency of operations that benefit from a consistent ordering of similar log events. The changes involve defining a new index setting, updating the core index sort configuration logic, and adding comprehensive tests to ensure its correct behavior.

Highlights

  • New Sort Setting: Introduced index.logsdb.sort_on_message_template to enable default sorting on the message.template_id field for LogsDB indices.
  • Dynamic Sort Configuration: The index sort configuration now dynamically includes message.template_id in the default sort order when the new setting is enabled, alongside host.name and @timestamp.
  • Expanded Test Coverage: Added unit and integration tests to validate the correct application of the message.template_id sort, both independently and in conjunction with existing host.name sorting.
  • Mapping Hint Integration: The LogsdbIndexModeSettingsProvider has been updated to recognize and propagate the sortOnMessageTemplate hint, ensuring proper index creation and setting application.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

coderabbitai bot commented Oct 15, 2025

Walkthrough

Adds a new index setting index.logsdb.sort_on_message_template, updates default LogsDB index-sort assembly to optionally include message.template_id, extends LogsdbIndexModeSettingsProvider to derive this from settings/mappings, and introduces corresponding unit, integration, and REST tests. Also registers the setting in built-in index settings.

Changes

Cohort / File(s) Summary
LogsDB sort setting introduction
server/src/main/java/org/elasticsearch/index/IndexSettings.java, server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java
Adds public setting LOGSDB_SORT_ON_MESSAGE_TEMPLATE (boolean, default false). Registers it in built-in index settings.
Index sort defaults logic update
server/src/main/java/org/elasticsearch/index/IndexSortConfig.java
Refactors default LogsDB/TSDb sort spec construction. Introduces helper specs for timestamp, host.name, and message.template_id. Builds sort specs dynamically: optional host.name, optional message.template_id, then @timestamp. Removes static arrays for previous combos.
LogsDB settings provider enhancements
x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProvider.java, x-pack/plugin/logsdb/src/test/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProviderTests.java
Extends MappingHints record with sortOnMessageTemplate. Computes it from the new setting or presence of PatternText mapper on message. Updates mapping includes and propagation logic. Tests updated to assert propagation and license-driven templating flag.
Sorting behavior tests (unit/integration/REST)
server/src/test/java/org/elasticsearch/index/IndexSortSettingsTests.java, x-pack/plugin/logsdb/src/internalClusterTest/java/org/elasticsearch/xpack/logsdb/LogsdbSortConfigIT.java, x-pack/plugin/logsdb/src/javaRestTest/java/org/elasticsearch/xpack/logsdb/patterntext/PatternTextBasicLicenseIT.java, x-pack/plugin/logsdb/src/yamlRestTest/resources/rest-api-spec/test/80_index_sort_defaults.yml
Adds unit tests for LogsDB sort including message.template_id; IT validating hostname+message+timestamp sort and on-disk order; REST Java tests for pattern_text behavior and settings; YAML REST specs covering multiple LogsDB mapping combinations and expected sort fields/orders/modes/missing.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Template as Index Template/Mapping
    participant Provider as LogsdbIndexModeSettingsProvider
    participant Settings as IndexSettings
    participant SortConfig as IndexSortConfig

    Client->>Template: Create data stream/index with mappings
    Template->>Settings: Apply index settings (includes logsdb flags)
    Settings->>Provider: Resolve MappingHints
    Note over Provider: Determine sortOnHostName and sortOnMessageTemplate<br/>- from settings<br/>- or mapping (PatternText on message)
    Provider-->>Settings: MappingHints{ sortOnHostName, sortOnMessageTemplate, ... }
    Settings->>SortConfig: Request default sort specs (LogsDB mode)
    SortConfig->>SortConfig: Build specs list<br/>[host.name?] + [message.template_id?] + @timestamp
    SortConfig-->>Settings: FieldSortSpec[]
    Settings-->>Client: Index created with index.sort.*
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I sorted my carrots by host and by tune,
Template whispers guide the timestamp’s swoon.
Message IDs line up, neat as a row,
Logs hop in order wherever they go.
Ears up, I nibble—tests green as spring—
Thump! Another tidy index thing. 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately summarizes the primary change, indicating that a default sort is being added for the message.template_id field within logsdb indices, which aligns exactly with the pull request’s modifications.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch clone-logs-message-default-sort

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a default sort on the message.template_id field for logsdb indices, which is a valuable enhancement for log data management. The implementation is solid, adding a new index setting and automatically enabling it when a pattern_text mapping is used for the message field. The changes are well-tested across different levels. My review includes a suggestion to improve code consistency for maintainability and a fix for a minor typo in an integration test.

{
"_doc": {
"properties": {
"@timestmap": {

Choose a reason for hiding this comment

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

high

There seems to be a typo in the field name. It should be @timestamp instead of @timestmap.

Suggested change
"@timestmap": {
"@timestamp": {

hostnameSpec.missingValue = "_last";
hostnameSpec.mode = MultiValueMode.MIN;
HOSTNAME_TIMESTAMP_SORT = new FieldSortSpec[] { hostnameSpec, timeStampSpec };
MESSAGE_PATTERN_SPEC = new FieldSortSpec("message.template_id");

Choose a reason for hiding this comment

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

medium

For consistency and readability, it would be better to explicitly define the properties for MESSAGE_PATTERN_SPEC, similar to how HOSTNAME_SPEC is defined. While the default values would be correctly applied, being explicit makes the configuration clearer. You can use a constructor overload and set the mode property to make it compact.

Suggested change
MESSAGE_PATTERN_SPEC = new FieldSortSpec("message.template_id");
MESSAGE_PATTERN_SPEC = new FieldSortSpec("message.template_id", SortOrder.ASC, "_last");
MESSAGE_PATTERN_SPEC.mode = MultiValueMode.MIN;

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 (4)
x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProvider.java (3)

60-66: Mapping includes expanded to message fields — OK; consider narrowing for perf

Looks good for enabling message/template detection. Optionally narrow to just properties.message and properties.message.template_id (and their _doc.* variants) to reduce mapping payload processed.


258-265: Early-return condition became stricter; restore host-only fast path

Previously, host-name add/sort being set would short-circuit without creating a MapperService. Now it requires message-template too, potentially increasing overhead. Relax the condition and propagate the message-template flag independently.

-                if (IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(indexTemplateAndCreateRequestSettings)
-                    && IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings)
-                    && IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)) {
-                    // Settings for adding and sorting on [host.name] are already set, propagate them.
-                    return new MappingHints(hasSyntheticSourceUsage, true, true, true, true);
-                }
+                if (IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(indexTemplateAndCreateRequestSettings)
+                    && IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings)) {
+                    // Settings for adding and sorting on [host.name] are already set, propagate them.
+                    boolean sortOnMsg = IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings);
+                    return new MappingHints(hasSyntheticSourceUsage, true, true, sortOnMsg, true);
+                }

309-317: Derive sortOnMessageTemplate from message.template_id presence/doc values

Checking the mapper type of message is an indirect signal. Prefer verifying the concrete sub-field used for sorting (message.template_id) exists and has doc values. This avoids false positives if message is PatternText but template_id isn’t available.

-                boolean sortOnMessageTemplate = IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)
-                    || (messageField instanceof PatternTextFieldMapper);
+                boolean sortOnMessageTemplate = IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)
+                    || (mapperService.mappingLookup().getMapper("message.template_id") instanceof KeywordFieldMapper tfm
+                        && tfm.fieldType().hasDocValues());
server/src/main/java/org/elasticsearch/index/IndexSortConfig.java (1)

110-125: Avoid reusing mutable static FieldSortSpec instances

The static FieldSortSpec objects (HOSTNAME_SPEC, MESSAGE_PATTERN_SPEC, TIMESTAMP_SPEC) are mutable. Returning them directly risks accidental mutation leaking across callers/tests. Prefer adding copies to the list.

Apply this diff within the assembly to copy specs before adding:

-                    List<FieldSortSpec> sortSpecs = new ArrayList<>(3);
-                    if (IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(settings)) {
-                        sortSpecs.add(HOSTNAME_SPEC);
-                    }
-                    if (IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(settings)) {
-                        sortSpecs.add(MESSAGE_PATTERN_SPEC);
-                    }
-                    sortSpecs.add(TIMESTAMP_SPEC);
+                    List<FieldSortSpec> sortSpecs = new ArrayList<>(3);
+                    if (IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(settings)) {
+                        var s = new FieldSortSpec(HOSTNAME_SPEC.field);
+                        s.order = HOSTNAME_SPEC.order;
+                        s.missingValue = HOSTNAME_SPEC.missingValue;
+                        s.mode = HOSTNAME_SPEC.mode;
+                        sortSpecs.add(s);
+                    }
+                    if (IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(settings)) {
+                        var s = new FieldSortSpec(MESSAGE_PATTERN_SPEC.field);
+                        s.order = MESSAGE_PATTERN_SPEC.order;
+                        s.missingValue = MESSAGE_PATTERN_SPEC.missingValue;
+                        s.mode = MESSAGE_PATTERN_SPEC.mode;
+                        sortSpecs.add(s);
+                    }
+                    {
+                        var s = new FieldSortSpec(TIMESTAMP_SPEC.field);
+                        s.order = TIMESTAMP_SPEC.order;
+                        s.missingValue = TIMESTAMP_SPEC.missingValue;
+                        s.mode = TIMESTAMP_SPEC.mode;
+                        sortSpecs.add(s);
+                    }

Optionally, add a small helper to reduce repetition:

private static FieldSortSpec copy(FieldSortSpec src) {
    var s = new FieldSortSpec(src.field);
    s.order = src.order;
    s.missingValue = src.missingValue;
    s.mode = src.mode;
    return s;
}

Also applies to: 155-165

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9371a61 and d42657e.

📒 Files selected for processing (9)
  • server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java (1 hunks)
  • server/src/main/java/org/elasticsearch/index/IndexSettings.java (1 hunks)
  • server/src/main/java/org/elasticsearch/index/IndexSortConfig.java (3 hunks)
  • server/src/test/java/org/elasticsearch/index/IndexSortSettingsTests.java (1 hunks)
  • x-pack/plugin/logsdb/src/internalClusterTest/java/org/elasticsearch/xpack/logsdb/LogsdbSortConfigIT.java (1 hunks)
  • x-pack/plugin/logsdb/src/javaRestTest/java/org/elasticsearch/xpack/logsdb/patterntext/PatternTextBasicLicenseIT.java (1 hunks)
  • x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProvider.java (6 hunks)
  • x-pack/plugin/logsdb/src/test/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProviderTests.java (2 hunks)
  • x-pack/plugin/logsdb/src/yamlRestTest/resources/rest-api-spec/test/80_index_sort_defaults.yml (1 hunks)
🔇 Additional comments (12)
x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProvider.java (3)

212-220: MappingHints expansion — LGTM


298-299: Message field lookup — LGTM

Retrieving the mapper for "message" after filtering mappings is correct.


160-163: Guard message-template sort behind templating being allowed

If templating is disabled by license, enabling LOGSDB_SORT_ON_MESSAGE_TEMPLATE can create inconsistent settings relative to the actual mapping. Guard this with the license check.

Apply this diff:

-            if (mappingHints.sortOnMessageTemplate) {
-                additionalSettings.put(IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.getKey(), true);
-            }
+            if (mappingHints.sortOnMessageTemplate) {
+                if (licenseService.allowPatternTextTemplating(isTemplateValidation)) {
+                    additionalSettings.put(IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.getKey(), true);
+                } else {
+                    LOGGER.debug(
+                        "creation of index [{}]: skipping message-template sort because templating is disabled",
+                        indexName
+                    );
+                }
+            }

To double-check wiring of the new setting through the default index-sort assembly, run:

server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java (1)

200-201: Built-in setting registration looks correct

LOGSDB_SORT_ON_MESSAGE_TEMPLATE is properly added to the built-in index settings set.

server/src/main/java/org/elasticsearch/index/IndexSettings.java (1)

671-677: New LogsDB setting is well-defined

Boolean, IndexScope, PrivateIndex, Final — consistent with other LogsDB flags.

x-pack/plugin/logsdb/src/test/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProviderTests.java (2)

981-984: License gating assertion is appropriate

Asserting DISABLE_TEMPLATING when pattern_text is present under basic license is correct.


999-1009: Propagation of message-template sort flag verified

Good coverage that the new flag passes through provider settings.

server/src/test/java/org/elasticsearch/index/IndexSortSettingsTests.java (2)

335-354: Unit test for message-template sort defaults looks good

Validates two-spec sort: message.template_id asc/min, @timestamp desc/max.


355-378: Combined hostname + message + timestamp sort test is solid

Covers ordering, mode, and missing semantics for all three fields.

x-pack/plugin/logsdb/src/yamlRestTest/resources/rest-api-spec/test/80_index_sort_defaults.yml (2)

132-186: REST spec: message.template_id + timestamp defaults

Good coverage asserting fields, order, mode, and missing; matches server defaults.


189-241: REST spec: host.name + message.template_id + timestamp defaults

Validates full tri-field sort defaults. Looks correct.

x-pack/plugin/logsdb/src/javaRestTest/java/org/elasticsearch/xpack/logsdb/patterntext/PatternTextBasicLicenseIT.java (1)

1-145: New IT validates basic-license behavior and LogsDB sort defaults

Asserts templating disabled and correct sort fields on backing indices; covers rollover. LGTM.

Comment on lines +82 to +104
final String mapping = """
{
"_doc": {
"properties": {
"@timestmap": {
"type": "date"
},
"host.name": {
"type": "keyword"
},
"message": {
"type": "pattern_text"
},
"test_id": {
"type": "text",
"store": true
}
}
}
}
""";

final DocWithId[] orderedDocs = {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix mapping typo: @timestmap → @timestamp

The mapping defines "@timestmap" (typo). Use "@timestamp" to align with data stream timestamp and test assertions.

-                  "@timestmap": {
+                  "@timestamp": {
                     "type": "date"
                   },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
final String mapping = """
{
"_doc": {
"properties": {
"@timestmap": {
"type": "date"
},
"host.name": {
"type": "keyword"
},
"message": {
"type": "pattern_text"
},
"test_id": {
"type": "text",
"store": true
}
}
}
}
""";
final DocWithId[] orderedDocs = {
final String mapping = """
{
"_doc": {
"properties": {
"@timestamp": {
"type": "date"
},
"host.name": {
"type": "keyword"
},
"message": {
"type": "pattern_text"
},
"test_id": {
"type": "text",
"store": true
}
}
}
}
""";
final DocWithId[] orderedDocs = {
🤖 Prompt for AI Agents
In
x-pack/plugin/logsdb/src/internalClusterTest/java/org/elasticsearch/xpack/logsdb/LogsdbSortConfigIT.java
around lines 82 to 104 the mapping contains a typo: the field is defined as
"@timestmap" but should be "@timestamp". Update the mapping string to rename
"@timestmap" to "@timestamp" (keeping type "date") so it matches the data stream
timestamp field used by the test assertions.

@visz11
Copy link
Author

visz11 commented Oct 16, 2025

/refacto-visz

1 similar comment
@visz11
Copy link
Author

visz11 commented Oct 16, 2025

/refacto-visz

Copy link

refacto-visz bot commented Oct 16, 2025

Refacto is reviewing this PR. Please wait for the review comments to be posted.

Copy link

refacto-visz bot commented Oct 16, 2025

Code Review: LogsDB Sort Configuration Enhancement

👍 Well Done
Comprehensive Test Coverage

Thorough testing validates configuration reliability across multiple scenarios with proper edge case handling.

Consistent Setting Pattern

New LOGSDB_SORT_ON_MESSAGE_TEMPLATE setting follows established boolean configuration pattern with proper scoping.

📁 Selected files for review (9)
  • server/src/main/java/org/elasticsearch/common/settings/IndexScopedSettings.java
  • server/src/main/java/org/elasticsearch/index/IndexSettings.java
  • server/src/main/java/org/elasticsearch/index/IndexSortConfig.java
  • server/src/test/java/org/elasticsearch/index/IndexSortSettingsTests.java
  • x-pack/plugin/logsdb/src/internalClusterTest/java/org/elasticsearch/xpack/logsdb/LogsdbSortConfigIT.java
  • x-pack/plugin/logsdb/src/javaRestTest/java/org/elasticsearch/xpack/logsdb/patterntext/PatternTextBasicLicenseIT.java
  • x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProvider.java
  • x-pack/plugin/logsdb/src/test/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProviderTests.java
  • x-pack/plugin/logsdb/src/yamlRestTest/resources/rest-api-spec/test/80_index_sort_defaults.yml
🎯 Custom Instructions
❌ Unapplied Instructions
Organization Guidelines

Reason: Not approved

📝 Additional Comments
server/src/main/java/org/elasticsearch/index/IndexSortConfig.java (5)
ArrayList Dynamic Growth

ArrayList initialized with capacity 3 but actual size varies from 1-3 elements based on settings. When both hostname and message template sorting disabled, only timestamp added causing 66% memory waste. Consider calculating exact capacity or using fixed-size arrays for better memory efficiency.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Memory-Allocation-Optimization
  • Collection-Sizing-Pattern
Complex Conditional Logic

Multiple conditional checks for sort configuration create branching complexity. Consider extracting to dedicated sort configuration builder method to improve readability and testability of sort specification logic.

Standards:

  • Clean-Code-Functions
  • Refactoring-Extract-Method
  • SOLID-SRP
Field Name Validation

Hardcoded field name 'message.template_id' in sort specification reduces injection risk but creates tight coupling. Field name should be validated against schema or use constants to prevent typos that could cause runtime failures. Consider using a validated constant to ensure field existence and prevent configuration errors.

Standards:

  • CWE-20
  • OWASP-A05
  • NIST-SSDF-PW.1
Static Array Caching

Individual FieldSortSpec objects created but common combinations not pre-cached as static arrays. Frequent index creation could benefit from pre-computed arrays for common sort configurations reducing object allocation overhead during index setup.

Standards:

  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Object-Pooling-Pattern
  • Static-Caching-Optimization
Missing Default Values

MESSAGE_PATTERN_SPEC lacks explicit default values for order, missingValue, and mode properties. While defaults may be applied elsewhere, explicit initialization improves code clarity and prevents configuration drift.

Standards:

  • Clean-Code-Explicit-Defaults
  • Maintainability-Quality-Configuration
x-pack/plugin/logsdb/src/main/java/org/elasticsearch/xpack/logsdb/LogsdbIndexModeSettingsProvider.java (1)
Configuration Injection Prevention

Settings injection uses proper constant-based key retrieval preventing configuration key manipulation. The boolean value is hardcoded preventing injection attacks. However, consider validating the settings map size or implementing rate limiting to prevent configuration flooding attacks in high-volume scenarios.

Standards:

  • CWE-20
  • OWASP-A05
  • NIST-SSDF-PW.1

Comment on lines +261 to +262
&& IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings)
&& IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)) {
Copy link

Choose a reason for hiding this comment

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

Logic Condition Error

Boolean logic uses AND operator requiring both hostname sorting AND hostname field addition to be true simultaneously. This creates impossible condition where message template sorting cannot be enabled independently. Logic should use OR operator to allow either hostname or message template sorting to trigger the enhanced mapping hints.

                if ((IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(indexTemplateAndCreateRequestSettings)
                    && IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings))
                    || IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)) {
Commitable Suggestion
Suggested change
&& IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings)
&& IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)) {
if ((IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(indexTemplateAndCreateRequestSettings)
&& IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings))
|| IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)) {
Standards
  • Algorithm-Correctness-Boolean-Logic
  • Business-Rule-Feature-Independence
  • Logic-Verification-Conditional-Logic

&& IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings)) {
// Settings for adding and sorting on [host.name] are already set, propagate them.
return new MappingHints(hasSyntheticSourceUsage, true, true, true);
return new MappingHints(hasSyntheticSourceUsage, true, true, true, true);
Copy link

Choose a reason for hiding this comment

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

Inconsistent Return Values

Hard-coded return statement assumes all boolean flags are true when condition is met. Logic inconsistency occurs because method returns true for sortOnMessageTemplate regardless of actual LOGSDB_SORT_ON_MESSAGE_TEMPLATE setting value. This bypasses proper setting evaluation and creates incorrect mapping configuration.

                    boolean sortOnHostName = IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(indexTemplateAndCreateRequestSettings);
                    boolean addHostNameField = IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings);
                    boolean sortOnMessageTemplate = IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings);
                    return new MappingHints(hasSyntheticSourceUsage, sortOnHostName, addHostNameField, sortOnMessageTemplate, true);
Commitable Suggestion
Suggested change
return new MappingHints(hasSyntheticSourceUsage, true, true, true, true);
boolean sortOnHostName = IndexSettings.LOGSDB_SORT_ON_HOST_NAME.get(indexTemplateAndCreateRequestSettings);
boolean addHostNameField = IndexSettings.LOGSDB_ADD_HOST_NAME_FIELD.get(indexTemplateAndCreateRequestSettings);
boolean sortOnMessageTemplate = IndexSettings.LOGSDB_SORT_ON_MESSAGE_TEMPLATE.get(indexTemplateAndCreateRequestSettings);
return new MappingHints(hasSyntheticSourceUsage, sortOnHostName, addHostNameField, sortOnMessageTemplate, true);
Standards
  • Algorithm-Correctness-Return-Logic
  • Business-Rule-Setting-Evaluation
  • Logic-Verification-State-Consistency

{
"_doc": {
"properties": {
"@timestmap": {
Copy link

Choose a reason for hiding this comment

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

Typo Field Reference

Field name contains typo '@timestmap' instead of '@timestamp' in mapping configuration. Incorrect field reference prevents proper timestamp handling causing mapping failures. Index creation reliability affected by configuration validation errors.

Standards
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • DbC-Precondition-Validation

hostnameSpec.missingValue = "_last";
hostnameSpec.mode = MultiValueMode.MIN;
HOSTNAME_TIMESTAMP_SORT = new FieldSortSpec[] { hostnameSpec, timeStampSpec };
MESSAGE_PATTERN_SPEC = new FieldSortSpec("message.template_id");
Copy link

Choose a reason for hiding this comment

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

Magic String Constant

Hardcoded string "message.template_id" creates coupling and maintenance risk. Field name changes require hunting through code. Extract to named constant for centralized management and refactoring safety.

Standards
  • Clean-Code-Constants
  • Maintainability-Quality-Coupling
  • Refactoring-Extract-Constant

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.

Sort by pattern_text field if exists

2 participants