[client-v1] ClickHouseException.getErrorCode() takes the code from a data row when a compressed query fails after rows

Aberta
#3,445 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
48/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
java
Domínio
api, backend

Direção de pesquisa

Read ApacheHttpConnectionImpl.checkResponse and HttpUrlConnectionImpl for client-v1, then compare ClickHouseException.extractErrorCode and ClickHouseHttpConnection.parseErrorFromException; the report also identifies HttpAPIClientHelper.readClickHouseError in client-v2 and related issue #3439. Start by tracing how response headers and body text determine the error code and message. Reproduce with the supplied Java example; done when failures after rows report server code 395 and a message beginning with the server exception.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

api-diagnostics bug client

Description

When a query fails during execution and the response is compressed, the server answers HTTP 500 with the rows that it already produced, then the exception text. If a row before the exception contains Code: <N>, client-v1 throws a ClickHouseException whose getErrorCode() is the <N> of the row, not the server's code. The message also starts in the row data. The same defect was reported for clickhouse-js in https://github.com/ClickHouse/clickhouse-js/issues/1175.

Values of this form are normal, for example in SELECT exception FROM system.query_log.

Scope seen in the run (3 of 3 runs):

  • client-v1 over HTTP, with the default compress_algorithm (LZ4, compress=1) and with GZIP, ZSTD, BROTLI and DEFLATE; formats JSONEachRow and RowBinaryWithNamesAndTypes.
  • client-v2 takes the code from the X-ClickHouse-Exception-Code header, so its code is correct. Its message starts in the row data only when a row contains the same code text (Code: 395. ), with and without useHttpCompression(true).
Steps to reproduce
  1. Start ClickHouse server 26.10 with default settings.
  2. Run the code example (set CLICKHOUSE_URL and CLICKHOUSE_PASSWORD as needed). Each query fails with throwIf after the server produced some rows.
  3. Compare each code and message with the server's code 395.
