Skip to content

Report a PPL result that covers only some of its shards - #5807

Merged
penghuo merged 5 commits into
opensearch-project:mainfrom
ahkcs:fix/ppl-shard-failure-warning
Oct 6, 2026
Merged

penghuo merged 5 commits into
opensearch-project:mainfrom
ahkcs:fix/ppl-shard-failure-warning

Conversation

@ahkcs

@ahkcs ahkcs commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Description

OpenSearch answers a search with HTTP 200 as long as one shard responded. search.default_allow_partial_results defaults to true, and the plugin never sets allowPartialSearchResults, so every PPL search inherits it. OpenSearchResponse read only getHits()/getAggregations() and discarded _shards, so PPL returned the surviving shards' rows as the whole answer, with no error and no warning (#5687).

Reproduced on a two-node cluster over a 4-shard pattern holding 990 documents:

# both nodes up
source=osdp-* | stats count() as n        ->  990
# one data node stopped; DSL reports _shards {total: 4, successful: 3, failed: 0}
source=osdp-* | stats count() as n        ->  750     <- no warning, HTTP 200

This captures the shard outcome and attaches a PARTIAL_RESULT warning through the existing warnings channel (Warning → QueryResponse.warnings → SimpleJsonResponseFormatter), which the Explore warning banner already renders as "Partial results":

"warnings": [{
  "type": "PARTIAL_RESULT",
  "message": "Results are partial: 1 of 2 shards did not return data.",
  "detail": "Rows and aggregate values from the shards that did not respond are missing, so counts may be undercounted. No copy of those shards was available -- a node may be down or a shard unassigned. Retry the query, or set search.default_allow_partial_results to false so such searches fail instead of returning a subset."
}]

PARTIAL_RESULT had no producer after #5814, so this reuses it instead of adding a type. Warning.java is unchanged.

Points for review

  • All three partial shapes are detected, not just failures. A shard with no available copy (the node-drop case) reports failed: 0 and just doesn't add up. A failedShards > 0 check misses it, and that's the most common production shape. A timed_out response is the third shape.
  • The shard counters overlap. A shard skipped by can-match counts in both skipped and successful, so the invariant is total = successful + failed + missing. Subtracting skipped again hides a missing shard behind every skipped one. I measured this on a live cluster: total: 3, successful: 2, skipped: 1 with one shard unassigned. Can-match only runs above pre_filter_shard_size (128), so no IT can reach this case, and ShardStatsTest pins the arithmetic to the measured numbers instead.
  • The warning is recorded on the query thread. client.search runs on the sql-background pool, which the warning thread-local can't reach. fetchNextBatch runs on the query thread, the same one that drains warnings, so the stats travel on the response object and get recorded there.
  • PIT creation. A PIT created over only some shards pins that subset, so every search against it looks complete. The gap is reported at creation. Creation now allows partial results, matching the search path; forbidding it turned one unassigned shard into a 500 for any cursor or >max_result_window query.
  • Timewrap. buildResultSet drained warnings after the timewrap block, whose finally clears the same thread-local, so every timewrap query lost its warnings. It drains first now.

Split

As @dai-chen asked, this PR now carries only the warning. The index-pruning fix for #5808 moved to #5819, stacked on this one. Without it, a query with request-level time bounds can still prune an unreachable index before the search runs, so this warning won't fire on that path until #5819 lands.

Testing

The fixture is an index whose shard can never be allocated (an allocation filter naming a node that doesn't exist), next to a healthy index in the same pattern. That gives total: 2, successful: 1, failed: 0 deterministically, with no node manipulation. The unassignable index is dropped between tests so no other class inherits a red cluster.

  • ShardStatsTest (11) and BackgroundSearchScannerTest (+3)
  • CalcitePartialResultOnShardFailureIT (4): count and row queries warn; complete results don't
  • ShardFailureWarningSecurityIT (2): the warning survives the security transport-to-worker handoff for an index-scoped role ([AUTOCUT] Integration Test Failed for sql-3.9.0 #5739); a complete result carries none. integTestWithSecurity only runs org.opensearch.sql.security.*, hence the separate class.

Also confirmed against a deployed build: 990 with both nodes up, 750 with one stopped, and the 750 now carries the warning.

Scope

Calcite path only, where the warnings channel is wired. Left for follow-ups:

  • the V2 fallback path, which builds its QueryResponse without warnings;
  • CSV/raw/viz formats, which have no warnings channel;
  • a setting to reject partial results instead of warning, mirroring DSL allow_partial_search_results.

Related Issues

Resolves #5687

Check List

  • New functionality includes testing.
  • New functionality has been documented (docs/user/ppl/interfaces/protocol.md gains a Warnings section).
  • API changes companion pull request created, if applicable. n/a, the warnings array already exists in the response contract.
  • Commits are signed per the DCO using --signoff.
  • Public documentation issue/PR created, if applicable.

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

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 0587190)

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

Race Condition

Warnings are drained from the thread-local before the timewrap finally block clears it. If an exception is thrown after draining but before the finally executes, the thread-local is left dirty for the next query on this thread. This occurs when the timewrap pivot throws or when QueryResponse construction fails.

List<Warning> warnings = CalcitePlanContext.drainWarnings();
Possible Issue

The warning is added on the query thread after the background fetch completes, but if the background fetch itself throws an exception (caught in getCurrentResponse), no warning is recorded. A partial result that triggers an exception path will silently lose its partial-result warning.

// On the query thread: the search may have run on the background pool, whose thread the
// thread-local warning sink cannot reach.
response.getShardStats().toWarning().ifPresent(CalcitePlanContext::addWarning);

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 0587190

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Prevent duplicate shard warnings across pages

The warning is added for every batch, but according to the test
collapsesTheSameShardOutcomeRepeatedAcrossPages, duplicate warnings should be
collapsed. The current implementation will add the same warning multiple times
across paginated results. Consider tracking already-reported shard stats to avoid
duplicate warnings.

opensearch/src/main/java/org/opensearch/sql/opensearch/storage/scan/BackgroundSearchScanner.java [158-162]

 public SearchBatchResult fetchNextBatch(OpenSearchRequest request) {
   OpenSearchResponse response = getCurrentResponse(request);
   // On the query thread: the search may have run on the background pool, whose thread the
   // thread-local warning sink cannot reach.
-  response.getShardStats().toWarning().ifPresent(CalcitePlanContext::addWarning);
+  // Only add warning if it hasn't been reported yet for this scan
+  if (!hasReportedShardWarning) {
+    response.getShardStats().toWarning().ifPresent(warning -> {
+      CalcitePlanContext.addWarning(warning);
+      hasReportedShardWarning = true;
+    });
+  }
 
   // Determine if we need future batches
   if (response.isCountResponse()) {
     stopIteration = true;
Suggestion importance[1-10]: 9

__

Why: This is a critical bug. The test collapsesTheSameShardOutcomeRepeatedAcrossPages expects only one warning across multiple pages, but the current implementation adds a warning for every batch. The suggestion correctly identifies the issue and proposes a reasonable solution using a flag to track whether the warning has been reported.

High
Verify missing shard calculation logic

The missing() calculation may incorrectly count shards when skipped shards are
present. According to the test comment, a skipped shard is counted in both skipped
and successful, but the current formula doesn't account for this overlap. Consider
whether the calculation should be total - successful - failed or if it needs
adjustment based on how skipped shards are counted.

opensearch/src/main/java/org/opensearch/sql/opensearch/response/ShardStats.java [61-63]

 public int missing() {
+  // Note: skipped shards are included in successful count
   return Math.max(0, total - successful - failed);
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the missing() calculation should be verified, especially given the test comment about skipped shards being counted in both skipped and successful. However, the improved code only adds a comment without changing the logic, and the existing implementation appears correct based on the test cases. The suggestion asks for verification rather than identifying a concrete bug.

Medium
Drain warnings after timewrap processing

Draining warnings before the timewrap block could lose warnings if the timewrap
processing throws an exception. The finally block clears the thread-local, which
would prevent warning recovery. Consider draining warnings after the timewrap block
or ensuring warnings are preserved across exception paths.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java [476-492]

-List<Warning> warnings = CalcitePlanContext.drainWarnings();
-
 // Timewrap post-processing: pivot unpivoted rows into period columns. The pivot is shared with
 // the analytics route (AnalyticsExecutionEngine) so both engines produce identical output.
 if (TimewrapPivot.isTimewrap()) {
   try {
     ...
   } finally {
     CalcitePlanContext.clearTimewrapSignals();
   }
 }
 
+List<Warning> warnings = CalcitePlanContext.drainWarnings();
+
Suggestion importance[1-10]: 3

__

Why: The suggestion raises a valid concern about exception handling, but the proposed change is questionable. The comment in the code explicitly states "Drain before the timewrap block: its finally clears the same thread-local," indicating this ordering is intentional. Moving the drain after the timewrap block could interfere with the clearTimewrapSignals() call in the finally block.

Low

Previous suggestions

Suggestions up to commit 9a87593
CategorySuggestion                                                                                                                                    Impact
General
Use graceful executor shutdown

Using shutdownNow() on the executor can leave background tasks in an inconsistent
state and may cause resource leaks. Consider using shutdown() followed by
awaitTermination() to allow graceful completion of running tasks.

opensearch/src/test/java/org/opensearch/sql/opensearch/storage/scan/BackgroundSearchScannerTest.java [60-65]

 @AfterEach
-void tearDown() {
+void tearDown() throws InterruptedException {
   // Warnings live in a thread-local drained by the execution engine; tests share this thread.
   CalcitePlanContext.drainWarnings();
-  executor.shutdownNow();
+  executor.shutdown();
+  if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
+    executor.shutdownNow();
+  }
 }
Suggestion importance[1-10]: 5

__

Why: Valid suggestion for test cleanup. Using shutdownNow() can be abrupt; graceful shutdown with awaitTermination() is better practice. However, this is test code where immediate shutdown may be acceptable, and the impact is limited to test execution rather than production behavior.

Low
Drain warnings after all processing

Draining warnings before the timewrap block could lose warnings generated during
timewrap processing. If an exception occurs in the timewrap block, warnings
accumulated before the drain would be lost. Consider draining warnings after all
processing is complete.

opensearch/src/main/java/org/opensearch/sql/opensearch/executor/OpenSearchExecutionEngine.java [475-492]

-// Drain before the timewrap block: its finally clears the same thread-local.
-List<Warning> warnings = CalcitePlanContext.drainWarnings();
-
 // Timewrap post-processing: pivot unpivoted rows into period columns.
 if (TimewrapPivot.isTimewrap()) {
   try {
     ...
   } finally {
     CalcitePlanContext.clearTimewrapSignals();
   }
 }
 
+// Drain after all processing to capture any warnings from timewrap
+List<Warning> warnings = CalcitePlanContext.drainWarnings();
+
Suggestion importance[1-10]: 3

__

Why: The suggestion raises a valid concern about warning timing, but the comment at line 475 explicitly states the drain must happen before the timewrap block because the finally clause clears the same thread-local. Moving the drain after could lose warnings if clearTimewrapSignals() clears them. The current implementation appears intentional.

Low
Suggestions up to commit 2d4f817
CategorySuggestion                                                                                                                                    Impact
General
Handle zero total shards case

The missing() calculation may incorrectly report missing shards when total is zero
(e.g., for UNKNOWN stats). This could lead to false positives in partial result
detection. Add a guard to return 0 when total is 0 to prevent misleading
calculations.

opensearch/src/main/java/org/opensearch/sql/opensearch/response/ShardStats.java [60-62]

 public int missing() {
+  if (total == 0) {
+    return 0;
+  }
   return Math.max(0, total - successful - failed);
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion addresses a potential edge case where total is zero. However, the Math.max(0, ...) already prevents negative results, and UNKNOWN has total=0 which correctly returns missing()=0. The guard is redundant but adds minor clarity.

Low
Suggestions up to commit 503c74b
CategorySuggestion                                                                                                                                    Impact
General
Handle zero total shards case

The missing() calculation may incorrectly report missing shards when total is zero
(e.g., for UNKNOWN stats). This could lead to false positives in partial result
detection. Add a guard to return 0 when total is 0 to prevent invalid calculations.

opensearch/src/main/java/org/opensearch/sql/opensearch/response/ShardStats.java [60-62]

 public int missing() {
+  if (total == 0) {
+    return 0;
+  }
   return Math.max(0, total - successful - failed);
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion adds a guard for total == 0, but the existing Math.max(0, ...) already prevents negative results. For UNKNOWN stats (0,0,0,0), the calculation correctly returns 0. The guard is redundant and offers minimal value.

Low
Suggestions up to commit c717eed
CategorySuggestion                                                                                                                                    Impact
General
Handle probe failures in readability check

The probe(null, timeField) call could throw an exception or timeout, but there's no
error handling. If the unfiltered probe fails, the method will propagate the
exception and potentially break the pruning logic. Add try-catch to handle probe
failures gracefully and return an empty set or log the error.

opensearch/src/main/java/org/opensearch/sql/opensearch/request/IndexPruner.java [160-169]

 Set<String> indicesNotProvenEmpty(String timeField) {
-  Set<String> readable = new HashSet<>(Arrays.asList(probe(null, timeField).getIndices()));
-  Set<String> missing = new LinkedHashSet<>();
-  for (ResolveIndexAction.ResolvedIndex index : resolved().getIndices()) {
-    if (!readable.contains(index.getName())) {
-      missing.add(index.getName());
+  try {
+    Set<String> readable = new HashSet<>(Arrays.asList(probe(null, timeField).getIndices()));
+    Set<String> missing = new LinkedHashSet<>();
+    for (ResolveIndexAction.ResolvedIndex index : resolved().getIndices()) {
+      if (!readable.contains(index.getName())) {
+        missing.add(index.getName());
+      }
     }
+    return missing;
+  } catch (Exception e) {
+    log.warn("Failed to probe readable indices: {}", e.getMessage());
+    return Collections.emptySet();
   }
-  return missing;
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that probe(null, timeField) could fail and proposes adding error handling. However, the test at line 309-316 shows that probe failures are already handled by falling back to not pruning. Adding explicit error handling here would improve robustness, though the current behavior already prevents incorrect pruning on failure.

Medium
Suggestions up to commit d0bd7e9
CategorySuggestion                                                                                                                                    Impact
General
Avoid unnecessary probe when not pruning

The indicesNotProvenEmpty method is called unconditionally even when no pruning
would occur. This probe should only run when candidates would actually reduce the
index set, to avoid unnecessary field capabilities requests. Move the unsearchable
check inside the existing isPrunedBy condition.

opensearch/src/main/java/org/opensearch/sql/opensearch/request/IndexPruner.java [75-93]

-Set<String> unsearchable = indexExpr.indicesNotProvenEmpty(timeField);
-if (unsearchable.isEmpty()) {
-  return new IndexName(String.join(",", candidates));
-}
-Set<String> keep = new LinkedHashSet<>(Arrays.asList(candidates));
-keep.addAll(unsearchable);
-log.info("Index pruning kept unsearchable indices {}", unsearchable);
-if (indexExpr.isPrunedBy(keep.size())) {
-  return new IndexName(String.join(",", keep));
+if (indexExpr.isPrunedBy(candidates.length)) {
+  Set<String> unsearchable = indexExpr.indicesNotProvenEmpty(timeField);
+  if (unsearchable.isEmpty()) {
+    return new IndexName(String.join(",", candidates));
+  }
+  Set<String> keep = new LinkedHashSet<>(Arrays.asList(candidates));
+  keep.addAll(unsearchable);
+  log.info("Index pruning kept unsearchable indices {}", unsearchable);
+  if (indexExpr.isPrunedBy(keep.size())) {
+    return new IndexName(String.join(",", keep));
+  }
 }
 return indexName;
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that indicesNotProvenEmpty is called before checking if pruning would occur. Moving this check inside the isPrunedBy condition would avoid an unnecessary field capabilities request when candidates.length doesn't reduce the index set, improving performance.

Medium
Handle zero total shards explicitly

The missing() calculation can produce incorrect results when total is zero (e.g.,
UNKNOWN stats). This would return 0 even though the stats are invalid. Add an
explicit check for total == 0 to return 0 immediately, making the intent clearer and
avoiding potential arithmetic issues.

opensearch/src/main/java/org/opensearch/sql/opensearch/response/ShardStats.java [62-64]

 public int missing() {
+  if (total == 0) {
+    return 0;
+  }
   return Math.max(0, total - successful - failed);
 }
Suggestion importance[1-10]: 3

__

Why: While the suggestion adds clarity, the Math.max(0, ...) already handles the case correctly when total is 0. The explicit check is redundant since Math.max(0, 0 - 0 - 0) returns 0. This is a minor code style improvement with minimal impact.

Low

@ahkcs ahkcs added the enhancement New feature or request label Sep 24, 2026
@ahkcs
ahkcs force-pushed the fix/ppl-shard-failure-warning branch from 22a208d to 70fb145 Compare September 24, 2026 21:11
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 70fb145

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 58fc3f9

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit af1da74

@ahkcs
ahkcs force-pushed the fix/ppl-shard-failure-warning branch from af1da74 to 4c2d3a6 Compare September 24, 2026 22:25
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 4c2d3a6

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.40%. Comparing base (8aea331) to head (0587190).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...opensearch/sql/opensearch/response/ShardStats.java 93.22% 2 Missing and 2 partials ⚠️
...opensearch/executor/OpenSearchExecutionEngine.java 0.00% 2 Missing ⚠️

❌ Your project check has failed because the head coverage (63.40%) 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    #5807      +/-   ##
============================================
+ Coverage     63.36%   63.40%   +0.04%     
- Complexity     8872     8898      +26     
============================================
  Files           949      950       +1     
  Lines         40322    40386      +64     
  Branches       4546     4553       +7     
============================================
+ Hits          25549    25608      +59     
- Misses        13929    13932       +3     
- Partials        844      846       +2     
Flag Coverage Δ
sql-engine 63.40% <90.90%> (+0.04%) ⬆️

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.

@ahkcs
ahkcs force-pushed the fix/ppl-shard-failure-warning branch from 4c2d3a6 to d553f91 Compare September 24, 2026 23:04
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit d553f91

ahkcs added a commit that referenced this pull request Sep 28, 2026
* Remove the opt-in partial-result mode for mapping conflicts

The mode (#5657) narrowed an aggregation to the index subset where the group
field is aggregatable and labelled the result with a warning. It is being dropped:
returning a knowingly incomplete answer to make a query faster is the wrong
default to offer, and gating it on a cluster setting, a per-request flag and a
response-format check made three moving parts that each had to survive the
security plugin's transport-to-worker handoff (#5739, #5743, #5758).

Removed: PartialResultAggregatePushdown and its hook in CalciteLogicalIndexScan,
plugins.query.partial_result.on_mapping_conflict.enabled, the per-request
partial_result field, and the warnings-supported format gate that existed only to
protect this feature. A conflicted aggregation once again returns the complete
result over every index, which since #5646 pushes down as a _source script
rather than failing.

Kept whole: the warnings channel it introduced -- Warning, QueryResponse.warnings,
CalcitePlanContext.addWarning/drainWarnings, and the SimpleJsonResponseFormatter
plumbing. Nothing produces a warning after this commit; #5807 is the next
producer, reporting a search that covered only some of its shards.

Note for reviewers: dropping partial_result from TransportPPLQueryRequest changes
that request's wire format. The class version-gates nothing and the field was
appended the same way in 3.9, so this is symmetric with how it arrived, but it
does mean a mixed 3.9/3.10 cluster must not route PPL across versions.

Signed-off-by: Kai Huang <[email protected]>

* Drop the per-index mapping retention the feature needed

getIndexMappings() on OpenSearchIndex and lastIndexMappings on the describe
request existed only so the partitioner could see which index mapped a field
which way. Nothing reads them now.

The deep copy before merging stays: MergeRuleHelper rewrites the accumulated
type's properties in place, so a fetched mapping would otherwise stop describing
its own index. Its test now asserts that on the fetched mappings directly rather
than through the removed accessor.

Signed-off-by: Kai Huang <[email protected]>

---------

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the fix/ppl-shard-failure-warning branch from 9f3945c to c717eed Compare September 28, 2026 18:52
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit c717eed

@ahkcs
ahkcs force-pushed the fix/ppl-shard-failure-warning branch from c717eed to 503c74b Compare September 28, 2026 18:58
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 503c74b

ahkcs added a commit to ahkcs/OpenSearch-Dashboards that referenced this pull request Sep 28, 2026
The comments and test fixtures around the warnings banner still described the
removed mapping-conflict mode ("Results exclude 1 of 2 indices due to a mapping
conflict"). Point them at a search that reached only some of its shards, the
case opensearch-project/sql#5807 reports under PARTIAL_RESULT.

Signed-off-by: Kai Huang <[email protected]>
OpenSearch answers a search with HTTP 200 as long as one shard responded
(search.default_allow_partial_results defaults to true), so a result can omit
whole shards. OpenSearchResponse read only the hits and aggregations and
discarded _shards, so PPL presented the surviving shards' rows as the whole
answer, with no error and no warning: a count of 750 where the answer is 990.

Capture the shard outcome and attach a PARTIAL_RESULT warning through the
existing warnings channel when the search did not cover every shard.

- ShardStats detects all three partial shapes: a failed shard, a shard with no
  available copy (total > successful + failed, with failed 0 -- the node-drop
  shape a failed-only check misses), and a timeout. Skipped shards are already
  counted in successful.
- Record from BackgroundSearchScanner on the query thread; the search itself
  may run on the background pool, whose thread the warning sink cannot see.
- A PIT created over only some of its shards pins that subset, so every search
  against it looks complete. Report the gap at creation, and allow partial
  creation to match the search path -- forbidding it turned one unassigned
  shard into a 500 for every cursor or >max_result_window query.
- Drain warnings before the timewrap block, whose finally clears the same
  thread-local and so dropped them for every timewrap query.

Scoped to the Calcite path, where the warnings channel is wired.

Signed-off-by: Kai Huang <[email protected]>
The warnings array has been part of the PPL JSON response since opensearch-project#5657 but was
never described in the protocol reference. Document the PARTIAL_RESULT type,
when the field is present, and which formats carry it.

Signed-off-by: Kai Huang <[email protected]>
integTestWithSecurity runs only org.opensearch.sql.security.*, so a path whose
IT lives elsewhere is never exercised with security installed. The warning
travels the response channel that opensearch-project#5739 showed the security transport
interceptor can drop on the transport-to-worker handoff, so check it survives
for an index-scoped role.

The unallocatable index is dropped between tests so no other class in the
suite inherits a red cluster.

Signed-off-by: Kai Huang <[email protected]>
@ahkcs
ahkcs force-pushed the fix/ppl-shard-failure-warning branch from 503c74b to 2d4f817 Compare September 30, 2026 21:25
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 2d4f817

Comment thread docs/user/ppl/interfaces/protocol.md Outdated
{
"type": "PARTIAL_RESULT",
"message": "Results are partial: 1 of 4 shards did not return data.",
"detail": "Rows and aggregate values from the shards that did not respond are missing, so counts may be undercounted. No copy of those shards was available -- a node may be down or a shard unassigned. Retry the query, or set search.default_allow_partial_results to false so such searches fail instead of returning a subset."

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.

Does this required? Opensearch response is enough shards: total:x, failed:y, success:z?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Updated: detail now carries the shard counts as OpenSearch reports them (_shards: total 4, successful 3, skipped 0, failed 0), plus timed_out and failure reasons when present. message stays as the one-line summary.

// result partial, which the response reports, rather than failing the query outright.
CreatePitRequest createPitRequest =
new CreatePitRequest(cursorKeepAlive, false, indexName.getIndexNames());
new CreatePitRequest(cursorKeepAlive, true, indexName.getIndexNames());

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.

how PIT creation warning returnned?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The warning is recorded when the PIT is created. A PIT created over only some shards pins that subset, so later searches on it look complete (1 of 1 shards); only the create response shows the gap (1 of 2). OpenSearchNodeClient.createPit turns that into a warning on the query thread, and it's returned with the other warnings. Verified with one shard unassigned. Added unit tests for this path.

@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 9a87593

The detail now carries the shard counts as OpenSearch reported them, plus any
failure reasons, instead of a written explanation. Format with Locale.ROOT so
the numbers don't depend on the JVM locale.

Signed-off-by: Kai Huang <[email protected]>
@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 0587190

@ahkcs
ahkcs requested review from dai-chen and penghuo October 6, 2026 18:03
@penghuo
penghuo merged commit f48b2b1 into opensearch-project:main Oct 6, 2026
46 of 47 checks passed
@ahkcs
ahkcs deleted the fix/ppl-shard-failure-warning branch October 6, 2026 21:01
ahkcs added a commit to ahkcs/sql that referenced this pull request Oct 12, 2026
…ch-project#5814)

* Remove the opt-in partial-result mode for mapping conflicts

The mode (opensearch-project#5657) narrowed an aggregation to the index subset where the group
field is aggregatable and labelled the result with a warning. It is being dropped:
returning a knowingly incomplete answer to make a query faster is the wrong
default to offer, and gating it on a cluster setting, a per-request flag and a
response-format check made three moving parts that each had to survive the
security plugin's transport-to-worker handoff (opensearch-project#5739, opensearch-project#5743, opensearch-project#5758).

Removed: PartialResultAggregatePushdown and its hook in CalciteLogicalIndexScan,
plugins.query.partial_result.on_mapping_conflict.enabled, the per-request
partial_result field, and the warnings-supported format gate that existed only to
protect this feature. A conflicted aggregation once again returns the complete
result over every index, which since opensearch-project#5646 pushes down as a _source script
rather than failing.

Kept whole: the warnings channel it introduced -- Warning, QueryResponse.warnings,
CalcitePlanContext.addWarning/drainWarnings, and the SimpleJsonResponseFormatter
plumbing. Nothing produces a warning after this commit; opensearch-project#5807 is the next
producer, reporting a search that covered only some of its shards.

Note for reviewers: dropping partial_result from TransportPPLQueryRequest changes
that request's wire format. The class version-gates nothing and the field was
appended the same way in 3.9, so this is symmetric with how it arrived, but it
does mean a mixed 3.9/3.10 cluster must not route PPL across versions.

Signed-off-by: Kai Huang <[email protected]>

* Drop the per-index mapping retention the feature needed

getIndexMappings() on OpenSearchIndex and lastIndexMappings on the describe
request existed only so the partitioner could see which index mapped a field
which way. Nothing reads them now.

The deep copy before merging stays: MergeRuleHelper rewrites the accumulated
type's properties in place, so a fetched mapping would otherwise stop describing
its own index. Its test now asserts that on the fetched mappings directly rather
than through the removed accessor.

Signed-off-by: Kai Huang <[email protected]>

---------

Signed-off-by: Kai Huang <[email protected]>
(cherry picked from commit 6d666ba)
Signed-off-by: Kai Huang <[email protected]>
ahkcs added a commit that referenced this pull request Oct 12, 2026
…5865)

* Remove the opt-in partial-result mode for mapping conflicts

The mode (#5657) narrowed an aggregation to the index subset where the group
field is aggregatable and labelled the result with a warning. It is being dropped:
returning a knowingly incomplete answer to make a query faster is the wrong
default to offer, and gating it on a cluster setting, a per-request flag and a
response-format check made three moving parts that each had to survive the
security plugin's transport-to-worker handoff (#5739, #5743, #5758).

Removed: PartialResultAggregatePushdown and its hook in CalciteLogicalIndexScan,
plugins.query.partial_result.on_mapping_conflict.enabled, the per-request
partial_result field, and the warnings-supported format gate that existed only to
protect this feature. A conflicted aggregation once again returns the complete
result over every index, which since #5646 pushes down as a _source script
rather than failing.

Kept whole: the warnings channel it introduced -- Warning, QueryResponse.warnings,
CalcitePlanContext.addWarning/drainWarnings, and the SimpleJsonResponseFormatter
plumbing. Nothing produces a warning after this commit; #5807 is the next
producer, reporting a search that covered only some of its shards.

Note for reviewers: dropping partial_result from TransportPPLQueryRequest changes
that request's wire format. The class version-gates nothing and the field was
appended the same way in 3.9, so this is symmetric with how it arrived, but it
does mean a mixed 3.9/3.10 cluster must not route PPL across versions.



* Drop the per-index mapping retention the feature needed

getIndexMappings() on OpenSearchIndex and lastIndexMappings on the describe
request existed only so the partitioner could see which index mapped a field
which way. Nothing reads them now.

The deep copy before merging stays: MergeRuleHelper rewrites the accumulated
type's properties in place, so a fetched mapping would otherwise stop describing
its own index. Its test now asserts that on the fetched mappings directly rather
than through the removed accessor.



---------


(cherry picked from commit 6d666ba)

Signed-off-by: Kai Huang <[email protected]>
ahkcs added a commit that referenced this pull request Oct 12, 2026
---------


(cherry picked from commit f48b2b1)

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

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] PPL returns HTTP 200 with silently partial results when shards fail (no _shards failure surfaced)

3 participants