[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"

Đang mở
#3,437 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
55/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
java
Lĩnh vực
api, backend

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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

Ngôn ngữ chính
Java
Star
1.6k
Fork
657
Merge trung bình
2 ngày 6 giờ
Pull request đã merge (30 ngày)
36

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của ClickHouse/clickhouse-java

Tất cả issue của ClickHouse/clickhouse-java

Issue tương tự

Thêm issue về Java

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.