Skip to content

[Enhancement] Raise default structural limits for deserialization filter - #5826

Merged
penghuo merged 2 commits into
opensearch-project:mainfrom
RyanL1997:deserialization-limit-defaults
Oct 2, 2026
Merged

penghuo merged 2 commits into
opensearch-project:mainfrom
RyanL1997:deserialization-limit-defaults

Conversation

@RyanL1997

@RyanL1997 RyanL1997 commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Follow-up to #5721. The default structural limits added there reject ordinary pushed-down expressions. Every shard then fails with Failed to deserialize expression code unless an operator raises the settings. For example, this conditional count fails at the current defaults:

SELECT COUNT(DISTINCT(CASE WHEN channelNo NOT IN (2,3,4,5,6,8,10,11) AND abandoned = FALSE THEN contactNo END))
FROM my-index

This PR raises the defaults to values sized from measurements, documents the three settings, and adds regression tests.

Setting Current default New default
plugins.query.deserialization.max_depth 20 150
plugins.query.deserialization.max_refs 1000 10000
plugins.query.deserialization.max_bytes 15000 65536

How the defaults were sized

Each limit should:

  1. admit legitimate expressions with headroom;
  2. be no looser than a limit OpenSearch already enforces on the same payload;
  3. stay a real bound wherever no other limit applies.

All numbers below were measured with an instrumented build that logged the depth, reference count, and byte count the JDK filter sees for every payload.

1. Existing integration tests. Across the SQL, PPL (v2), and legacy suites (about 2000 tests, 74 unique expression payloads, 2 cursor payloads), the largest values are depth 15, 238 references, and 5.9 KB. All of them fit the current defaults. That's why the suites didn't catch this: none of them contains a moderately complex conditional expression.

2. Representative analytics expressions, run end to end against a test cluster:

Expression depth refs bytes Current defaults
The query above (CASE + NOT IN of 8 values) 28 420 7291 rejected (depth)
CASE with 10 WHENs, 3 conditions each 19 966 9923 accepted
CASE with 25 WHENs, 3 conditions each 19 2196 17728 rejected (refs, bytes)
CASE WHEN x IN (50 values) 34 1565 13278 rejected (depth, refs)
CASE WHEN x IN (100 values) 37 2965 21728 rejected (all three)
20 nested levels of AND/OR 72 722 8313 rejected (depth)
CASE WHEN x IN (250 values), the largest that fits the script size limit 40 7165 47078 rejected (all three)
Pagination cursors (SELECT *, expressions, WHERE ... IN) ≤ 11 ≤ 182 ≤ 5796 accepted

