[client-v2] Stream insert: when reset() fails before a retry, the exception drops the error of the failed attempt
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 2/5
- Tempo estimado
- 1-3 horas
- Facilidade para iniciantes
- 55/100
Direção de pesquisa
Start in the insert retry loop in Client.java near lines 1894-1908, where writer.onRetry() runs after recordInsertRetry and the ClientException is built from only the IOException. Use failIfCancelled at Client.java:2135-2140 as the model for keeping the last attempt's failure. Check MetricsRecorder.java:102 for the retry-metric contract. Run the reproduction program in the issue to confirm the cause chain. Done when the exception keeps the failed attempt's error as cause or suppressed, and recordInsertRetry is not called for a retry that never happens.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Description
When an insert from an InputStream or a DataStreamWriter fails with a retryable error, the client calls reset() (or DataStreamWriter#onRetry()) before the retry. If that call throws, the application gets ClientException: Failed to reset stream before next attempt, and its only cause is the IOException of the reset. The error of the failed attempt (connection refused, or a server error such as READONLY or TOO_MANY_PARTS) is not in the cause chain and is not a suppressed exception. Only the WARN log line of the attempt shows it. Also, MetricsRecorder#recordInsertRetry is called for a retry that the client then does not make.
Affected: Client#insert with an InputStream that has no valid mark (for example a BufferedInputStream with no mark(), or a FileInputStream), and with a DataStreamWriter whose onRetry() throws. The javadoc suggests that a writer throws there to say that its source cannot be retried (DataStreamWriter.java:23).
Steps to reproduce
- Run the program in "Code Example". Case 1 uses an endpoint with no server. Cases 2 and 3 set
readonly=1to get a retryable server error (164). - Compare the exceptions of cases 1 and 2 with the contrast case 3.
Error Log or Exception StackTrace
The program prints each exception of the cause chain on one line:
== 1: connection refused, BufferedInputStream
ClientException: Failed to reset stream before next attempt
IOException: Resetting to invalid mark
recordInsertRetry calls: 1
== 2: READONLY, DataStreamWriter whose onRetry() throws
ClientException: Failed to reset stream before next attempt
IOException: source cannot be read again
recordInsertRetry calls: 1
== 3 (contrast): READONLY, ByteArrayInputStream
ServerException: Code: 164. DB::Exception: default: Cannot execute query in readonly mode. (READONLY) (version 26.10.4.207 (official build))
recordInsertRetry calls: 3
The lost error of case 1 is only in the log:
WARN com.clickhouse.client.api.Client - Insert (stream) failed (attempt 1 of 4, queryId: null), endpoint: http://localhost:1/, cause: com.clickhouse.shaded.org.apache.hc.client5.http.HttpHostConnectException: Connect to http://localhost:1 failed: Connection refused. Retrying.
Expected Behaviour
The exception tells the application why the insert failed, as in case 3: the error of the failed attempt is the cause or a suppressed exception of the ClientException. The client already does this when a cancellation stops the retry loop: failIfCancelled keeps the failure of the last attempt as cause (Client.java:2135-2140). recordInsertRetry is called only for a retry that the client makes: "Reports that an attempt of an insert operation failed and the client retries it" (MetricsRecorder.java:102).
Root cause: Client.java:1908 creates the ClientException with only the IOException as cause and drops lastException. Client.java:1894 records the retry before writer.onRetry() runs at Client.java:1906.
The fix is a few lines in this one method. Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.
Related:
- #2675 (open): the client never calls
mark(), soreset()fails for aBufferedInputStream. This issue is about the error whenreset()fails. - #3300 (open): removes the per-attempt
WARNlog, the only place where the lost error shows today. - #3404 (open): documents the current cause chain; it needs an update if this changes.
Code Example
Reproduction program (Java, 48 lines)
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.DataStreamWriter;
import com.clickhouse.client.api.insert.InsertSettings;
import com.clickhouse.client.api.observability.DefaultMetricsRecorder;
import com.clickhouse.data.ClickHouseFormat;
import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;
public class StreamRetryRepro {
static final AtomicInteger retries = new AtomicInteger();
static Client client(String url) {
return new Client.Builder().addEndpoint(url).setUsername("default")
.setPassword(System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", ""))
.setMetricsRecorder(new DefaultMetricsRecorder() {
@Override public void recordInsertRetry(InsertSettings s, String t, Throwable c) { retries.incrementAndGet(); }
}).build();
}
static void run(String name, Client c, Object data, InsertSettings s) {
retries.set(0);
System.out.println("== " + name);
try {
if (data instanceof InputStream) c.insert("t", (InputStream) data, ClickHouseFormat.CSV, s).get();
else c.insert("t", (DataStreamWriter) data, ClickHouseFormat.CSV, s).get();
} catch (Exception e) {
for (Throwable t = e; t != null; t = t.getCause())
System.out.println(" " + t.getClass().getSimpleName() + ": " + t.getMessage().split("\n")[0].replaceAll("\\(queryId=.*", ""));
}
System.out.println(" recordInsertRetry calls: " + retries.get());
}
public static void main(String[] args) throws Exception {
String url = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
byte[] csv = "1\n2\n".getBytes();
InsertSettings readonly = new InsertSettings().serverSetting("readonly", "1");
try (Client good = client(url); Client noServer = client("http://localhost:1")) {
good.query("CREATE OR REPLACE TABLE t (id UInt32) ENGINE = MergeTree ORDER BY id").get().close();
run("1: connection refused, BufferedInputStream", noServer,
new BufferedInputStream(new ByteArrayInputStream(csv)), new InsertSettings());
run("2: READONLY, DataStreamWriter whose onRetry() throws", good, new DataStreamWriter() {
public void onOutput(OutputStream out) throws IOException { out.write(csv); out.close(); }
public void onRetry() throws IOException { throw new IOException("source cannot be read again"); }
}, readonly);
run("3 (contrast): READONLY, ByteArrayInputStream", good, new ByteArrayInputStream(csv), readonly);
}
}
}
Run: CLICKHOUSE_URL=http://localhost:8123 CLICKHOUSE_PASSWORD=... java -cp client-v2-<version>-all.jar:slf4j-api.jar:slf4j-simple.jar StreamRetryRepro.java
Configuration
Client Configuration
new Client.Builder().addEndpoint(url).setUsername("default").setPassword(password).build(); // default retry settings
Environment
- Cloud
- Client version: client-v2,
mainat 051a7ecfd (0.12.0-rc1-SNAPSHOT) - Language version: OpenJDK 17.0.21
- OS: Linux (Docker)
ClickHouse Server
- ClickHouse Server version: 26.10.4.207
- ClickHouse Server non-default settings, if any: none (the program sets
readonly=1for cases 2 and 3) CREATE TABLEstatements for tables involved: in the program- Sample data for all these tables: in the program
Classification: impact: none · area: API & diagnostics (insert retry errors, retry metric)
Found by automated analysis (Polyglot AI) while working on #2675. 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