Skip to content

[BugFix] Fix PPL replace being O(n²) in the field count (#5959) - #5961

Merged
RyanL1997 merged 1 commit into
opensearch-project:mainfrom
RyanL1997:fix/5959-replace-quadratic-projection
Nov 20, 2026
Merged

RyanL1997 merged 1 commit into
opensearch-project:mainfrom
RyanL1997:fix/5959-replace-quadratic-projection

Conversation

@RyanL1997

@RyanL1997 RyanL1997 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Description

replace looked up every column it leaves unchanged by name with a linear search, so on wide indices planning time grew with the square of the field count, no matter how many fields were replaced. It now builds a name-to-position map once and looks those columns up by position. The plan and query results are unchanged.

Before / after: source=wide_N | replace "s1" WITH "S1" IN status | head 10

Fields Before After
3,500 72 ms 27 ms
7,000 230 ms 28 ms
14,000 900 ms 32 ms

Related Issues

Resolves #5959

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • New functionality has javadoc added.
  • New functionality has a user manual doc added.
  • New PPL command checklist all confirmed.
  • API changes companion pull request created.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

@RyanL1997

RyanL1997 commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Decision Log

replace resolved every column it leaves unchanged with RelBuilder.field(String), which scans the field list on each call, so planning was O(fields²) on wide indices. It now resolves those columns by position through a name-to-position map, using the buildFieldIndex helper from #5956.

  • Correctness: the map keeps the first position of a repeated name and matches case-sensitively, like field(String), so the plan is unchanged. Existing tests pass with no expected-output changes, and 77 replace queries give identical plans and errors before and after.
  • Rejected: looking columns up by loop position without a map, because a repeated name would then read the wrong column.
  • Watch: convert has the same pattern and is fixed separately in [BugFix] Fix PPL convert being O(n²) in the field count (#5958) #5960.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit a130151)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Semantics Change on Duplicate/Case-Variant Names

buildFieldIndex(fieldNames) is built from the output field name list. If it uses case-insensitive matching or handles duplicates differently than RelBuilder.field(String), replace will resolve unchanged columns differently than before. The added test testReplaceResolvesColumnsLikeFieldByName asserts case-sensitive, first-match semantics matching RelBuilder.field(String), but this depends entirely on the (not shown) buildFieldIndex implementation. Please confirm that for repeated names the map stores the first occurrence (not the last) and that lookup is case-sensitive, to preserve the prior behavior.

Map<String, Integer> fieldIndex = buildFieldIndex(fieldNames);

// Project all fields, replacing specified ones in-place
for (String fieldName : fieldNames) {
  if (fieldsToReplace.contains(fieldName)) {
    // Replace this field in-place with all pattern/replacement pairs applied sequentially
    RexNode fieldRef = context.relBuilder.field(fieldName);

    // Apply all replacement pairs sequentially (nested REPLACE calls)
    for (ReplacePair pair : node.getReplacePairs()) {
      RexNode patternNode = rexVisitor.analyze(pair.getPattern(), context);
      RexNode replacementNode = rexVisitor.analyze(pair.getReplacement(), context);

      String patternStr = pair.getPattern().getValue().toString();
      String replacementStr = pair.getReplacement().getValue().toString();

      if (patternStr.contains("*")) {
        WildcardUtils.validateWildcardSymmetry(patternStr, replacementStr);

        String regexPattern = WildcardUtils.convertWildcardPatternToRegex(patternStr);
        String regexReplacement =
            WildcardUtils.convertWildcardReplacementToRegex(replacementStr);

        RexNode regexPatternNode =
            context.rexBuilder.makeLiteral(
                regexPattern,
                context.rexBuilder.getTypeFactory().createSqlType(SqlTypeName.VARCHAR),
                true);
        RexNode regexReplacementNode =
            context.rexBuilder.makeLiteral(
                regexReplacement,
                context.rexBuilder.getTypeFactory().createSqlType(SqlTypeName.VARCHAR),
                true);

        fieldRef =
            context.rexBuilder.makeCall(
                org.apache.calcite.sql.fun.SqlLibraryOperators.REGEXP_REPLACE_3,
                fieldRef,
                regexPatternNode,
                regexReplacementNode);
      } else {
        fieldRef =
            context.relBuilder.call(
                SqlStdOperatorTable.REPLACE, fieldRef, patternNode, replacementNode);
      }
    }

    projectList.add(fieldRef);
  } else {
    // Keep original field unchanged
    projectList.add(context.relBuilder.field(fieldIndex.get(fieldName)));

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 01738b3

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to a130151
Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Ensure duplicate names map to first index

Building the index map by iterating fieldNames and using put will cause
later-duplicate names to overwrite earlier ones, so a repeated column name would
resolve to its LAST occurrence. This contradicts the stated semantics (and the new
testReplaceResolvesColumnsLikeFieldByName test) that RelBuilder.field(String)
resolves to the FIRST occurrence. Ensure buildFieldIndex uses putIfAbsent (or
equivalent) so the first index wins.

core/src/main/java/org/opensearch/sql/calcite/CalciteRelNodeVisitor.java [5050]

-Map<String, Integer> fieldIndex = buildFieldIndex(fieldNames);
+Map<String, Integer> fieldIndex = buildFieldIndex(fieldNames); // must map name -> first index
Suggestion importance[1-10]: 6

__

Why: The suggestion raises a valid concern about duplicate field name resolution semantics, which is directly tested by testReplaceResolvesColumnsLikeFieldByName. However, without seeing the buildFieldIndex implementation, it's unclear whether the issue actually exists; the suggestion essentially asks to verify the behavior.

Low

Previous suggestions

Suggestions up to commit 01738b3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Index current row fields, not output names

buildFieldIndex is constructed from fieldNames (the output projection names) rather
than from the current relBuilder row's field names. If fieldNames differs in order
or content from relBuilder.peek().getRowType().getFieldNames(),
fieldIndex.get(fieldName) will return a wrong ordinal and project the incorrect
column. Build the index from the current row's field names to match the semantics of
relBuilder.field(String).

core/src/main/java/org/opensearch/sql/calcite/CalciteRelNodeVisitor.java [5031]

-Map<String, Integer> fieldIndex = buildFieldIndex(fieldNames);
+Map<String, Integer> fieldIndex =
+    buildFieldIndex(context.relBuilder.peek().getRowType().getFieldNames());
 
 // Project all fields, replacing specified ones in-place
 for (String fieldName : fieldNames) {
   if (fieldsToReplace.contains(fieldName)) {
Suggestion importance[1-10]: 5

__

Why: The suggestion raises a valid concern about semantic correctness: buildFieldIndex should ideally be built from the current relBuilder row's field names to match relBuilder.field(String) semantics. However, in this context fieldNames appears to be derived from the current row (as it was used in the original relBuilder.field(fieldName) lookups), so the practical impact may be minimal. Still, the suggestion improves robustness.

Low

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.13%. Comparing base (0924db1) to head (a130151).

Additional details and impacted files
@@            Coverage Diff            @@
##               main    #5961   +/-   ##
=========================================
  Coverage     89.12%   89.13%           
- Complexity    12176    12177    +1     
=========================================
  Files           978      978           
  Lines         41815    41816    +1     
  Branches       4811     4811           
=========================================
+ Hits          37269    37273    +4     
+ Misses         3077     3075    -2     
+ Partials       1469     1468    -1     
Flag Coverage Δ
integration 69.92% <100.00%> (+0.01%) ⬆️
unit 76.24% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@RyanL1997 RyanL1997 added bug Something isn't working enhancement New feature or request performance Make it fast! PPL Piped processing language bugFix and removed bug Something isn't working labels Nov 19, 2026
…roject#5959)

replace resolved every column it leaves unchanged with
RelBuilder.field(String), which searches the field names linearly, so
building its projection took O(fields^2) time on wide indices. Resolve
those columns by ordinal through buildFieldIndex, which keeps the first
ordinal of a repeated name as field(String) does, so the plan is
unchanged.

Signed-off-by: Jialiang Liang <jiallian@amazon.com>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit a130151

@Swiddis Swiddis left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

same as #5960 (comment)

@RyanL1997
RyanL1997 merged commit 7963b3e into opensearch-project:main Nov 20, 2026
112 of 116 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugFix enhancement New feature or request performance Make it fast! PPL Piped processing language

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] PPL replace is O(n²) in the field count on wide indices

3 participants