Intelligence Explain: SQL Statement Query Time Prediction
Tags: opengauss
Published: 2023-04-14 04:46:55

**Overview**

Predictor is a query time prediction tool that leverages machine learning and has online learning capabilities. By continuously learning the historical execution information collected in the database, Predictor can predict the execution time of a plan.

To use this tool, you must start the Python process AI Engine for model training and inference.

This function is stored in the $GAUSSHOME/**bin/dbmind/components/predictor** directory. Some functions of this module involve complex setup. Therefore, you need to switch to the directory to find the corresponding files and deploy the functions according to the description in this section.

**Environment Deployment**

**Prerequisites**
openGauss is in the normal state. The user has logged in to openGauss with an authenticated identity. The executed SQL syntax is correct and no error is reported. In the historical performance data window, the number of openGauss concurrent tasks is stable, the structure and number of tables remain unchanged, the data volume changes smoothly, and the GUC parameters related to query performance remain unchanged. During prediction, the model has been trained and converged. The running environment of the AIEngine is stable.

**Request Example**
The AIEngine process communicates with the kernel process using HTTPS. An example request is as follows:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59952vtwmyasjedgrqtr.png)

Table 1 AIEngine external APIs

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9lrrjejp4bja7wxqt1g7.png)

**Generating Certificates**
Before using the prediction function, you need to use OpenSSL to generate certificates required for authentication between the communication parties, ensuring communication security.

1. Set up a certificate generation environment. The certificate file is stored in **$GAUSSHOME/CA**.

– Copy the certificate generation script and related files.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b5qabky2ruy73sn9q0dt.png)

– Copy the configuration file openssl.cnf to **$GAUSSHOME**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cuspumm528huqkah9tnf.png)

– Modify the configuration parameters in **openssl.conf**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ej12kpwtor85xdwvm0q9.png)

– The certificate generation environment is ready.

2. Generate a certificate and private key.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z0ayuxpj23wmz8nqf0na.png)

– Set the password as prompted, for example, **Test@123**.

– The password must contain at least eight characters of at least three different types.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0sbhn5qiej4jds7jl9jz.png)

– Set the options as prompted.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nk7z3ww8i2joignszkyd.png)

– Enter the IP address for starting the AIEngine, for example, **127.0.0.1**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2xk62cyfsit6ne19gph.png)

– Set the options as prompted.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjprwmojydac1mbjk5n0.png)

– Enter the IP address for starting openGauss, for example, **127.0.0.1**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rq23jl4wcqbfaz8i42qs.png)

– Set the options as prompted.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ce62zgwiflcsgtcau8s.png)

**Setting Up the Environment**
1. Copy the tool code folder to the target environment.

– Assume that the installation directory is **$INSTALL_FOLDER**.

– Assume that the destination directory is **/home/ai_user**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kgez2nsgtt2h5xmp97n.png)

2. Copy the CA certificate folder to a directory in the AIEngine environment.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/btf3y5sb2k5eldh4lclc.png)

3. Install the **predictor/install/requirements(-gpu).txt** tool.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqc9amw40apd92kdbr4z.png)

**Starting the AIEngine**
1. Switch to the AIEngine environment (that is, copy the target environment **ai_user** of the predictor).

Set parameters in **predictor/python/settings.py**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yrv6nib732d2ztn70au.png)

2. Run the startup script of the AIEngine.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tk0rkg1td1bim5ngfh5x.png)

In this case, the AIEngine keeps enabled on the corresponding port and waits for the request of the time prediction function from the kernel.

For details about how to initiate a time prediction command from the kernel, see User Guide.

**User Guide**
**Data Collection**
1. Enable data collection.

1.1 Set parameters related to the ActiveSQL operator.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/se9z1nnhdx8i6sxrsq8v.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dd8z0fw4hudejeewf0o0.png)

1.2 Collect information.

Execute the service query statement.

View data collected in real time.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bdoevnyj7liyo4jrfkx.png)

Expected result: All jobs that meet **resource_track_duration** and **resource_track_cost** are collected.

2. Disable data collection.

2.1 Set parameters related to the ActiveSQL operator.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fx7sgpurg96366l0rrpm.png)