Error Log or Exception StackTrace
v1 LZ4: code 60, message Code: 60. DB::Exception: Unknown table x.
v1 GZIP: code 60, message {"exception":"Code: 60. DB::Exception: Unk
v2: code 395, message Code: 395. DB::Exception: boom: while exec
v1 LZ4: code 395, message Code: 395. DB::Exception: text in a row","
v1 GZIP: code 395, message {"exception":"Code: 395. DB::Exception: te
v2: code 395, message Code: 395. DB::Exception: text in a row","
v1 LZ4: code 395, message Code: 395, server: 2026cacdf86a, r?+??̶!#븵
v1 GZIP: code 395, message {"exception":"hello","number":0}?{"excepti
v2: code 395, message Code: 395. DB::Exception: boom: while exec

Only lines 3 and 9 are correct. Line 7 (raw compressed bytes) is #3107.

Expected Behaviour

Each line has code 395 and a message that starts with Code: 395. DB::Exception: boom. The server sends that code in the header and as the last text of the body (decompressed, curl -H 'Accept-Encoding: gzip' '…&enable_http_compression=1'; with compress=1 the status and header are the same):

HTTP/1.1 500 Internal Server Error
X-ClickHouse-Exception-Code: 395
Content-Encoding: gzip

{"exception":"Code: 60. DB::Exception: Unknown table x. (UNKNOWN_TABLE) (version 1)","number":0}
...
Code: 395. DB::Exception: boom: while executing 'FUNCTION throwIf(...)'. (FUNCTION_THROW_IF_VALUE_IS_NON_ZERO) (version 26.10.4.207 (official build))
Root cause
  • client-v1: checkResponse (clickhouse-http-client/src/main/java/com/clickhouse/client/http/ApacheHttpConnectionImpl.java:259, the same in HttpUrlConnectionImpl) throws the whole decoded body as the message and does not use the X-ClickHouse-Exception-Code header for the code. extractErrorCode (clickhouse-client/src/main/java/com/clickhouse/client/ClickHouseException.java:69) then takes the first Code: <N> of the message. When the body cannot be decoded, parseErrorFromException (ClickHouseHttpConnection.java:326) starts the message at the first ode: of the raw bytes, with the same result.
  • client-v2: readClickHouseError (client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java:517) starts the message at the first <code>. of the body.

The server's exception is the last text of the body. Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.

Related:

  • #3107 (open) is the LZ4 decoding failure on 26.9+; GZIP shows the same codes without it.
  • #3439 (open): readClickHouseError also matches a part of the code at the end of a read. One change of the search can fix both.
Code Example
Reproduction program (Java, 40 lines)
import com.clickhouse.client.*;
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.ServerException;
import com.clickhouse.client.api.query.QuerySettings;
import com.clickhouse.client.config.ClickHouseClientOption;
import com.clickhouse.data.ClickHouseCompression;
import com.clickhouse.data.ClickHouseFormat;

public class ErrorCodeFromRow {
    public static void main(String[] args) throws Exception {
        String url = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        String password = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        String[] rows = {"Code: 60. DB::Exception: Unknown table x. (UNKNOWN_TABLE) (version 1)",
                "Code: 395. DB::Exception: text in a row", "hello"};
        ClickHouseNode server = ClickHouseNode.of(url + "/default?user=default&password=" + password);
        for (String row : rows) {
            // The query fails during execution, after the server produced some rows.
            String sql = "SELECT '" + row + "' AS exception, number FROM numbers(10)"
                    + " WHERE throwIf(number = 5, 'boom') = 0 SETTINGS max_block_size = 1";
            for (ClickHouseCompression alg : new ClickHouseCompression[] {ClickHouseCompression.LZ4, ClickHouseCompression.GZIP}) {
                try (ClickHouseClient c = ClickHouseClient.newInstance(ClickHouseProtocol.HTTP);
                     ClickHouseResponse r = c.read(server).option(ClickHouseClientOption.COMPRESS_ALGORITHM, alg)
                             .format(ClickHouseFormat.JSONEachRow).query(sql).executeAndWait()) {
                } catch (ClickHouseException e) {
                    System.out.println("v1 " + alg + ": code " + e.getErrorCode() + ", message " + start(e.getMessage()));
                }
            }
            try (Client c = new Client.Builder().addEndpoint(url).setUsername("default").setPassword(password).build()) {
                c.query(sql, new QuerySettings().setFormat(ClickHouseFormat.JSONEachRow)).get().close();
            } catch (ServerException e) {
                System.out.println("v2: code " + e.getCode() + ", message " + start(e.getMessage()));
            }
        }
    }

    static String start(String m) {
        return m.replaceAll("[\\x00-\\x1f]", "?").substring(0, 42);
    }
}
Configuration
Client Configuration
// client-v1: default options, compress_algorithm LZ4 (default) or GZIP
ClickHouseClient.newInstance(ClickHouseProtocol.HTTP).read(server).option(ClickHouseClientOption.COMPRESS_ALGORITHM, alg)
// client-v2: default options
new Client.Builder().addEndpoint(url).setUsername("default").setPassword(password).build()
Environment
  • Cloud
  • Client version: main at 051a7ecfd (0.12.0-rc1-SNAPSHOT); the root-cause files are the same on 8480ca001
  • Language version: Java 17 (OpenJDK 17.0.21.1)
  • OS: Linux (Docker)
ClickHouse Server
  • ClickHouse Server version: 26.10.4.207
  • ClickHouse Server non-default settings, if any: none
  • CREATE TABLE statements for tables involved: none (numbers(10))
  • Sample data for all these tables: none

Classification: impact: none · area: API & diagnostics (error parsing)


Found by automated analysis (Polyglot AI) while checking clickhouse-js#1175 against the other client repos. 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

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de ClickHouse/clickhouse-java

Todas as issues de ClickHouse/clickhouse-java

Issues semelhantes

Mais issues de Java

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.