Skip to content

JDBC does not recognize CH errors in the middle of a result #650

Open

Description

@den-crane
SELECT toString(cityHash64(number)) 
FROM  numbers(10000000000)    
where intDiv(1,number-100000)>-1000000000000000 


....
15335767028551339235
12760187302687605805
11100438807872808134
708232450366267289
8950872048444443462
12595162315755727141
15351880352077599325
13448237354462061702
2932317051899664345
4513747946220550376
2548036246277231731
Code: 153, e.displayText() = DB::Exception: Division by zero (version 20.8.18.32 (official build))

Now the error is just one more value. No JAVA exception.

Activity

  1. den-crane commented on May 5, 2021

    @den-crane
    ContributorAuthor

    hm, but only in the case with a single column.

  2. zhicwu commented on May 5, 2021

    @zhicwu
    Contributor

    Thanks @den-crane. I was able to reproduce the issue on 21.3 as well. I think the problem is server responded 200, so unless we parse each line of the result(regardless what the output format is), we'll run into this kind of issue.

    I also tried different output format and multiple columns, but unfortunately they all have the same issue.

    curl -v 'http://localhost:8123/?query=SELECT+2,+1+FROM+system.numbers+where+intDiv(1,number-100000)>-10
    0000000000000+FORMAT+RowBinary'
    *   Trying 127.0.0.1...
    * TCP_NODELAY set
    * Connected to localhost (127.0.0.1) port 8123 (#0)
    > GET /?query=SELECT+2,+1+FROM+system.numbers+where+intDiv(1,number-100000)>-100000000000000+FORMAT+RowBinary HTTP/1.1
    > Host: localhost:8123
    > User-Agent: curl/7.58.0
    > Accept: */*
    >
    < HTTP/1.1 200 OK
    < Date: Wed, 05 May 2021 23:21:27 GMT
    < Connection: Keep-Alive
    < Content-Type: application/octet-stream
    < X-ClickHouse-Server-Display-Name: ***
    < Transfer-Encoding: chunked
    < X-ClickHouse-Query-Id: c2ecb703-4aef-4101-b386-b1d3036ef75c
    < X-ClickHouse-Format: RowBinary
    < X-ClickHouse-Timezone: Etc/UTC
    < Keep-Alive: timeout=3
    < X-ClickHouse-Summary: {"read_rows":"0","read_bytes":"0","written_rows":"0","written_bytes":"0","total_rows_to_read":"0"}
    <
    ...
    Code: 153, e.displayText() = DB::Exception: Division by zero: while executing 'FUNCTION intDiv(1 :: 1, minus(number, 100000) :: 4) -> intDiv(1, minus(number, 100000)) Int8 : 2' (version 21.3.9.83 (official build))
    * Connection #0 to host localhost left intact
  3. zhicwu commented on May 6, 2021

    @zhicwu
    Contributor

    With http response 200, error only happens when 1) there's network issue(IOException); or 2) JDBC driver failed to parse value(e.g. trying the parse the error message as a number). As a result, when output format is TabSeparated*(or similar text-based format) and the ResultSet only contains one column, and either the column type is String or we use resultSet.getString() to retrieve value, there will be no exception.

    This cannot be fixed easily on client side without changing output format, because user can write arbitrary SQL - it's hard to tell if there's error or not from result of below SQL:

    select '1' as a
    union all
    select 'Code: 153, e.displayText() = DB::Exception: Division by zero: while executing ''FUNCTION intDiv(1 :: 1, minus(number, 100000) :: 4) -> intDiv(1, minus(number, 100000)) Int8 : 2'' (version 21.3.9.83 (official build))'

    @den-crane suggested to look into ClickHouse/ClickHouse#21136. Before http interface is enhanced, I hope switching to RowBinary format can fix the issue from client side.

  4. added this to the 0.3.2 Release milestone on May 6, 2021
  5. added
    legacy
    on Oct 6, 2021
  6. zhicwu commented on Nov 28, 2021

    @zhicwu
    Contributor

    In 0.3.1 and earlier version, query SELECT '2' FROM system.numbers where intDiv(1,number-100000)>-100000000000000 will return below result without any exception - the error message became last line of result set:

    '2'
    Code: 153. DB::Exception: Division by zero: while executing 'FUNCTION intDiv(1 :: 1, minus(number, 100000) :: 4) -> intDiv(1, minus(number, 100000)) Int8 : 2'. (ILLEGAL_DIVISION) (version 21.11.4.14 (official build))
    

    Starting from 0.3.2, depending on protocol you chose, the result is slightly different:

    • http - deserialization error(because we now use binary format), not ideal
    java.io.UncheckedIOException: Failed to read column #1(total 1): '2' String
    
    • grpc - expected error
    Error: DB::Exception: Division by zero: while executing 'FUNCTION intDiv(1 :: 1, minus(number, 100000) :: 4) -> intDiv(1, minus(number, 100000)) Int8 : 2' on server ClickHouseNode(addr=grpc:192.168.3.16:9100, db=default)@340446604
    SQLState:  07000
    ErrorCode: 1002
  7. den-crane commented on Feb 10, 2023

    @den-crane
    ContributorAuthor

    clickhouse-jdbc-0.4.0-shaded.jar:

    SELECT toString(cityHash64(number)) FROM  numbers(10000000000) where intDiv(1,number-1000000)>-1000000000000000
    
    java.io.IOException: Reached end of input stream after reading 22 of 51 bytes
    
  8. zhicwu commented on Feb 10, 2023

    @zhicwu
    Contributor

    Thanks @den-crane. The inner exception should be changed to StreamCorruptedException as it's more specific. There's buffer(size = 4096 but it's customizable) in ClickHouseInputStream, so if there's no fake error(rare but possible) and the error message is not too long, I should be able to extract the error.

    Using curl:

    echo "SELECT toString(cityHash64(number)) FROM  numbers(10000000000) where intDiv(1,number-1000000)>-1000000000000000" | curl -X POST 'http://localhost:8123/' --data-binary @-
    ...
    18400166420351108711
    Code: 153. DB::Exception: Division by zero: while executing 'FUNCTION intDiv(1 :: 1, minus(number, 1000000) :: 4) -> intDiv(1, minus(number, 1000000)) Int8 : 2'. (ILLEGAL_DIVISION) (version 22.8.13.20 (official build))

    Using Java:

    java.io.UncheckedIOException: Failed to read column #1 of 1: toString(cityHash64(number)) String
    	at com.clickhouse.data.ClickHouseDataProcessor.nextRecord(ClickHouseDataProcessor.java:142)
    	at com.clickhouse.data.ClickHouseDataProcessor.access$000(ClickHouseDataProcessor.java:23)
    	at com.clickhouse.data.ClickHouseDataProcessor$RecordsIterator.next(ClickHouseDataProcessor.java:49)
    	at com.clickhouse.data.ClickHouseDataProcessor$RecordsIterator.next(ClickHouseDataProcessor.java:35)
    	at com.clickhouse.examples.jdbc.Test.client(Test.java:332)
    	at com.clickhouse.examples.jdbc.Test.main(Test.java:578)
    Caused by: java.io.IOException: Reached end of input stream after reading 22 of 51 bytes
    	at com.clickhouse.data.stream.AbstractByteArrayInputStream.readBytes(AbstractByteArrayInputStream.java:236)
    	at com.clickhouse.data.stream.AbstractByteArrayInputStream.readBuffer(AbstractByteArrayInputStream.java:163)
    	at com.clickhouse.data.ClickHouseInputStream.readString(ClickHouseInputStream.java:1025)
    	at com.clickhouse.data.ClickHouseInputStream.readUnicodeString(ClickHouseInputStream.java:1061)
    	at com.clickhouse.data.format.BinaryDataProcessor.readTextString(BinaryDataProcessor.java:668)
    	at com.clickhouse.data.format.ClickHouseRowBinaryProcessor.readAndFill(ClickHouseRowBinaryProcessor.java:249)
    	at com.clickhouse.data.ClickHouseDataProcessor.nextRecord(ClickHouseDataProcessor.java:132)
    	... 5 more
    
  9. added
    connectivity
    on Jan 10, 2025
  10. 11 remaining items

  11. added this to the 0.9.7 milestone on Jan 7, 2026
  12. modified the milestones: 0.9.7, 0.9.8 on Jan 21, 2026
  13. modified the milestones: 0.9.8, 0.9.9 on Mar 16, 2026
  14. added this to the 0.9.10 milestone on Apr 15, 2026
  15. modified the milestones: 0.11.0, 0.12.0 on Sep 23, 2026
  16. removed this from the 0.12.0 milestone on Nov 10, 2026
  17. added
    jdbc
    on Nov 26, 2026
  18. polyglotAI-bot commented on Nov 29, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    jdbc-v2, client-v2, and the v1 driver lose a server error that comes after HTTP 200. Open PR #3097 fixes only client-v2 and jdbc-v2 (it closes #2702), and its diff does not apply to main. This issue is the only one for the v1 driver.

    Analysis: The server part is done: ClickHouse/ClickHouse#75175 closed with ClickHouse/ClickHouse#88818 (first in 25.11). After HTTP 200, the server now sends the header X-ClickHouse-Exception-Tag, ends the body with a tagged __exception__ frame, and cuts the connection. main does not read that header: client-v2 checks only X-ClickHouse-Exception-Code (HttpAPIClientHelper.java:848), and BinaryStreamReader.java:307 reports the cut stream as a column read error. The v1 transport also checks only that header (ApacheHttpConnectionImpl.java:215-216).

    Reproduction: complete program and output

    Changed from the issue's steps: the error at number 10000000 in place of 1000000, so that the server always sends HTTP 200 first (with 1000000 the error sometimes comes before it); one case for each module, and a contrast case.

    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader;
    import com.clickhouse.client.api.query.QueryResponse;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        // The issue's query; the server fails with "Division by zero" (code 153) at number 10000000,
        // after it has sent HTTP 200 and some million rows.
        static final String SQL = "SELECT toString(cityHash64(number)) FROM numbers(10000000000)"
                + " where intDiv(1,number-10000000)>-1000000000000000";
    
        static String describe(Throwable e) {
            String s = e.getClass().getSimpleName();
            if (e instanceof SQLException) s += " (errorCode " + ((SQLException) e).getErrorCode() + ")";
            String m = String.valueOf(e.getMessage());
            s += ": " + (m.length() > 120 ? m.substring(0, 120) + "…" : m);
            if (e.getCause() != null) s += " | cause " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage();
            return s;
        }
    
        static void jdbc(String label, String urlParams) throws Exception {
            Properties props = new Properties();
            props.setProperty("user", "default");
            props.setProperty("password", PASSWORD);
            String jdbcUrl = "jdbc:clickhouse:" + URL.replaceFirst("^https?:", "") + "/default" + urlParams;
            try (Connection conn = DriverManager.getConnection(jdbcUrl, props); Statement st = conn.createStatement()) {
                long rows = 0;
                try (ResultSet rs = st.executeQuery(SQL)) {
                    while (rs.next()) { rs.getString(1); rows++; }
                    System.out.println(label + ": no exception, rows=" + rows);
                } catch (Exception e) {
                    System.out.println(label + ": rows=" + rows + " then " + describe(e));
                }
            }
        }
    
        public static void main(String[] args) throws Exception {
            jdbc("jdbc-v2", "");
            try (Client client = new Client.Builder().addEndpoint(URL).setUsername("default").setPassword(PASSWORD).build()) {
                long rows = 0;
                try (QueryResponse r = client.query(SQL).get()) {
                    ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(r);
                    while (reader.next() != null) { rows++; }
                    System.out.println("client-v2: no exception, rows=" + rows);
                } catch (Exception e) {
                    System.out.println("client-v2: rows=" + rows + " then " + describe(e));
                }
            }
            // Contrast: with wait_end_of_query=1 the server sends no row before the error.
            jdbc("jdbc-v2, wait_end_of_query=1", "?clickhouse_setting_wait_end_of_query=1");
            // v1 driver (last: after it, the same JVM keeps the v1 driver); compress=0 because of #3107
            jdbc("v1 driver", "?clickhouse.jdbc.v1=true&compress=0");
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.4.11:

    jdbc-v2: rows=7783675 then SQLException (errorCode 0): Failed to read value for column toString(cityHash64(number)) | cause ClientException: Failed to read value for column toString(cityHash64(number))
    client-v2: rows=7783675 then ClientException: Failed to read value for column toString(cityHash64(number)) | cause ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
    jdbc-v2, wait_end_of_query=1: rows=0 then SQLException (errorCode 153): Code: 153. DB::Exception: Division by zero: while executing 'FUNCTION intDiv(1_UInt8 :: 1, minus(__table1.number, 100000… | cause ServerException: …
    v1 driver: rows=7783559 then SQLException (errorCode 0): org.apache.hc.core5.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected | cause ConnectionClosedException: …
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

  19. added
    api-diagnostics
    client
    on Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-diagnosticsblocked-by-clickhousebugclientconnectivityjdbclegacy

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions