Skip to content

Replace native cursor serialization with Jackson Smile - #5802

Open
mengweieric wants to merge 4 commits into
opensearch-project:mainfrom
mengweieric:fix/smile-cursor-serialization
Open

mengweieric wants to merge 4 commits into
opensearch-project:mainfrom
mengweieric:fix/smile-cursor-serialization

Conversation

@mengweieric

Copy link
Copy Markdown
Collaborator

Description

V2 pagination cursors carry the physical plan state needed to fetch the next page. The current cursor envelope uses Java object serialization. That couples decoding to implementation classes and allows a broader object graph than pagination needs.

This change replaces the physical-plan envelope with a closed, versioned Jackson Smile schema. The schema accepts only ProjectNode and IndexScanNode. OpenSearch request state continues to use the OpenSearch transport codec, and projection expressions continue to use the existing filtered expression codec. ServiceLoader keeps the engine-specific flattening and rebuilding logic outside core.

The new cursor format uses the n:v2: prefix and standard Base64 so it is clearly separated from the legacy n: object stream. Cursor payloads are bounded by nesting depth, token count, field-name length, and plugins.query.cursor.max_bytes. The new size setting defaults to 1 MiB and has a 16 MiB administrative ceiling. This separate budget prevents the smaller per-expression limit from rejecting a valid complete cursor.

PIT ownership transfers only after the complete cursor has been encoded and validated. If any serialization or validation step fails, the current plan retains ownership and closes the PIT. This preserves the lifecycle contract established by #5221 without leaving an unreachable search context.

Legacy n: cursors are not decoded by the new format. Because cursors are opaque and short-lived, pagination that is still in progress during an upgrade must be restarted.

Validation completed on Java 21:

  • ./gradlew --continue build -x integTest -x tracingIntegTest -x yamlRestTest -x doctest
  • ./gradlew :integ-test:integTest --tests org.opensearch.sql.sql.StandalonePaginationIT
  • Unit coverage for Smile round trips, malformed and oversized payloads, structural limits, expression limits, service loading, PIT handoff after successful encoding, and PIT cleanup on failure

The pagination design and the new cursor-size setting are documented in this repository.

Related Issues

Follow-up to #5221.

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. N/A: no PPL command is added.
  • API changes companion pull request created. N/A: no REST API schema changes.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created. N/A: documentation is included in this repository.

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.

Signed-off-by: menwe <menwe@amazon.com>
Signed-off-by: menwe <menwe@amazon.com>
Signed-off-by: menwe <menwe@amazon.com>
Signed-off-by: menwe <menwe@amazon.com>
@mengweieric

Copy link
Copy Markdown
Collaborator Author

Intent: Replace physical-plan cursor object serialization with a bounded, closed Smile schema while preserving pagination and PIT lifecycle behavior.
Not a goal: Replace the existing filtered expression codec or change query semantics.

@mengweieric mengweieric added the enhancement New feature or request label Sep 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR Code Analyzer ❗

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

PathLineSeverityDescription
core/build.gradle60highNew dependency added: com.fasterxml.jackson.dataformat:jackson-dataformat-smile. Per mandatory supply-chain policy, all dependency additions must be flagged regardless of apparent legitimacy. Maintainers should verify the artifact coordinates, version, and checksum against the official Jackson release channel.
opensearch/src/main/java/org/opensearch/sql/opensearch/executor/pagination/PlanFlattener.java52mediumThe onCursorEncoded commit callback calls expressionSerializer::deserialize on every previously serialized expression string. Deserializing Java object streams as a post-encode commit step is unexpected: it triggers ObjectInputStream on attacker-influenced serialized data after the ownership transfer decision has already been made, potentially exercising deserialization gadgets as a side-effect of normal pagination. Verify this is intentional round-trip validation and not a logic error that was silently left in.

The table above displays the top 10 most important findings.

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


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.

@mengweieric mengweieric added the skip-diff-analyzer Maintainer to skip code-diff-analyzer check, after reviewing issues in AI analysis. label Sep 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

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

Possible Issue

The maxBase64Length() calculation in ReadLimits can overflow for large maxBytes values. When maxBytes is close to Integer.MAX_VALUE, the expression 4L * ((maxBytes + 2L) / 3L) can exceed Long.MAX_VALUE, causing silent wraparound. This would allow oversized cursors to bypass the size check in checkBase64Size.

private long maxBase64Length() {
  return 4L * ((maxBytes + 2L) / 3L);
}
Resource Leak

If writeMapper.writeValueAsBytes(flattened.node()) throws an exception after flattener().flatten(plan, settings) has been called, the onCursorEncoded callback is never invoked. This leaves the PIT in an intermediate state where ownership has not been transferred but the scan has been marked as serialized. The caller's close() will then call cleanup() instead of forceCleanup(), potentially leaving the PIT open.

}

