diff --git a/client-v2/src/main/java/com/clickhouse/client/api/Client.java b/client-v2/src/main/java/com/clickhouse/client/api/Client.java index f7dc49519..fa0bf5ff4 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/Client.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/Client.java @@ -1700,6 +1700,9 @@ public CompletableFuture insert(String tableName, List data, /** *

Sends write request to database. Input data is read from the input stream.

* + *

See {@link #insert(String, List, InputStream, ClickHouseFormat, InsertSettings)} for how a retry uses + * {@code data}.

+ * * @param tableName - destination table name * @param data - data stream to insert * @param format - format of the data in the stream @@ -1712,6 +1715,9 @@ public CompletableFuture insert(String tableName, InputStream da /** *

Sends write request to database. Input data is read from the input stream.

* + *

See {@link #insert(String, List, InputStream, ClickHouseFormat, InsertSettings)} for how a retry uses + * {@code data}.

+ * * @param tableName - destination table name * @param data - data stream to insert * @param format - format of the data in the stream @@ -1726,6 +1732,9 @@ public CompletableFuture insert(String tableName, List c /** * Sends write request to database. Input data is read from the input stream. * + *

See {@link #insert(String, List, InputStream, ClickHouseFormat, InsertSettings)} for how a retry uses + * {@code data}.

+ * * @param tableName - destination table name * @param data - data stream to insert * @param format - format of the data in the stream @@ -1741,6 +1750,13 @@ public CompletableFuture insert(String tableName, /** * Sends write request to database. Input data is read from the input stream. * + *

Before each retry, the client calls {@link InputStream#reset()} on {@code data}, also when the failed + * attempt read no data. The client does not call {@link InputStream#mark(int)}, so the application must set a + * mark at the start of the data (a {@link java.io.ByteArrayInputStream} has one by default). If + * {@code reset()} throws an {@link java.io.IOException}, the operation fails with a {@link ClientException}. For a + * stream that cannot be reset, use {@link #insert(String, List, DataStreamWriter, ClickHouseFormat, InsertSettings)}, + * or set {@link ClientConfigProperties#CLIENT_RETRY_ON_FAILURE} to {@link ClientFaultCause#None}.

+ * * @param tableName - destination table name * @param columnNames - list of column names to insert data into. If null or empty, all columns will be used. * @param data - data stream to insert diff --git a/client-v2/src/main/java/com/clickhouse/client/api/DataStreamWriter.java b/client-v2/src/main/java/com/clickhouse/client/api/DataStreamWriter.java index bdc9b71de..3623b4a4c 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/DataStreamWriter.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/DataStreamWriter.java @@ -7,7 +7,8 @@ public interface DataStreamWriter { /** * Called by client when output stream is ready for user data. - * This method is called once per operation, so all data should be written while the call. + * This method is called once for each request that the client sends. Write all data in this call. + * A retry sends a new request, so the method is called again and must write all data again. * Output stream will be closed by client. * When client compression is enabled, then output stream will be a compressing one. * If {@link ClientConfigProperties#APP_COMPRESSED_DATA} is set for an operation, @@ -19,8 +20,12 @@ public interface DataStreamWriter { /** * Is called when client is going to perform a retry. + * The client calls this method before each retry, also when the failed attempt did not call + * {@link #onOutput(OutputStream)}. * It is optional to implement this method because most cases there is nothing to reset. * Useful to reset wrapped stream or throw exception to indicate that retry is not supported for a data source. + * If this method throws an {@link IOException}, the operation fails with a {@link ClientException} and the + * client makes no more attempts. * @throws IOException - when any IO exception happens. */ default void onRetry() throws IOException {} diff --git a/docs/clickhouse-docs/client.mdx b/docs/clickhouse-docs/client.mdx index 67dd0f753..fe6580371 100644 --- a/docs/clickhouse-docs/client.mdx +++ b/docs/clickhouse-docs/client.mdx @@ -167,8 +167,8 @@ Configuration is defined during client creation. See `com.clickhouse.client.api. | `setConnectionRequestTimeout(long timeout, ChronoUnit unit)` | `timeout` - timeout value
`unit` - time unit | Sets connection request timeout. This take effect only for getting connection from a pool. | `10000` | `connection_request_timeout` | | `setSocketTimeout(long timeout, ChronoUnit unit)` | `timeout` - timeout value
`unit` - time unit | Sets socket timeout that affects read and write operations | `0` | `socket_timeout` | | `setExecutionTimeout(long timeout, ChronoUnit timeUnit)` | `timeout` - timeout value
`timeUnit` - time unit | Sets maximum execution timeout for queries | `0` | `max_execution_time` | -| `retryOnFailures(ClientFaultCause ...causes)` | `causes` - enum constant of `ClientFaultCause` | Sets recoverable/retriable fault types. | `NoHttpResponse` `ConnectTimeout` `ConnectionRequestTimeout` | `client_retry_on_failures` | -| `setMaxRetries(int maxRetries)` | `maxRetries` - number of retries | Sets maximum number of retries for failures defined by `retryOnFailures` | `3` | `retry` | +| `retryOnFailures(ClientFaultCause ...causes)` | `causes` - enum constant of `ClientFaultCause` | Sets recoverable/retriable fault types. `ClientFaultCause.None` disables retries. | `NoHttpResponse` `ConnectTimeout` `ConnectionRequestTimeout` `ServerRetryable` | `client_retry_on_failures` | +| `setMaxRetries(int maxRetries)` | `maxRetries` - number of retries | Sets maximum number of retries for failures defined by `retryOnFailures`. With more than one endpoint, the maximum is the larger of this value and the number of endpoints minus 1. See [Retries and Input Streams](#insert-stream-retries). | `3` | `retry` | @@ -655,6 +655,56 @@ try (InputStream dataStream = getDataStream()) { ``` +#### Retries and Input Streams {#insert-stream-retries} + +The client retries an insert that fails for a cause in `retryOnFailures` (key `client_retry_on_failures`). The default causes are: + +- `NoHttpResponse`: the server closed the connection and sent no response. +- `ConnectTimeout`: the client cannot connect to the server. +- `ConnectionRequestTimeout`: the client cannot get a connection from the pool in time. +- `ServerRetryable`: the server returned an error for which `ServerException#isRetryable()` returns `true`, for example `MEMORY_LIMIT_EXCEEDED` (241) or `TOO_MANY_PARTS` (252). + +The client makes at most `setMaxRetries` retries (key `retry`, default `3`). For more than one endpoint, see `setMaxRetries` in [Client Configuration](#client-configuration). + +Before each retry, the client calls `reset()` on the `InputStream`. It does this also when the failed attempt read no data, for example after a connection failure. The client does not call `mark()`. Thus, `reset()` moves the stream back to the last mark that the application set, and the insert fails if the stream has no valid mark: + +| Stream | Retry | +|--------|-------| +| `ByteArrayInputStream` | Works. Its mark is at the start of the data until the application sets a different mark. | +| `BufferedInputStream` with no mark | Fails: `IOException: Resetting to invalid mark`. | +| `BufferedInputStream` after `mark(readlimit)` | Works if the data is not larger than `readlimit`. The stream keeps in memory all data that it read after the mark. | +| A stream for which `markSupported()` returns `false`, for example `FileInputStream` or `GZIPInputStream` | Fails: `IOException: mark/reset not supported`. | + +When `reset()` fails, the insert fails with `ClientException: Failed to reset stream before next attempt`, and the client makes no more attempts. The cause of this exception is the `IOException` from `reset()`. The client logs the error of the failed attempt at the `WARN` level. + +A retry after a server error can occur after the client sent all of the data. Thus, for a retry, the stream must keep all of the data. Use the procedure that applies to your data source: + +**The data fits in memory.** Use a `ByteArrayInputStream`, or call `mark()` at the start of the data before you call `insert`: + +```java +BufferedInputStream data = new BufferedInputStream(source); +data.mark(Integer.MAX_VALUE); // the stream keeps all data in memory +client.insert(TABLE_NAME, data, ClickHouseFormat.CSV).get(); +``` + +**You can open the source again, for example a file.** Use `insert(String tableName, DataStreamWriter writer, ClickHouseFormat format, InsertSettings settings)`. The client calls `DataStreamWriter#onOutput` for each request that it sends, so for a retry the writer reads the source again from the start. The client calls `DataStreamWriter#onRetry` before each retry. + +```java +Path file = Paths.get("data.csv"); +client.insert(TABLE_NAME, out -> Files.copy(file, out), ClickHouseFormat.CSV, new InsertSettings()).get(); +``` + +**You cannot reset the stream.** Disable retries. Then the client does not call `reset()`, and the insert fails with the error of the first attempt. For one insert: + +```java +InsertSettings settings = new InsertSettings(); +settings.setOption(ClientConfigProperties.CLIENT_RETRY_ON_FAILURE.getKey(), + Collections.singletonList(ClientFaultCause.None)); +client.insert(TABLE_NAME, dataStream, ClickHouseFormat.CSV, settings).get(); +``` + +For all operations of the client, use `Client.Builder#retryOnFailures(ClientFaultCause.None)`. `setMaxRetries(0)` disables retries only when the client has one endpoint. + ### insert(String tableName, List<?> data, InsertSettings settings) {#insertstring-tablename-listlt-data-insertsettings-settings} Sends a write request to database. The list of objects is converted into an efficient format and then is sent to a server. The class of the list items should be registered up-front using `register(Class, TableSchema)` method. diff --git a/docs/features.md b/docs/features.md index ef27f4018..9673f107f 100644 --- a/docs/features.md +++ b/docs/features.md @@ -68,6 +68,7 @@ Compatibility-sensitive traits: - JSONEachRow reading depends on the selected parser factory and request format settings: parser materialization determines Java value types, the reader infers minimal schema from the first row, and JSON number server settings are applied only when `QuerySettings` resolves to `ClickHouseFormat.JSONEachRow` and `json_disable_number_quoting` is enabled. - JSONEachRow schema inference is intentionally best-effort: scalar values use Java-to-ClickHouse type mappings, while JSON arrays and objects are identified structurally as `Array` and `Map`. For arrays, maps, and some nested or ambiguous values, the inferred type may not include the most specific element, key, value, or nested ClickHouse type. - Binary string support is scope-sensitive and off by default: it only changes how top-level `String`/`FixedString` columns are read (to `StringValue` instead of `String`); nested string values are always read as `String`. `StringValue` is produced only by the read path and has no public constructor (it cannot be instantiated by user code). It is intentionally a mutable, zero-copy holder — it wraps (does not copy) the bytes it is given and `toByteArray()` returns the live backing array when the value spans the whole array (otherwise an exact-size copy), so callers needing an independent snapshot must copy the bytes themselves. +- Insert retries depend on the data source: before each retry, an insert from an `InputStream` calls `reset()` on the stream, also when the failed attempt read no data, and never calls `mark()`. A stream with no valid mark (for example a `BufferedInputStream` with no mark, or a stream for which `markSupported()` is `false`) makes the insert fail with `ClientException` (`Failed to reset stream before next attempt`). An insert with a `DataStreamWriter` calls `onRetry()` before each retry and `onOutput()` once for each request that it sends. `ClientFaultCause.None` disables the retries, so `reset()` and `onRetry()` are not called. `retry=0` does not disable them when the client has more than one endpoint: the maximum number of retries is the larger of `retry` and the number of endpoints minus 1. ## `jdbc-v2`