Skip to content

Fix UnsupportedOperationException merging an empty object with a populated sibling index - #5791

Merged
ahkcs merged 1 commit into
opensearch-project:mainfrom
ahkcs:fix/clonedeep-empty-object-immutable-properties
Sep 22, 2026
Merged

ahkcs merged 1 commit into
opensearch-project:mainfrom
ahkcs:fix/clonedeep-empty-object-immutable-properties

Conversation

@ahkcs

@ahkcs ahkcs commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Description

A wildcard PPL/SQL query over two indices whose only mapping difference is an
otherwise-empty object path (a.b.c: {"type":"object"}) on one index versus the
same path carrying a leaf (a.b.c.leaf) on the other can fail with:

java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableMap.put(ImmutableMap.java:814)
    at org.opensearch.sql.opensearch.util.MergeRules.LatestRule.mergeInto(LatestRule.java:22)
    at ...MergeRuleHelper.merge(MergeRuleHelper.java:31)
    at ...DeepMergeRule.mergeInto(DeepMergeRule.java:28)
    ...
    at ...OpenSearchDescribeIndexRequest.getFieldTypes(OpenSearchDescribeIndexRequest.java:123)

Root cause. OpenSearchDataType.cloneDeep() (added in #5657, which merges
deep copies so the merge no longer mutates the retained per-index mappings)
only allocated a mutable properties map when the source object had properties.
For an empty object it left copy.properties as the class-default
ImmutableMap.of(). When getFieldTypes() deep-merges the two indices and the
empty-object side is merged first, it becomes the accumulator whose c has no
properties; the populated sibling then contributes leaf, and
MergeRuleHelper's in-place put lands on that immutable map and throws.

The crash is intermittent because getIndexMappings() returns an unordered map
(Collectors.toUnmodifiableMap), so it only fires on runs where the empty-object
index happens to be merged first.

Fix. Always give the copy a mutable LinkedHashMap, so the deep merge can
add fields regardless of whether the cloned object started empty. This matches
what parseMapping() already produces for a freshly parsed empty object (a
mutable LinkedHashMap), which is why the pre-#5657 path — merging the parsed
maps directly — did not hit this.

Reproducer

PUT /ppl-merge-repro-empty      { a.b.c: object (no properties) }, doc { a.b.c: {} }
PUT /ppl-merge-repro-populated  { a.b.c: object -> leaf: keyword }, doc { a.b.c.leaf: "value" }
POST /_plugins/_ppl { "query": "source=`ppl-merge-repro-*`" }

Fails on the runs where the empty index sorts first; passes with this change.

Testing

Added OpenSearchDescribeIndexRequestTest#getFieldTypesMergesEmptyObjectWithPopulatedSibling,
which pins the empty-object index to iterate first so it reproduces
deterministically. It fails with UnsupportedOperationException before the fix
and passes after. Existing OpenSearchDescribeIndexRequestTest,
OpenSearchDataType*, and MergeRules.* suites remain green.

Related Issues

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.

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit a08d9a0)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ No major issues detected

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to a08d9a0
Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Ensure deterministic map ordering

The test relies on insertion order to ensure the empty mapping is processed first.
However, ImmutableMap.of() does not guarantee ordering. Use ImmutableMap.builder()
or LinkedHashMap to ensure deterministic test behavior.

opensearch/src/test/java/org/opensearch/sql/opensearch/request/system/OpenSearchDescribeIndexRequestTest.java [84-85]

 when(client.getIndexMappings("idx-*"))
-    .thenReturn(ImmutableMap.of("idx-empty", mapping, "idx-populated", mapping2));
+    .thenReturn(new LinkedHashMap<>(Map.of("idx-empty", mapping, "idx-populated", mapping2)));
Suggestion importance[1-10]: 9

__

Why: The test explicitly requires the empty mapping to be processed first (as noted in the comment on line 83), but ImmutableMap.of() does not guarantee insertion order. This is a critical correctness issue that could cause flaky test failures. Using LinkedHashMap ensures deterministic ordering.

High

Previous suggestions

Suggestions up to commit 2bd1750
CategorySuggestion                                                                                                                                    Impact
General
Add null check for properties

Consider checking if properties is null before calling forEach to prevent potential
NullPointerException. While the current code may work if properties is always
initialized, defensive programming would make this more robust.

opensearch/src/main/java/org/opensearch/sql/opensearch/data/type/OpenSearchDataType.java [279-281]

 Map<String, OpenSearchDataType> copiedProperties = new LinkedHashMap<>();
-properties.forEach((field, type) -> copiedProperties.put(field, type.cloneDeep()));
+if (properties != null) {
+  properties.forEach((field, type) -> copiedProperties.put(field, type.cloneDeep()));
+}
 copy.properties = copiedProperties;
