From 777d77410cd8430915b8c12edbdf367b43e5dfe4 Mon Sep 17 00:00:00 2001
From: Jan Kuipers <148754765+jan-elastic@users.noreply.github.com>
Date: Wed, 13 Nov 2024 17:14:57 +0100
Subject: [PATCH] Fix NPE in MlMemoryAutoscalingDecider (#116650) (#116743)

* Fix NPE in MlMemoryAutoscalingDecider

* Update docs/changelog/116650.yaml

* Update 116650.yaml

* Update docs/changelog/116650.yaml

* better fix
---
 docs/changelog/116650.yaml                                  | 5 +++++
 .../xpack/ml/autoscaling/MlMemoryAutoscalingCapacity.java   | 6 +++++-
 .../xpack/ml/autoscaling/MlMemoryAutoscalingDecider.java    | 2 +-
 3 files changed, 11 insertions(+), 2 deletions(-)
 create mode 100644 docs/changelog/116650.yaml

diff --git a/docs/changelog/116650.yaml b/docs/changelog/116650.yaml
new file mode 100644
index 0000000000000..d314a918aede9
--- /dev/null
+++ b/docs/changelog/116650.yaml
@@ -0,0 +1,5 @@
+pr: 116650
+summary: Fix bug in ML autoscaling when some node info is unavailable
+area: Machine Learning
+type: bug
+issues: []
diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingCapacity.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingCapacity.java
index bab7bb52f928f..5a06308a3c8cc 100644
--- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingCapacity.java
+++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingCapacity.java
@@ -17,7 +17,11 @@ public static Builder builder(ByteSizeValue nodeSize, ByteSizeValue tierSize) {
     }
 
     public static Builder from(AutoscalingCapacity autoscalingCapacity) {
-        return builder(autoscalingCapacity.node().memory(), autoscalingCapacity.total().memory());
+        if (autoscalingCapacity == null) {
+            return builder(null, null);
+        } else {
+            return builder(autoscalingCapacity.node().memory(), autoscalingCapacity.total().memory());
+        }
     }
 
     @Override
diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingDecider.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingDecider.java
index dfe0e557f749d..0ff6aece95ab1 100644
--- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingDecider.java
+++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/autoscaling/MlMemoryAutoscalingDecider.java
@@ -809,7 +809,7 @@ static MlMemoryAutoscalingCapacity ensureScaleDown(
         MlMemoryAutoscalingCapacity scaleDownResult,
         MlMemoryAutoscalingCapacity currentCapacity
     ) {
-        if (scaleDownResult == null || currentCapacity == null) {
+        if (scaleDownResult == null || currentCapacity == null || currentCapacity.isUndetermined()) {
             return null;
         }
         MlMemoryAutoscalingCapacity newCapacity = MlMemoryAutoscalingCapacity.builder(