[client-v2] use_form_request_for_query puts the SQL statement into a multipart form field, so SQL over 128 KiB fails with "HTML Form Exception: Field value too long"

Abierto
#3,437 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
55/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
java
Área
api, backend

Línea de trabajo

Start with client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java, especially createRequest() around lines 648–659, and trace how the multipart request carries the SQL and statement parameters. Review the existing client-v2 query tests and add coverage for SQL and parameter values larger than the server’s 128 KiB form-field limit. Done when multipart queries no longer fail for the reported large SQL case and the regression is covered by tests.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug client documentation queries

Description

When client.http.use_form_request_for_query (ClientConfigProperties.HTTP_SEND_PARAMS_IN_BODY) is enabled and a query has statement parameters, HttpAPIClientHelper.createRequest() builds a multipart/form-data body that contains both the param_* values and the SQL statement itself:

// client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java:648-659
if (useMultipart) {
    req.removeHeaders(HttpHeaders.CONTENT_ENCODING);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    addStatementParams(requestConfig, multipartEntityBuilder::addTextBody);
    multipartEntityBuilder.addTextBody(ClickHouseHttpProto.QPARAM_QUERY_STMT, body); // <-- SQL becomes a form field
    httpEntity = multipartEntityBuilder.build();
    ...
}

The server parses that body with Poco's HTMLForm, which caps each individual field value at http_max_field_value_size (128 KiB by default). So:

  1. Regression for large SQL. Without the option the SQL is the raw request body and is only bounded by max_query_size. With use_form_request_for_query=true plus any parameter, the same statement becomes a form field, and anything over 128 KiB is rejected — e.g. a big inline IN (...) list, or generated SQL that also binds a parameter. The option is advertised as a way to avoid long-URL failures (Client.java:1292), so it silently introduces a new, smaller limit on the statement.
  2. The escape hatch does not escape for big parameters either. Moving a parameter out of the URL into the form replaces a URL-length/field-size failure with the same 128 KiB form-field cap. A 200 KB parameter fails both ways; a 100 KB one works both ways.

Raising the cap through per-request server settings does not help, because the form is parsed before per-query settings are applied (and a readonly user cannot set it).

The error surfaced by client-v2 is also opaque — the response body is reported as <Unreadable error message>:

com.clickhouse.client.api.ServerException: Code: 1000. DB::Exception: <Unreadable error message> (transport error: 500)

while the raw server response is:

Poco::Exception. Code: 1000, e.code() = 0, HTML Form Exception: Field value too long (version 26.11.2.4 (official build))

ClickHouse server version

26.11.2.4 (official build), local single node over HTTP on localhost:8123.

Reproduction

client-v2/src/test/java/com/clickhouse/client/api/MultipartFieldSizeTest.java:

package com.clickhouse.client.api;

import com.clickhouse.client.api.query.GenericRecord;
import com.clickhouse.client.api.query.QuerySettings;
import org.testng.annotations.Test;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class MultipartFieldSizeTest {

    private Client newClient(boolean multipart) {
        return new Client.Builder()
                .addEndpoint("http://localhost:8123")
                .setUsername("default")
                .setPassword("")
                .setOption(ClientConfigProperties.HTTP_SEND_PARAMS_IN_BODY.getKey(), String.valueOf(multipart))
                .build();
    }

    private void run(String name, boolean multipart, String sql, Map<String, Object> params) {
        try (Client client = newClient(multipart)) {
            List<GenericRecord> records = client.queryAll(sql, params, new QuerySettings());
            System.out.println(name + ": OK " + records.get(0).getString(1));
        } catch (Exception e) {
            String msg = e.getMessage();
            if (e.getCause() != null) {
                msg = msg + " | cause: " + e.getCause().getMessage();
            }
            System.out.println(name + ": ERROR " + msg.split("\n")[0]);
        }
    }

    @Test
    public void testLargeSql() throws Exception {
        String padding = new String(new char[200_000]).replace('\0', 'x');
        String bigSql = "SELECT {p:UInt8} AS p, length('" + padding + "') AS len";
        Map<String, Object> p = Collections.singletonMap("p", 1);
        run("large SQL, no multipart", false, bigSql, p);
        run("large SQL, multipart",    true,  bigSql, p);

        String big = new String(new char[200_000]).replace('\0', 'y');
        String q = "SELECT length({p:String}) AS len";
        run("large param, no multipart", false, q, Collections.singletonMap("p", big));
        run("large param, multipart",    true,  q, Collections.singletonMap("p", big));

        String mid = new String(new char[100_000]).replace('\0', 'z');
        run("100KB param, multipart", true, q, Collections.singletonMap("p", mid));

        rawMultipart(bigSql); // show the server-side error text the client hides
    }

    private void rawMultipart(String sql) throws Exception {
        String boundary = "----b0undary";
        String payload = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"query\"\r\n\r\n"
                + sql + "\r\n--" + boundary + "--\r\n";
        java.net.HttpURLConnection c = (java.net.HttpURLConnection) new java.net.URL("http://localhost:8123/").openConnection();
        c.setRequestMethod("POST");
        c.setDoOutput(true);
        c.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        c.getOutputStream().write(payload.getBytes("UTF-8"));
        java.io.InputStream in = c.getResponseCode() >= 400 ? c.getErrorStream() : c.getInputStream();
        java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int n;
        while ((n = in.read(buf)) > 0) bos.write(buf, 0, n);
        System.out.println("raw multipart status=" + c.getResponseCode() + " body=" + bos.toString("UTF-8").trim());
    }
}

