[client-v2] Stream insert: when reset() fails before a retry, the exception drops the error of the failed attempt

Offen
#3,405 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 1 Tag

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Anfängerfreundlichkeit
55/100
Issue-Typ
Bug
Klarheit
Klar beschrieben
Aktivitätsstatus
Aktiv
Tech-Stack
java
Bereich
api

Rechercherichtung

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.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

api-diagnostics bug client

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
  1. Run the program in "Code Example". Case 1 uses an endpoint with no server. Cases 2 and 3 set readonly=1 to get a retryable server error (164).
  2. 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(), so reset() fails for a BufferedInputStream. This issue is about the error when reset() fails.
  • #3300 (open): removes the per-attempt WARN log, 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, main at 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=1 for cases 2 and 3)
  • CREATE TABLE statements 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.

Vorherrschende Sprache
Java
Sterne
1.6k
Forks
657
Ø Merge
2 T. 6 Std.
Gemergte PRs (30 T.)
36

Entwicklungsumgebung

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus ClickHouse/clickhouse-java

Alle Issues in ClickHouse/clickhouse-java

Ähnliche Issues

Weitere Issues zu Java

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.