A trivial CASE already costs depth 13. Each further level of nesting adds 3–4, so the current max_depth=20 admits only 2–3 levels. IN lists become a balanced OR tree (ExpressionAnalyzer#buildOrTree), so they add depth logarithmically but references and bytes linearly, at about 28 references and 170 bytes per value. Each pushed-down aggregation or filter is a separate script, so a query with several metrics does not accumulate against one limit.

3. Limits already in place.

  • script.max_size_in_bytes (default 65535) is checked by ScriptService.compile on every shard before the plugin deserializes anything. I verified this end to end: a CASE WHEN x IN (400 values) fails with exceeded max allowed inline script size in bytes [65535] with size [96601]. An accepted script therefore decodes to at most about 49 KB, which is about 7200 references for legitimate expressions.
  • Stack depth: deserializing nested v2 expressions in a fresh JVM on a 1 MB thread stack (the JVM default; OpenSearch does not set -Xss) succeeds up to depth ~1200 and overflows at ~1260. On a data node the search thread has already used part of that stack, so the practical ceiling is lower.

Why 150 / 10000 / 65536

Setting Largest legitimate value measured Other bound Headroom
max_depth = 150 72 stack overflow at ~1200 2x over the deepest measured expression (about 45 nesting levels allowed), about 8x below the overflow point
max_refs = 10000 7165 about 7200 reachable under script.max_size_in_bytes never rejects a script OpenSearch accepted; cursors use at most 182
max_bytes = 65536 47078 about 49 KB reachable under script.max_size_in_bytes never rejects a script OpenSearch accepted; cursors use at most 5.8 KB

max_refs and max_bytes are set just above what script.max_size_in_bytes already permits. On the script path they add no new capacity; they keep a bound on the cursor path, which that setting does not cover. max_depth is the one limit that other settings don't cover, so it stays well below the stack-overflow point.

Scope

The limits apply to payloads deserialized by DefaultExpressionSerializer (v2 expression scripts, used by SQL and by PPL on the v2 engine) and PlanSerializer (SQL cursors). The Calcite engine's RelJsonSerializer payload is a single String, whose structure is carried in JSON, so these limits do not constrain it.

Known gap

plugins.query.max_expression_depth (default 1000) bounds AST depth at parse time, which is far deeper than max_depth allows. A query can still pass the parser and then be rejected on the data nodes. Aligning the two guards is left for a follow-up.

Tests

  • DefaultExpressionSerializerTest: each of the following round-trips at the new defaults and is rejected at the current ones
    • the conditional count above
    • 20 nested levels of AND/OR
    • a CASE with 25 WHEN clauses
    • a 250-value IN list, the largest that fits in script.max_size_in_bytes
  • DefaultExpressionSerializerTest: 60 nested NOTs (depth ~185) are rejected by the filter with an IllegalStateException
  • DeserializationFilterUtilTest: boundary checks updated for the new defaults, plus a check that values exactly at the limits are accepted

Related Issues

Follow-up to #5721, #5469

Check List

  • New functionality includes testing.
  • New functionality has been documented.
  • Commits are signed per the DCO using --signoff.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

The defaults added in opensearch-project#5721 reject ordinary pushed-down expressions. A
CASE WHEN with a NOT IN list inside COUNT(DISTINCT ...) reaches a
serialization depth of 28 against a max_depth of 20, and an IN list of
about 35 values exceeds max_refs of 1000.

Raise the defaults to max_depth=300, max_refs=10000, max_bytes=100000,
document the settings, and add regression tests for conditional counts,
large IN lists, and excessive nesting.

Signed-off-by: Jialiang Liang <[email protected]>
@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Analyzer ❗

AI-powered 'Code-Diff-Analyzer' found issues on commit de2751e.

PathLineSeverityDescription
core/src/main/java/org/opensearch/sql/utils/DeserializationFilterUtil.java78lowDeserialization filter limits are significantly relaxed: DEFAULT_MAX_DEPTH 20→150 (7.5x), DEFAULT_MAX_REFS 1000→10000 (10x), DEFAULT_MAX_BYTES 15000→65536 (4.4x). While the change includes thorough documentation, real-world measurements, and tests verifying stack-overflow protection remains intact, loosening Java deserialization guards is security-relevant and warrants maintainer verification that the class allowlist is sufficient to prevent gadget-chain exploitation at the new limits.

The table above displays the top 10 most important findings.

Total: 1 | Critical: 0 | High: 0 | Medium: 0 | Low: 1


Pull Requests Author(s): Please update your Pull Request according to the report above.

Repository Maintainer(s): You can bypass diff analyzer by adding label skip-diff-analyzer after reviewing the changes carefully, then re-run failed actions. To re-enable the analyzer, remove the label, then re-run all actions.


⚠️ Note: The Code-Diff-Analyzer helps protect against potentially harmful code patterns. Please ensure you have thoroughly reviewed the changes beforehand.

Thanks.

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit de2751e)

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 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to de2751e
Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Security
Add safety bounds validation

Consider adding validation to ensure these constants remain within safe bounds.
While 150 depth is safer than the previous 20, extremely deep nesting could still
cause stack overflow issues. Add runtime checks or document the absolute maximum
safe values based on typical thread stack sizes.

core/src/main/java/org/opensearch/sql/utils/DeserializationFilterUtil.java [72-75]

+/** Maximum safe depth before risking stack overflow (typically ~1200 for 1MB stack). */
+private static final int ABSOLUTE_MAX_DEPTH = 1200;
+
 public static final int DEFAULT_MAX_DEPTH = 150;
 
 public static final int DEFAULT_MAX_REFS = 10000;
 public static final int DEFAULT_MAX_BYTES = 65536;
 
