Skip to content

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

Backlog

Description

@polyglotAI-bot

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:

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 051a7ec (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.

Activity

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

    area:client-insertbugclient-api-v2

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions