Skip to content

[client-v2, jdbc-v2] The default retry after NoHttpResponseException runs a write statement twice and reports success #3455

Backlog

Description

@polyglotAI-bot

Description

When the connection closes after the server ran a statement but before the response arrives, Client.execute and Client.query send the statement again (NoHttpResponse is in the default client_retry_on_failures). The server runs it a second time, and the client reports success:

  • execute("INSERT ...") stores the rows twice on a MergeTree table;
  • execute("ALTER TABLE ... UPDATE v = v + 1 ...") applies the mutation twice;
  • jdbc-v2 Statement.executeUpdate stores the rows twice (jdbc-v2 runs statements through Client.query, StatementImpl.java:410; PreparedStatement.executeBatch did the same in our run).

A caller-set query id does not prevent it when the first attempt has finished. With retries off, the caller gets the NoHttpResponseException, and the row is stored once. Client.insert also sends its data again; docs/integration-client.md:1178 documents that for the insert APIs, so this issue is about the statements of query and execute.

Root cause. HttpAPIClientHelper.java:1185 makes a NoHttpResponseException retryable for every request, and the retry loop sends the statement again whatever it is (Client.java:2052). The exception comes for a stale pooled connection (the case of docs/integration-client.md:700), and also when the server ran the request and only the response was lost.

The fix needs a maintainer decision: which statements query and execute may send again after a fault where the server can have run the request. #3174 needs the same decision for insert. Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.

Related: #3174 is the same retry; with a caller-set query id and the first attempt still running, the retry fails with 216.

Steps to reproduce

  1. Put a TCP proxy between the client and the server that forwards a request, waits until the server answers, and closes the client connection with no response (the program of "Code Example" has one).
  2. Run a write statement through the proxy with Client.execute or jdbc-v2 Statement.executeUpdate, with the default retry settings.
  3. Read the table on the server directly.

Error Log or Exception StackTrace

No exception. The client logs one retry for each case and returns success:

WARN Client - Query failed (attempt 1 of 4, queryId: null), endpoint: http://127.0.0.1:35235/, cause: org.apache.hc.core5.http.NoHttpResponseException: 127.0.0.1:35235 failed to respond. Retrying.
execute(INSERT) -> OK; SELECT count() FROM t = 2
execute(ALTER TABLE ... UPDATE v = v + 1) -> OK; SELECT v FROM t = 2
jdbc-v2 Statement.executeUpdate(INSERT) -> OK; SELECT count() FROM t = 2
execute(INSERT), retries off -> NoHttpResponseException: 127.0.0.1:35235 failed to respond; SELECT count() FROM t = 1

system.query_log has two QueryFinish rows for the one ALTER call, with two query ids.

Expected Behaviour

The client does not run a write statement a second time with no error. The repo docs say that reads are "always safe to re-run" and that writes "have side effects" (docs/integration-client.md:997 and :1167); #3072 lists INSERT without block deduplication and ALTER / mutations as not safe to retry. docs/integration-jdbc.md:847 tells JDBC users to "Trust the client's network retry strategy for network or I/O failures".

Code Example

Reproduction program (Java, 125 lines)
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.query.GenericRecord;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

public class Repro {
    static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
    static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
    static final AtomicBoolean armed = new AtomicBoolean();

    interface Op { void run() throws Exception; }

    public static void main(String[] args) throws Exception {
        URI server = URI.create(URL);
        ServerSocket proxy = new ServerSocket(0);
        Thread acceptor = new Thread(() -> accept(proxy, server.getHost(), server.getPort()));
        acceptor.setDaemon(true);
        acceptor.start();
        String viaProxy = "http://127.0.0.1:" + proxy.getLocalPort();
        sql("CREATE OR REPLACE TABLE t (id Int32, v Int32) ENGINE = MergeTree ORDER BY id");

        run("execute(INSERT)", "SELECT count() FROM t", () -> {
            try (Client c = client(viaProxy, true)) { c.execute("INSERT INTO t VALUES (1, 0)").get().close(); }
        });
        sql("TRUNCATE TABLE t");
        sql("INSERT INTO t VALUES (1, 0)");
        run("execute(ALTER TABLE ... UPDATE v = v + 1)", "SELECT v FROM t", () -> {
            try (Client c = client(viaProxy, true)) {
                c.execute("ALTER TABLE t UPDATE v = v + 1 WHERE 1 SETTINGS mutations_sync = 1").get().close();
            }
        });
        sql("TRUNCATE TABLE t");
        run("jdbc-v2 Statement.executeUpdate(INSERT)", "SELECT count() FROM t", () -> {
            Properties p = new Properties();
            p.setProperty("user", "default");
            p.setProperty("password", PASSWORD);
            try (Connection conn = new com.clickhouse.jdbc.Driver().connect("jdbc:clickhouse:" + viaProxy + "/default", p);
                 Statement st = conn.createStatement()) {
                st.executeUpdate("INSERT INTO t VALUES (1, 0)");
            }
        });
        sql("TRUNCATE TABLE t");
        run("execute(INSERT), retries off", "SELECT count() FROM t", () -> {
            try (Client c = client(viaProxy, false)) { c.execute("INSERT INTO t VALUES (1, 0)").get().close(); }
        });
    }