Run with mvn -pl client-v2 test -Dtest=MultipartFieldSizeTest (surefire redirects stdout to client-v2/target/surefire-reports/com.clickhouse.client.api.MultipartFieldSizeTest-output.txt).

Expected: large SQL, multipart succeeds, like large SQL, no multipart does — turning the option on should not shrink the maximum statement size.

Actual (on main, commit 67775d0d3):

large SQL, no multipart: OK 1
large SQL, multipart: ERROR Failed to get query response | cause: Code: 1000. DB::Exception: <Unreadable error message> (transport error: 500) (queryId= )
large param, no multipart: ERROR Failed to get query response | cause: Code: 1000. DB::Exception: <Unreadable error message> (transport error: 500) (queryId= )
large param, multipart: ERROR Failed to get query response | cause: Code: 1000. DB::Exception: <Unreadable error message> (transport error: 500) (queryId= )
100KB param, multipart: OK 100000
raw multipart status=500 body=Poco::Exception. Code: 1000, e.code() = 0, HTML Form Exception: Field value too long (version 26.11.2.4 (official build))

In an earlier run that left response compression at its default, the non-multipart 200 KB parameter case reported the message verbatim — Code: 1000, e.code() = 0, HTML Form Exception: Field value too long — confirming the same cause for the URL path.

The 100 KB control passing while 200 KB fails pins the failure on the 128 KiB per-field cap rather than on total body size.

Suggested fix

Roughly in order of how much they solve:

  • Keep the SQL out of the form. In HttpAPIClientHelper.createRequest() (client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java:648-659), send the statement as the raw request body (or as a URL query= entry when small) and put only param_* values into the multipart body. That removes failure mode 1 entirely and restores parity with the non-multipart path.
  • Add http_max_field_value_size to the URL query string (not to settings that travel in the form/body) when the multipart path is taken, so it is in effect before the form is parsed — with the documented caveat that a readonly user cannot raise it.
  • Surface a usable error. The client reports <Unreadable error message> for this 500; the Poco text is in the response body and should be propagated.
  • At minimum, document the 128 KiB per-field limit on ClientConfigProperties.HTTP_SEND_PARAMS_IN_BODY (ClientConfigProperties.java:306) and in Client.java:1292, and consider a client-side check that names the oversized part.

Link

Same defect reported for clickhouse-js: https://github.com/ClickHouse/clickhouse-js/issues/1219
Same server cap on other client paths: #3256 (INSERT statement in the URL), #2856 (parameters in the URL / HTTP 414).
Also reported for the Rust client: https://github.com/ClickHouse/clickhouse-rs/issues/501

Lenguaje dominante
Java
Estrellas
1.6k
Forks
657
Merge medio
2 d 6 h
PR fusionados (30 d)
36

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de ClickHouse/clickhouse-java

Todos los issues de ClickHouse/clickhouse-java

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.