2.2 Execute the service query statement.

Wait for 3 minutes and check the data on the current node.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acs7pujo00gn2dl18h9w.png)

Expected result: No new data is added to the tables and views.

3. Persist data.

3.1 Set parameters related to the ActiveSQL operator.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7q4g8on874vduuqu1kna.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ny0ewxn22vq9l9wkkzuz.png)

3.2 Execute the service query statement.

Wait for 3 minutes and check the data on the current node.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hm27yjy6tp6emp5arx97.png)

Expected result: All jobs that meet **resource_track_duration** and **resource_track_cost** are collected.

**Model Management (System Administrators)**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qis5cmj58my0agl01tge.png)

1. Add a new model.

INSERT INTO gs_opt_model values('……');

Example:

INSERT INTO gs_opt_model values('rlstm', 'model_name', 'datname', '127.0.0.1', 5000, 2000, 1, -1, 64, 512, 0 , false, false, '{S, T}', '{0,0}', '{0,0}', 'Text');


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ecni01vrsv6lhtxa0rya.png)

2. Modify model parameters.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vc5g8dbw0htfrejqgwqw.png)

3. Delete a model.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikj3hsd42i58rujhpwxi.png)

4. Query the existing model and its status.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjvicpxw3ldrulvupfdb.png)

**Model Training (System Administrators)**

1. Add models and modify model parameters by following the steps in Model Management (System Administrators).

Example:

Add a mode.

INSERT INTO gs_opt_model values('rlstm', 'default', 'postgres', '127.0.0.1', 5000, 2000, 1, -1, 64, 512, 0 , false, false, '{S, T}', '{0,0}', '{0,0}', 'Text');

Modify training parameters.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upoomu1tgaspdxipfau3.png)

2. Check that the database status is normal and historical data is collected properly before you perform the following operations:

Delete the original encoding data.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/erpq7aufafhteufacp1y.png)

To encode data, specify the database name.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5s1ypeb6peljk8d3tsk.png)

Start training.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/efzwk5q4tcgzyg3cpvfa.png)

3. Run the following command to obtain the relative path of the model training log on the AIEngine side:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smka7mxw3tl8lifca4ol.png)

**Model Prediction**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ycqu0hr4r8cmwp6u8k8w.png)

1. Call EXPLAIN.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1h89bmdjyiccqqt0rqs9.png)

Expected result:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jg19yobqi76lufh4afv5.png)

**Other Functions**
1. Check whether the AIEngine can be connected.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5i79ornrbxclqxy0m737.png)

2. Check the path for storing model logs on the AIEngine.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqetwi6rmo768vqp3sed.png)

**Best Practices**

For details about the parameters, see GS_OPT_MODEL.

Table 1

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3l4sdaf6nox3twxyvkaa.png)

Recommended parameter settings:

INSERT INTO gs_opt_model values('rlstm', 'open_ai', 'postgres', '127.0.0.1', 5000, 2000, 1, -1, 64, 512, 0, false, false, '{S, T}', '{0,0}', '{0,0}', 'Text');

**FAQs**

**AI Engine Configuration**
**·** **AI Engine failed to be started**: Check whether the IP address and port are available and whether the CA certificate path exists.
**·** **AI Engine does not respond**: Check whether the CA certificates of the two communication parties are consistent.
**·** **Training and test failure**: Check whether the path for saving the model files exists and whether the training prediction file is correctly downloaded.
**·** **Changing the AI Engine IP address**: Regenerate the certificate by following the steps in Generating Certificates. Enter the new IP address in Generate a certificate and private key.

**Database Internal Errors**
Problem: AI Engine connection failed.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnotjtr5zd6u8kjy1usf.png)

Solution: Check whether the AI Engine is started or restarted properly. Check whether the CA certificates of the communication parties are consistent. Check whether the IP address and port number in the model configuration match.

Problem: The model does not exist.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5k6m4wvhmhfmaol6013e.png)

Solution: Check whether GS_OPT_MODEL contains the model specified in the **model_name** column in the statement. If the error is reported when the prediction function is used, check whether the model has been trained.