    static void run(String name, String check, Op op) throws Exception {
        armed.set(true); // the proxy drops the response of the next INSERT or ALTER
        String result = "OK";
        try {
            op.run();
        } catch (Exception e) {
            Throwable t = e.getCause() != null ? e.getCause() : e;
            result = t.getClass().getSimpleName() + ": " + t.getMessage().split("\n")[0];
        }
        try (Client admin = client(URL, true)) {
            GenericRecord r = admin.queryAll(check).get(0);
            System.out.println(name + " -> " + result + "; " + check + " = " + r.getLong(1));
        }
    }

    static void sql(String statement) throws Exception {
        try (Client admin = client(URL, true)) { admin.execute(statement).get().close(); }
    }

    static Client client(String endpoint, boolean retries) {
        Client.Builder b = new Client.Builder().addEndpoint(endpoint).setUsername("default").setPassword(PASSWORD);
        if (!retries) {
            b.setOption("client_retry_on_failures", "None");
        }
        return b.build();
    }

    // Forwards each request. When armed, it forwards the next INSERT or ALTER, waits until the server
    // answers (the statement has run), and closes the client connection with no response.
    static void accept(ServerSocket proxy, String host, int port) {
        while (true) {
            try {
                Socket in = proxy.accept();
                Socket out = new Socket(host, port);
                AtomicBoolean drop = new AtomicBoolean();
                Thread up = new Thread(() -> pipe(in, out, drop, true));
                Thread down = new Thread(() -> pipe(out, in, drop, false));
                up.setDaemon(true);
                down.setDaemon(true);
                up.start();
                down.start();
            } catch (Exception e) {
                return;
            }
        }
    }

    static void pipe(Socket from, Socket to, AtomicBoolean drop, boolean request) {
        byte[] buf = new byte[65536];
        try {
            InputStream src = from.getInputStream();
            int n;
            while ((n = src.read(buf)) >= 0) {
                if (request) {
                    String s = new String(buf, 0, n, StandardCharsets.ISO_8859_1);
                    if ((s.contains("INSERT") || s.contains("ALTER")) && armed.compareAndSet(true, false)) {
                        drop.set(true);
                    }
                } else if (drop.get()) {
                    from.close();
                    to.close();
                    return;
                }
                to.getOutputStream().write(buf, 0, n);
                to.getOutputStream().flush();
            }
        } catch (Exception ignored) {
        }
    }
}

Run with client-v2 and jdbc-v2 on the class path: CLICKHOUSE_URL=http://localhost:8123 CLICKHOUSE_PASSWORD=... java -cp <classpath> Repro.java.

Configuration

Client Configuration

new Client.Builder().addEndpoint(endpoint).setUsername("default").setPassword(PASSWORD).build();
// defaults: retry=3, client_retry_on_failures=NoHttpResponse,ConnectTimeout,ConnectionRequestTimeout,ServerRetryable

Environment

  • Cloud
  • Client version: client-v2 and jdbc-v2 main (8480ca0); the same default and retry loop in v0.11.2
  • Language version: Java 17.0.21
  • OS: Linux

ClickHouse Server

  • ClickHouse Server version: 26.11.2.4
  • ClickHouse Server non-default settings, if any: none
  • CREATE TABLE statements for tables involved: CREATE TABLE t (id Int32, v Int32) ENGINE = MergeTree ORDER BY id (in the program)
  • Sample data for all these tables: in the program

Classification: impact: Data integrity · area: Connectivity (retries)


Found by automated analysis (Polyglot AI) while working on #3174. Verified against a live server.

Activity

  1. added
    documentation
    client
    jdbc
    connectivity
    on Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugclientconnectivitydocumentationjdbc

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions