Re: [EXTERNAL] Support load balancing in libpq

Aleksander Alekseev <aleksander@timescale.com>

From: Aleksander Alekseev <aleksander@timescale.com>
To: PostgreSQL Hackers <pgsql-hackers@postgresql.org>
Cc: Daniel Gustafsson <daniel@yesql.se>, Jelte Fennema <postgres@jeltef.nl>, "Gregory Stark (as CFM)" <stark.cfm@gmail.com>, Andrey Borodin <amborodin86@gmail.com>, Jacob Champion <jchampion@timescale.com>, Maxim Orlov <orlovmg@gmail.com>, Jelte Fennema <Jelte.Fennema@microsoft.com>, Michael Banck <mbanck@gmx.net>, Andres Freund <andres@anarazel.de>
Date: 2023-03-27T13:32:20Z
Lists: pgsql-hackers
Hi,

> So I think it should be:
>
> ```
> if (conn->addr == NULL && conn->naddr != 0)
> ```
>
> [...]
>
> I will take a look at v16 now.

The code coverage could be slightly better.

In v16-0001:

```
+        ret = store_conn_addrinfo(conn, addrlist);
+        pg_freeaddrinfo_all(hint.ai_family, addrlist);
+        if (ret)
+            goto error_return;    /* message already logged */
```

The goto path is not test-covered.

In v16-0002:

```
+    }
+    else
+        conn->load_balance_type = LOAD_BALANCE_DISABLE;
```

The else branch is never executed.

```
         if (ret)
             goto error_return;    /* message already logged */

+        /*
+         * If random load balancing is enabled we shuffle the addresses.
+         */
+        if (conn->load_balance_type == LOAD_BALANCE_RANDOM)
+        {
+            /*
+             * This is the "inside-out" variant of the Fisher-Yates shuffle
[...]
+             */
+            for (int i = 1; i < conn->naddr; i++)
+            {
+                int            j =
pg_prng_uint64_range(&conn->prng_state, 0, i);
+                AddrInfo    temp = conn->addr[j];
+
+                conn->addr[j] = conn->addr[i];
+                conn->addr[i] = temp;
+            }
+        }
```

Strangely enough the body of the for loop is never executed either.
Apparently only one address is used and there is nothing to shuffle?

Here is the exact command I used to build the code coverage report:

```
git clean -dfx && meson setup --buildtype debug -Db_coverage=true
-Dcassert=true -DPG_TEST_EXTRA="kerberos ldap ssl load_balance"
-Dldap=disabled -Dssl=openssl -Dtap_tests=enabled
-Dprefix=/home/eax/projects/pginstall build && ninja -C build &&
PG_TEST_EXTRA=1 meson test -C build && ninja -C build coverage-html
```

I'm sharing this for the sake of completeness. I don't have a strong
opinion on whether we should bother with covering every new line of
code with tests.

Except for the named nitpicks v16 looks good to me.

-- 
Best regards,
Aleksander Alekseev



Commits

  1. Fix pointer cast for seed calculation on 32-bit systems

  2. Copy and store addrinfo in libpq-owned private memory

  3. libpq: Use modern socket flags, if available.