Suggestion importance[1-10]: 3

__

Why: While adding a null check is defensive programming, the suggestion doesn't consider the existing codebase context. The properties field appears to be initialized (likely in constructors or as a class field), and the PR's purpose is specifically to ensure a mutable map is always created. Adding this check would contradict the PR's intent to always provide a mutable map for merge operations.

Low

…lated sibling

cloneDeep() only allocated a mutable properties map when the source object had
properties; for an empty object it left copy.properties as the class-default
ImmutableMap.of(). When a wildcard describe merges two indices whose only
difference is one carrying a leaf under an otherwise-empty object path, and the
empty side is merged first, MergeRuleHelper's in-place put of the sibling's leaf
lands on that immutable map and throws UnsupportedOperationException.

Always give the copy a mutable LinkedHashMap so the deep merge can add fields
regardless of whether the object started empty.

The crash only reproduces when the empty-object index sorts first in the
unordered map getIndexMappings returns, so the added regression test pins that
iteration order to reproduce deterministically.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the fix/clonedeep-empty-object-immutable-properties branch from 2bd1750 to a08d9a0 Compare September 22, 2026 21:28
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit a08d9a0

@ahkcs ahkcs added the bugFix label Sep 22, 2026
@codecov

codecov Bot commented Sep 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 63.26%. Comparing base (07f079d) to head (a08d9a0).

❌ Your project check has failed because the head coverage (63.26%) is below the target coverage (99.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5791      +/-   ##
============================================
- Coverage     63.26%   63.26%   -0.01%     
+ Complexity     8823     8822       -1     
============================================
  Files           938      938              
  Lines         40217    40216       -1     
  Branches       4532     4531       -1     
============================================
- Hits          25442    25441       -1     
  Misses        13951    13951              
  Partials        824      824              
Flag Coverage Δ
sql-engine 63.26% <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.

@dai-chen dai-chen 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.

Since the OpenSearchDataType.properties is still an ImmutableMap, could you double check any other code path may mutate it?

@ahkcs

ahkcs commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Since the OpenSearchDataType.properties is still an ImmutableMap, could you double check any other code path may mutate it?

I audited OpenSearchDataType.getProperties() / properties mutation site repo-wide. The only path that mutates properties is the schema merge: MergeRuleHelper.merge → LatestRule/TextKeywordConflictRule put, and DeepMergeRule recursing into existing.getProperties(). Its only caller is getFieldTypes(), which deep-copies its inputs first, so the merge only ever writes into the top-level HashMap or a cloneDeep()-produced map — both mutable after this fix. Every other getProperties() use (traverseAndFlatten, resolve) is read-only, and the SecurityLakeDataSourceFactory puts are on the unrelated DataSourceMetadata.properties.

@ahkcs
ahkcs merged commit d7af0dc into opensearch-project:main Sep 22, 2026
64 of 69 checks passed
@ahkcs
ahkcs deleted the fix/clonedeep-empty-object-immutable-properties branch September 22, 2026 23:16
ahkcs added a commit that referenced this pull request Oct 12, 2026
…lated sibling (#5791) (#5864)

cloneDeep() only allocated a mutable properties map when the source object had
properties; for an empty object it left copy.properties as the class-default
ImmutableMap.of(). When a wildcard describe merges two indices whose only
difference is one carrying a leaf under an otherwise-empty object path, and the
empty side is merged first, MergeRuleHelper's in-place put of the sibling's leaf
lands on that immutable map and throws UnsupportedOperationException.

Always give the copy a mutable LinkedHashMap so the deep merge can add fields
regardless of whether the object started empty.

The crash only reproduces when the empty-object index sorts first in the
unordered map getIndexMappings returns, so the added regression test pins that
iteration order to reproduce deterministically.


(cherry picked from commit d7af0dc)

Signed-off-by: Kai Huang <[email protected]>
joshuali925 pushed a commit to opensearch-project/observability-stack that referenced this pull request Oct 15, 2026
…indices (#482)

OpenSearch 3.9.0 ships opensearch-project/sql#5657, which made wildcard
PPL/SQL queries throw UnsupportedOperationException when one index maps an
empty object and a sibling index maps a leaf under the same path. After the
first rollover of otel-v1-apm-span, events.attributes is an empty object in
the new index, so every query on otel-v1-apm-span-* can fail, including
Agent Traces. The fix (opensearch-project/sql#5791) was backported to 3.9 in
opensearch-project/sql#5864 and is in the 3.9.1 staging image.

OpenSearch Dashboards stays on 3.9.0.

Signed-off-by: Kyle Hounslow <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants