@@ -255,6 +255,40 @@ public void testInitializingPrimaryRemovesInitializingReplicaWithSameAID() {
255255
256256 }
257257
258+ public void testRecoveryFailures () {
259+ disableRandomFailures ();
260+ String index = "index_" + randomAlphaOfLength (8 ).toLowerCase (Locale .ROOT );
261+ ClusterState state = ClusterStateCreationUtils .state (index , randomBoolean (),
262+ ShardRoutingState .STARTED , ShardRoutingState .INITIALIZING );
263+
264+ // the initial state which is derived from the newly created cluster state but doesn't contain the index
265+ ClusterState previousState = ClusterState .builder (state )
266+ .metaData (MetaData .builder (state .metaData ()).remove (index ))
267+ .routingTable (RoutingTable .builder ().build ())
268+ .build ();
269+
270+ // pick a data node to simulate the adding an index cluster state change event on, that has shards assigned to it
271+ final ShardRouting shardRouting = state .routingTable ().index (index ).shard (0 ).replicaShards ().get (0 );
272+ final ShardId shardId = shardRouting .shardId ();
273+ DiscoveryNode node = state .nodes ().get (shardRouting .currentNodeId ());
274+
275+ // simulate the cluster state change on the node
276+ ClusterState localState = adaptClusterStateToLocalNode (state , node );
277+ ClusterState previousLocalState = adaptClusterStateToLocalNode (previousState , node );
278+ IndicesClusterStateService indicesCSSvc = createIndicesClusterStateService (node , RecordingIndicesService ::new );
279+ indicesCSSvc .start ();
280+ indicesCSSvc .applyClusterState (new ClusterChangedEvent ("cluster state change that adds the index" , localState , previousLocalState ));
281+
282+ assertNotNull (indicesCSSvc .indicesService .getShardOrNull (shardId ));
283+
284+ // check that failing unrelated allocation does not remove shard
285+ indicesCSSvc .handleRecoveryFailure (shardRouting .reinitializeReplicaShard (), false , new Exception ("dummy" ));
286+ assertNotNull (indicesCSSvc .indicesService .getShardOrNull (shardId ));
287+
288+ indicesCSSvc .handleRecoveryFailure (shardRouting , false , new Exception ("dummy" ));
289+ assertNull (indicesCSSvc .indicesService .getShardOrNull (shardId ));
290+ }
291+
258292 public ClusterState randomInitialClusterState (Map <DiscoveryNode , IndicesClusterStateService > clusterStateServiceMap ,
259293 Supplier <MockIndicesService > indicesServiceSupplier ) {
260294 List <DiscoveryNode > allNodes = new ArrayList <>();
0 commit comments