private ProjectNode flattenProject(
    ProjectOperator projectOp,
    List<OpenSearchIndexScan> serializedScans,
    List<String> serializedExpressions,
    DefaultExpressionSerializer expressionSerializer) {
  PhysicalPlan child = projectOp.getChild().get(0);
  SerializablePlanNode childNode =
      flattenNode(child, serializedScans, serializedExpressions, expressionSerializer);

  List<String> serializedExprs =
      projectOp.getProjectList().stream()
          .map(expr -> expressionSerializer.serialize((NamedExpression) expr))
          .toList();
  serializedExpressions.addAll(serializedExprs);
Possible Issue

The checkEncodedSize method calculates maxEncodedLength as 4L * ((maxBytes + 2L) / 3L), which can overflow when maxBytes is close to Integer.MAX_VALUE. This would allow oversized Base64 strings to bypass the size check. The same overflow issue exists in PlanSerializer.ReadLimits.maxBase64Length().

private static void checkEncodedSize(String code, int maxBytes) {
  long maxEncodedLength = 4L * ((maxBytes + 2L) / 3L);
  if (code.length() > maxEncodedLength) {
    throw new IllegalArgumentException("Serialized expression exceeds the configured byte limit");
  }

@github-actions

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Improve ServiceLoader error message clarity

The loadService method throws IllegalStateException if no provider is found, but
this exception is not caught or documented. If the ServiceLoader configuration is
missing or incorrect, the application will fail at runtime. Consider adding a more
descriptive error message that includes troubleshooting steps or configuration
requirements.

core/src/main/java/org/opensearch/sql/executor/pagination/PlanSerializer.java [216-223]

 private static <T> T loadService(Class<T> serviceClass) {
   return java.util.ServiceLoader.load(serviceClass, PlanSerializer.class.getClassLoader())
       .findFirst()
       .orElseThrow(
           () ->
               new IllegalStateException(
-                  "No ServiceLoader provider found for " + serviceClass.getName()));
+                  "No ServiceLoader provider found for " + serviceClass.getName() 
+                  + ". Ensure META-INF/services configuration is present."));
 }
Suggestion importance[1-10]: 5

__

Why: Adding troubleshooting guidance to the error message improves developer experience when ServiceLoader configuration is missing, though the impact is moderate since this is a deployment-time issue.

Low
Validate encoded byte length accurately

The encoded size check uses code.length() which counts characters, not bytes. For
Base64 strings containing only ASCII characters, this is equivalent, but the method
should explicitly validate byte length to match the documented behavior and avoid
potential issues with non-ASCII characters in the string.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/serde/DefaultExpressionSerializer.java [76-81]

 private static void checkEncodedSize(String code, int maxBytes) {
   long maxEncodedLength = 4L * ((maxBytes + 2L) / 3L);
-  if (code.length() > maxEncodedLength) {
+  if (code.getBytes(StandardCharsets.UTF_8).length > maxEncodedLength) {
     throw new IllegalArgumentException("Serialized expression exceeds the configured byte limit");
   }
 }
Suggestion importance[1-10]: 3

__

Why: Base64 strings are ASCII-only, so String.length() already measures byte length accurately. The suggested change adds unnecessary overhead without improving correctness.

Low
Possible issue
Validate Base64 byte length accurately

The Base64 length check uses encoded.length() which counts characters, not bytes.
For standard Base64 encoding, each character is 1 byte in UTF-8, but this assumption
may not hold in all environments. Use
encoded.getBytes(StandardCharsets.UTF_8).length to ensure accurate byte-length
validation.

core/src/main/java/org/opensearch/sql/executor/pagination/PlanSerializer.java [111-115]

 private static void checkBase64Size(String encoded, ReadLimits limits) {
-  if (encoded.length() > limits.maxBase64Length()) {
+  if (encoded.getBytes(StandardCharsets.UTF_8).length > limits.maxBase64Length()) {
     throw new IllegalArgumentException("Cursor exceeds the configured byte limit");
   }
 }
Suggestion importance[1-10]: 3

__

Why: For standard Base64 strings (ASCII-only), String.length() equals byte length. The suggestion to use getBytes(UTF_8).length adds overhead without practical benefit since Base64 output is always ASCII.

Low

@mengweieric mengweieric added the skip-diff-reviewer Maintainer to skip code-diff-reviewer check, after reviewing issues in AI analysis. label Sep 23, 2026
@codecov

codecov Bot commented Sep 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.42077% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.24%. Comparing base (5953571) to head (4888e61).

Files with missing lines Patch % Lines
...search/sql/executor/pagination/PlanSerializer.java 70.58% 21 Missing and 4 partials ⚠️
.../opensearch/executor/pagination/PlanRebuilder.java 80.95% 3 Missing and 1 partial ⚠️
...rch/storage/serde/DefaultExpressionSerializer.java 81.25% 1 Missing and 2 partials ⚠️
.../opensearch/executor/pagination/PlanFlattener.java 95.23% 2 Missing ⚠️

❌ Your project check has failed because the head coverage (63.24%) 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    #5802    +/-   ##
==========================================
  Coverage     63.23%   63.24%            
- Complexity     8823     8850    +27     
==========================================
  Files           938      941     +3     
  Lines         40236    40339   +103     
  Branches       4537     4541     +4     
==========================================
+ Hits          25445    25513    +68     
- Misses        13966    13995    +29     
- Partials        825      831     +6     
Flag Coverage Δ
sql-engine 63.24% <81.42%> (+<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.

@Swiddis

Swiddis commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Has merge conflicts, but I trust this as long as CI passes. We should have sufficient ITs for cursor serialization.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request skip-diff-analyzer Maintainer to skip code-diff-analyzer check, after reviewing issues in AI analysis. skip-diff-reviewer Maintainer to skip code-diff-reviewer check, after reviewing issues in AI analysis.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants