Skip to content

Fix PIT (Point in Time) resource leaks in v2 query engine - #5221

Merged
yuancu merged 3 commits into
opensearch-project:mainfrom
LantaoJin:pr/issues/5220
Mar 11, 2026
Merged

yuancu merged 3 commits into
opensearch-project:mainfrom
LantaoJin:pr/issues/5220

Conversation

@LantaoJin

@LantaoJin LantaoJin commented Mar 10, 2026 •

Copy link
Copy Markdown
Member

Description

This PR fixes multiple PIT (Point in Time) resource leak scenarios in the v2 query engine. PITs are server-side resources created for paginated search; if not properly deleted, they accumulate and eventually hit the search.max_open_pit_context limit, causing all subsequent queries to fail.

Three distinct PIT leak paths were identified:

  1. explain() never closes the physical plan — OpenSearchExecutionEngine.explain() builds a physical plan (which creates a PIT) to generate explain output, then discards it without calling close(). Every explain call leaks a PIT per index matched. For example, source=test* against 50 indices leaks 50 PITs per call, exhausting the default 300 limit in just 6 calls.

  2. OpenSearchIndexScan.close() skips PIT deletion on non-final pages — close() delegates to request.clean() which only deletes the PIT when needClean=true (last page consumed). If the scan is closed early due to LIMIT, exception, or timeout, the PIT is orphaned.

  3. Explicit cursor close doesn't delete PIT — CursorCloseOperator propagates close() to children, but OpenSearchIndexScan.close() → cleanup() → clean() skips PIT deletion because needClean=false mid-pagination. The PIT is never reclaimed.

Related Issues

Resolves #5220

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.

@github-actions

This comment was marked as resolved.

@github-actions

github-actions Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 35203c9

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Properly stub request mock for serialization test

The test mocks request but writeExternal internally calls methods on request (e.g.,
to serialize it) that are not stubbed, which will likely cause a
NullPointerException or unexpected behavior. The mock needs to stub all methods
invoked during writeExternal, or the test should use a real/partial request object
to properly simulate serialization and set cursorSerialized = true.

opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScanTest.java [309-315]

 // Simulate successful cursor serialization by calling writeExternal
 var out = mock(ObjectOutput.class);
+// Stub methods called during serialization
+var bytesRef = new org.apache.lucene.util.BytesRef(new byte[0]);
+var bytesStream = mock(org.opensearch.common.io.stream.BytesStreamOutput.class);
+when(request.writeTo(any())).thenAnswer(inv -> null);
+// ... or use a real request and only mock the client
 indexScan.writeExternal(out);
 
 indexScan.close();
 verify(client).cleanup(request);
 verify(client, never()).forceCleanup(any());
Suggestion importance[1-10]: 5

__

Why: The concern about unstubbed mock methods during writeExternal is valid — writeExternal calls methods on request that aren't stubbed on the mock, potentially causing failures. However, the improved_code provided is incomplete and uses placeholder comments rather than a concrete fix, making it less actionable.

Low
Ensure all table scans are closed in tree

The traversal stops as soon as it finds a TableScanOperator, but a tree could
theoretically have multiple TableScanOperator leaves (e.g., a join). More
critically, if a non-TableScanOperator node has no children, getChild() returns an
empty list and the recursion silently terminates without ever reaching a
TableScanOperator deeper in the tree. Consider always recursing into children even
after finding a scan, or at least handling the case where no scan is found.

core/src/main/java/org/opensearch/sql/planner/physical/CursorCloseOperator.java [66-72]

 private void forceCloseChildren(PhysicalPlan node) {
   if (node instanceof TableScanOperator scan) {
     scan.forceClose();
-  } else {
-    node.getChild().forEach(this::forceCloseChildren);
   }
+  node.getChild().forEach(this::forceCloseChildren);
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion raises a valid point about trees with multiple TableScanOperator nodes (e.g., joins). The improved code correctly continues recursing even after finding a scan. However, this is a minor edge case for the current use case where a single scan is expected, and the improvement is modest.

Low

Previous suggestions

Suggestions up to commit c2ab5c7
CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix inverted cleanup condition for serialized cursors

The condition logic appears inverted. When request.hasAnotherBatch() &&
cursorSerialized is true, the cursor has been serialized for the next page, so the
PIT should be preserved (not cleaned up at all). Calling client.cleanup(request)
in this branch may still delete the PIT depending on the implementation. The
forceCleanup should be called when there are no more batches or the cursor was not
serialized, and when the cursor was serialized with more batches remaining, no
cleanup should occur.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScan.java [117-125]

 if (request.hasAnotherBatch() && cursorSerialized) {
   // PIT has been serialized into a cursor for the next page request.
-  // Only clean up in-memory state; the PIT must survive for the next request.
-  client.cleanup(request);
+  // Do NOT clean up; the PIT must survive for the next request.
 } else {
   // No more pages, or query failed/aborted before cursor was serialized.
   // Force delete the PIT to prevent leaking.
   client.forceCleanup(request);
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion raises a valid concern: when cursorSerialized is true and there's another batch, calling client.cleanup(request) might still delete the PIT depending on implementation. However, the comment says "Only clean up in-memory state; the PIT must survive", suggesting cleanup is intentionally different from forceCleanup. Without knowing the cleanup vs forceCleanup contract, this could be a real bug or by design. The suggestion is plausible and worth considering.

Medium
Fix unreliable test using mocked serialization

The writeExternal call on a mocked request may not behave correctly since request is
a mock and internal serialization logic (e.g., reqOut.bytes()) will likely throw a
NullPointerException or fail silently, meaning cursorSerialized may never be set to
true. The test should verify that cursorSerialized is actually set, or use a
real/spy request object to ensure writeExternal completes successfully.

opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScanTest.java [309-315]

-// Simulate successful cursor serialization by calling writeExternal
-var out = mock(ObjectOutput.class);
+// Use a spy or real request to ensure writeExternal actually sets cursorSerialized = true
+// and verify the expected cleanup behavior
 indexScan.writeExternal(out);
-
+// Confirm cursorSerialized was set (indirectly via close() behavior)
 indexScan.close();
 verify(client).cleanup(request);
 verify(client, never()).forceCleanup(any());
Suggestion importance[1-10]: 6

__

Why: This is a valid concern — calling writeExternal on an indexScan with a mocked request may fail because writeExternal likely calls methods on request that return null from the mock, potentially causing a NullPointerException before cursorSerialized = true is set. However, the improved_code doesn't actually fix the issue, it just adds a comment, so the actionable value is limited.

Low
General
Ensure all scan nodes are closed in tree traversal

The traversal stops as soon as it finds a TableScanOperator, but a tree could
theoretically have multiple TableScanOperator nodes (e.g., joins). Additionally, if
a non-TableScanOperator node wraps a TableScanOperator but also has its own
resources, those won't be released. Consider calling forceCloseChildren on all
children even when a TableScanOperator is found, or at minimum traversing all
branches.

core/src/main/java/org/opensearch/sql/planner/physical/CursorCloseOperator.java [66-72]

 private void forceCloseChildren(PhysicalPlan node) {
   if (node instanceof TableScanOperator scan) {
     scan.forceClose();
   } else {
     node.getChild().forEach(this::forceCloseChildren);
   }
+  // If the tree can have multiple scan nodes, traverse all children regardless:
+  // node.getChild().forEach(this::forceCloseChildren);
 }
Suggestion importance[1-10]: 3

__

Why: The concern about multiple TableScanOperator nodes is theoretically valid, but the improved_code doesn't actually change the logic (it only adds a commented-out alternative). The suggestion is speculative and the existing_code matches the improved_code functionally, making it a low-impact observation.

Low
Suggestions up to commit 2f6c5a6
CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix inverted pagination cleanup logic

The logic is inverted: when hasAnotherBatch() returns true, there are more pages
remaining and the PIT should be preserved (not cleaned up at all), but the current
code calls client.cleanup(request) which may still release in-memory state needed
for the next page. When hasAnotherBatch() is false, the PIT should be force-deleted,
which is correct. Consider whether calling client.cleanup(request) mid-pagination is
safe, or if the branch for hasAnotherBatch() == true should be a no-op to truly
preserve the PIT for the next page.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/OpenSearchIndexScan.java [108-120]

 @Override
 public void close() {
   super.close();
 
   if (request.hasAnotherBatch()) {
-    // PIT is still needed for the next page — only clean up the in-memory state
-    // without deleting the PIT from OpenSearch.
-    client.cleanup(request);
+    // PIT is still needed for the next page — do not clean up anything server-side.
+    // No-op: preserve the PIT for the next paginated request.
   } else {
     // No more pages expected (last page consumed, non-paginated query, or error path).
     // Force delete the PIT to prevent leaking.
     client.forceCleanup(request);
   }
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion raises a valid concern about whether calling client.cleanup(request) when hasAnotherBatch() is true is safe or should be a no-op. However, the behavior of client.cleanup vs client.forceCleanup is not fully visible in the diff, and the comment in the code says it only cleans up "in-memory state" without deleting the PIT, so the suggestion may be based on incomplete context. Still, it's worth investigating whether the hasAnotherBatch() == true branch should be a no-op.

Low
General
Ensure all scan nodes are force-closed

The traversal stops as soon as it finds a TableScanOperator, but if a plan tree has
a TableScanOperator wrapped inside another TableScanOperator (or multiple scan nodes
at different levels), only the first one found will be closed. Additionally, if a
non-scan node has no children, the recursion silently stops without closing any
scan. Consider always recursing into children even after finding a scan, to ensure
all scan nodes are closed.

core/src/main/java/org/opensearch/sql/planner/physical/CursorCloseOperator.java [66-72]

 private void forceCloseChildren(PhysicalPlan node) {
   if (node instanceof TableScanOperator scan) {
     scan.forceClose();
-  } else {
-    node.getChild().forEach(this::forceCloseChildren);
   }
+  node.getChild().forEach(this::forceCloseChildren);
 }
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies that the current traversal stops recursing into children once a TableScanOperator is found, which could miss nested scan nodes. However, in practice, a TableScanOperator has no children (returns empty list), so the original code is functionally equivalent for typical plan trees. The improvement is still valid for correctness in edge cases.

Low
Prevent cleanup exceptions from masking original errors

Adding plan.close() in the finally block of the explain path may cause issues if
plan.close() itself throws an exception, which would suppress the original exception
from listener.onFailure(e). Wrap plan.close() in a try-catch to safely handle any
cleanup errors without masking the original failure.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java [146-150]

 } catch (Exception e) {
   listener.onFailure(e);
 } finally {
-  plan.close();
+  try {
+    plan.close();
+  } catch (Exception closeEx) {
+    // log or ignore cleanup error to avoid masking original exception
+  }
 }
Suggestion importance[1-10]: 4

__

Why: This is a valid defensive programming suggestion — exceptions thrown in finally blocks can suppress original exceptions. However, this is a minor robustness concern and the impact is limited since close() failures are relatively rare in practice.

Low

@qianheng-aws

Copy link
Copy Markdown
Collaborator

OpenSearchExecutionEngine.explain() builds a physical plan (which creates a PIT) to generate explain output

PIT isn't really needed for plan explain, I think creating PIT here is a kind of resource wasting.

@LantaoJin

LantaoJin commented Mar 10, 2026 •

Copy link
Copy Markdown
Member Author

OpenSearchExecutionEngine.explain() builds a physical plan (which creates a PIT) to generate explain output

PIT isn't really needed for plan explain, I think creating PIT here is a kind of resource wasting.

Exactly, I just release the resource, will check how to avoid to create.

I checked the code and find it maybe not worth to fix it in explain due to change so many interfaces in v2.

@LantaoJin
LantaoJin marked this pull request as draft March 10, 2026 10:16
@github-actions

This comment was marked as resolved.

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit c2ab5c7

@LantaoJin
LantaoJin marked this pull request as ready for review March 11, 2026 08:43
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 35203c9

@yuancu
yuancu merged commit e11e11e into opensearch-project:main Mar 11, 2026
38 checks passed
opensearch-trigger-bot Bot pushed a commit that referenced this pull request Mar 11, 2026
* Fix PIT (Point in Time) resource leaks in v2 query engine

Signed-off-by: Lantao Jin <[email protected]>

* Fix PIT context leaks when a query without cursor/pagination fails during execution

Signed-off-by: Lantao Jin <[email protected]>

* Avoid to expose sensitive document

Signed-off-by: Lantao Jin <[email protected]>

---------

Signed-off-by: Lantao Jin <[email protected]>
(cherry picked from commit e11e11e)
Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
opensearch-trigger-bot Bot pushed a commit that referenced this pull request Mar 13, 2026
* Fix PIT (Point in Time) resource leaks in v2 query engine

Signed-off-by: Lantao Jin <[email protected]>

* Fix PIT context leaks when a query without cursor/pagination fails during execution

Signed-off-by: Lantao Jin <[email protected]>

* Avoid to expose sensitive document

Signed-off-by: Lantao Jin <[email protected]>

---------

Signed-off-by: Lantao Jin <[email protected]>
(cherry picked from commit e11e11e)
Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
yuancu pushed a commit that referenced this pull request Mar 13, 2026
…y engine (#5229)

* Fix PIT (Point in Time) resource leaks in v2 query engine (#5221)

* Fix PIT (Point in Time) resource leaks in v2 query engine

Signed-off-by: Lantao Jin <[email protected]>

* Fix PIT context leaks when a query without cursor/pagination fails during execution

Signed-off-by: Lantao Jin <[email protected]>

* Avoid to expose sensitive document

Signed-off-by: Lantao Jin <[email protected]>

---------

Signed-off-by: Lantao Jin <[email protected]>
(cherry picked from commit e11e11e)
Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Resolve compile error

Signed-off-by: Lantao Jin <[email protected]>

---------

Signed-off-by: Lantao Jin <[email protected]>
Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Lantao Jin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] PPL query failed with Trying to create too many Point In Time contexts. Must be less than or equal to: [300]

3 participants