+static {
+  if (DEFAULT_MAX_DEPTH > ABSOLUTE_MAX_DEPTH) {
+    throw new IllegalStateException("DEFAULT_MAX_DEPTH exceeds safe limit");
+  }
+}
+
Suggestion importance[1-10]: 3

__

Why: While adding validation for safety bounds is a reasonable defensive practice, the PR already documents that the depth of ~1200 causes stack overflow and sets DEFAULT_MAX_DEPTH to 150 (well below that limit). The suggested static initializer adds complexity without significant benefit since the constants are already conservatively chosen and documented. The validation would only catch developer errors during compilation, not runtime configuration issues.

Low

Previous suggestions

Suggestions up to commit bf4b298
CategorySuggestion                                                                                                                                    Impact
Security
Add safety threshold constant

Consider adding validation to ensure these constants remain within safe bounds. The
comment mentions staying "well below the ~1000 depth at which JDK deserialization
overflows a 1 MB thread stack", but there's no runtime check to prevent
configuration from exceeding this critical threshold.

core/src/main/java/org/opensearch/sql/utils/DeserializationFilterUtil.java [70-73]

 public static final int DEFAULT_MAX_DEPTH = 300;
+public static final int MAX_SAFE_DEPTH = 1000;
 
 public static final int DEFAULT_MAX_REFS = 10000;
 public static final int DEFAULT_MAX_BYTES = 100000;
Suggestion importance[1-10]: 4

__

Why: While adding a MAX_SAFE_DEPTH constant could be useful for documentation purposes, the suggestion doesn't provide runtime validation as claimed in the description. The 'improved_code' only adds a constant without any enforcement mechanism, making this a minor documentation improvement rather than a security enhancement.

Low

@RyanL1997 RyanL1997 changed the title Raise default structural limits for deserialization filter [Enhancement]Raise default structural limits for deserialization filter Sep 30, 2026
@RyanL1997 RyanL1997 added the enhancement New feature or request label Sep 30, 2026
@codecov

codecov Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 63.36%. Comparing base (8aea331) to head (de2751e).
⚠️ Report is 1 commits behind head on main.

❌ Your project check has failed because the head coverage (63.36%) 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    #5826   +/-   ##
=========================================
  Coverage     63.36%   63.36%           
  Complexity     8872     8872           
=========================================
  Files           949      949           
  Lines         40322    40322           
  Branches       4546     4546           
=========================================
  Hits          25549    25549           
  Misses        13929    13929           
  Partials        844      844           
Flag Coverage Δ
sql-engine 63.36% <ø> (ø)

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.

Size the defaults against measured legitimate expressions and the limits
OpenSearch already enforces. The deepest legitimate expression measured
reaches depth 72, and cold deserialization overflows a 1 MB stack at
about 1200, so 150 leaves headroom on both sides. Pushed-down scripts
are capped by script.max_size_in_bytes (65535) before deserialization,
so max_bytes=65536 and max_refs=10000 never reject a script OpenSearch
accepted.

Add regression tests for deeply nested conditions and CASE with many
WHEN clauses.

Signed-off-by: Jialiang Liang <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit de2751e

@RyanL1997
RyanL1997 marked this pull request as ready for review October 1, 2026 00:32
@RyanL1997 RyanL1997 changed the title [Enhancement]Raise default structural limits for deserialization filter [Enhancement] Raise default structural limits for deserialization filter Oct 2, 2026
@penghuo
penghuo merged commit 803ed31 into opensearch-project:main Oct 2, 2026
80 of 82 checks passed
@opensearch-ci-bot

Copy link
Copy Markdown
Contributor

The backport to 3.9 failed. Please backport manually. See failed workflow run: https://github.com/opensearch-project/sql/actions/runs/37386971548

RyanL1997 added a commit that referenced this pull request Oct 12, 2026
…rialization filter (#5826) (#5862)

Raise the deserialization filter defaults to max_depth=150,
max_refs=10000, max_bytes=65536, document the settings, and add
regression tests.

(cherry picked from commit 803ed31)

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

Labels

backport 3.9 enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants