1111import org .apache .logging .log4j .Logger ;
1212import org .elasticsearch .action .ActionListener ;
1313import org .elasticsearch .compute .data .LongBlock ;
14+ import org .elasticsearch .compute .data .Page ;
1415import org .elasticsearch .xpack .esql .VerificationException ;
1516import org .elasticsearch .xpack .esql .common .Failure ;
1617import org .elasticsearch .xpack .esql .core .expression .Alias ;
@@ -347,8 +348,7 @@ private ActionListener<Result> approximateListener(ActionListener<Result> listen
347348 return new ActionListener <>() {
348349 @ Override
349350 public void onResponse (Result result ) {
350- assert result .executionInfo () != null ;
351- boolean esStatsQueryExecuted = result .executionInfo ().clusterInfo .values ()
351+ boolean esStatsQueryExecuted = result .executionInfo () != null && result .executionInfo ().clusterInfo .values ()
352352 .stream ()
353353 .noneMatch (
354354 cluster -> cluster .getFailures ().stream ().anyMatch (e -> e .getCause () instanceof UnsupportedOperationException )
@@ -357,6 +357,7 @@ public void onResponse(Result result) {
357357 logger .debug ("not approximating stats query" );
358358 listener .onResponse (result );
359359 } else {
360+ result .pages ().forEach (Page ::close );
360361 runner .run (toPhysicalPlan .apply (sourceCountPlan ()), configuration , foldContext , sourceCountListener (listener ));
361362 }
362363 }
@@ -405,7 +406,7 @@ private ActionListener<Result> sourceCountListener(ActionListener<Result> listen
405406 sourceRowCount = rowCount (countResult );
406407 logger .debug ("sourceCountPlan result: {} rows" , sourceRowCount );
407408 double sampleProbability = sourceRowCount <= SAMPLE_ROW_COUNT ? 1.0 : (double ) SAMPLE_ROW_COUNT / sourceRowCount ;
408- if (queryProperties .preservesRows || sampleProbability == 1.0 ) {
409+ if (queryProperties .preservesRows ) {
409410 runner .run (toPhysicalPlan .apply (approximatePlan (sampleProbability )), configuration , foldContext , listener );
410411 } else {
411412 runner .run (
@@ -430,8 +431,10 @@ private LogicalPlan countPlan(double sampleProbability) {
430431 Holder <Boolean > encounteredStats = new Holder <>(false );
431432 LogicalPlan countPlan = logicalPlan .transformUp (plan -> {
432433 if (plan instanceof LeafPlan ) {
433- // The leaf plan should be appended by a SAMPLE.
434- plan = new Sample (Source .EMPTY , Literal .fromDouble (Source .EMPTY , sampleProbability ), plan );
434+ if (sampleProbability < 1.0 ) {
435+ // The leaf plan should be appended by a SAMPLE.
436+ plan = new Sample (Source .EMPTY , Literal .fromDouble (Source .EMPTY , sampleProbability ), plan );
437+ }
435438 } else if (encounteredStats .get () == false ) {
436439 if (plan instanceof Aggregate aggregate ) {
437440 // The STATS function should be replaced by a STATS COUNT(*).
0 commit comments