[client-v2, jdbc-v2] The default retry after NoHttpResponseException runs a write statement twice and reports success
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Facilidade para iniciantes
- 30/100
Direção de pesquisa
Start by reading HttpAPIClientHelper.java:1185 and the retry loop at Client.java:2052; the report identifies both as part of the cause. Check the existing retry tests and the linked behavior for insert in #3174, then determine which query and execute statements can safely be retried after an ambiguous response. Done means write statements are not silently run twice and client-v2 and jdbc-v2 behavior is covered.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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 aMergeTreetable;execute("ALTER TABLE ... UPDATE v = v + 1 ...")applies the mutation twice;- jdbc-v2
Statement.executeUpdatestores the rows twice (jdbc-v2 runs statements throughClient.query,StatementImpl.java:410;PreparedStatement.executeBatchdid 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
- 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).
- Run a write statement through the proxy with
Client.executeor jdbc-v2Statement.executeUpdate, with the default retry settings. - 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(8480ca001); 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 TABLEstatements 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.
- Linguagem predominante
- Java
- Estrelas
- 1.6k
- Forks
- 657
- Merge médio
- 2d 6h
- PRs com merge (30d)
- 36
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de ClickHouse/clickhouse-java
-
api-diagnostics bug jdbc
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
ClickHouse/clickhouse-java#3464 ·
Mantenedores costumam responder em até 1 dia
-
tests
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
ClickHouse/clickhouse-java#3452 ·
Mantenedores costumam responder em até 1 dia
-
bug jdbc performance queries sql-parser
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 77/100
ClickHouse/clickhouse-java#3451 ·
Mantenedores costumam responder em até 1 dia
-
bug jdbc legacy queries
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
ClickHouse/clickhouse-java#3444 ·
Mantenedores costumam responder em até 1 dia
-
api-diagnostics bug client jdbc
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
ClickHouse/clickhouse-java#3439 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
Todas as issues de ClickHouse/clickhouse-java
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 60/100
quelea-projection/Quelea#749 ·
Mantenedores costumam responder em até 1 dia
-
free_port can hand one port to two callers, so the fixed-port http tests fail in parallel runsAberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 92/100
erkamyaman/rust-anything#963 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 Meio dia Facilidade para iniciantes 76/100
-
Deferred
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
Sanne/incus-spawn#2768 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 82/100
morluto/rea#15041 · 1 comentário ·
Mantenedores costumam responder em até 1 dia