1111import org .elasticsearch .xpack .esql .core .util .Holder ;
1212import org .elasticsearch .xpack .esql .expression .function .vector .Knn ;
1313import org .elasticsearch .xpack .esql .optimizer .LogicalOptimizerContext ;
14+ import org .elasticsearch .xpack .esql .plan .logical .Aggregate ;
1415import org .elasticsearch .xpack .esql .plan .logical .Filter ;
1516import org .elasticsearch .xpack .esql .plan .logical .Limit ;
1617import org .elasticsearch .xpack .esql .plan .logical .LogicalPlan ;
@@ -25,7 +26,12 @@ public PushLimitToKnn() {
2526 public LogicalPlan rule (Limit limit , LogicalOptimizerContext ctx ) {
2627 var currentLimit = (int ) limit .limit ().fold (ctx .foldCtx ());
2728 Holder <Integer > currentLimitHolder = new Holder <>(currentLimit );
29+ Holder <Boolean > breakerReached = new Holder <>(false );
2830 return limit .transformDown (plan -> {
31+ if (breakerReached .get ()) {
32+ // We reached a breaker and don't want to continue processing
33+ return plan ;
34+ }
2935 if (plan instanceof Filter filter ) {
3036 Expression limitAppliedExpression = limitFilterExpressions (filter .condition (), limit , ctx );
3137 if (limitAppliedExpression .equals (filter .condition ()) == false ) {
@@ -37,6 +43,8 @@ public LogicalPlan rule(Limit limit, LogicalOptimizerContext ctx) {
3743 currentLimitHolder .set (newLimit );
3844 }
3945 return descendantLimit ;
46+ } else if (plan instanceof Aggregate ) {
47+ breakerReached .set (true );
4048 }
4149
4250 return plan ;
0 commit comments