Skip to content

In the JDBC query result set, columns of type AggregateFunction cannot be parsed normally #2662

Open

Description

@CCweixiao

Description

When creating a materialized view, specify the Select statement as follows:

SELECT
    toDate(timestamp) AS date,
    countState(*) AS count,
    quantileState(0.9)(duration) AS tp90_duration_ms,
    quantileState(0.99)(duration) AS tp99_duration_ms,
    avgState(duration) AS avg_duration_ms,
    maxState(duration) AS max_duration_ms,
    minState(duration) AS min_duration_ms
FROM test.test_table_local
GROUP BY
    date

This statement is queried directly with JDBC, and the final error is:
java.sql.SQLException: Failed to read value for column count

final debug result:

  1. BinaryStreamReader.java -> readValue method

     case AggregateFunction:
           return (T)this.readBitmap(actualColumn);
    
  2. readBitmap method

    private ClickHouseBitmap readBitmap(ClickHouseColumn column) throws IOException {
        return ClickHouseBitmap.deserialize(this.input, ((ClickHouseColumn)column.getNestedColumns().get(0)).getDataType());
    }

    column.getNestedColumns() is empty

Image

Error Log or Exception StackTrace

This statement is queried directly with JDBC, and the final error is:
java.sql.SQLException: Failed to read value for column count

Expected Behaviour

Code Example

Configuration

Client Configuration

Environment

  • Cloud
  • Client version: 0.9.4
  • Language version: 1.8
  • OS: mac

ClickHouse Server

  • ClickHouse Server version: 25.5.1

Activity

  1. chernser commented on Nov 19, 2025

    @chernser
    Contributor

    @CCweixiao
    Thank you for reporting this!
    We will look into it.

  2. added
    client
    data-types
    on Nov 19, 2025
  3. github-actions commented on Nov 20, 2026

    @github-actions

    This issue has been automatically marked as stale because it has not had activity in the last year. It will be closed in 30 days if no further activity occurs. Please feel free to leave a comment if you believe the issue is still relevant. Thank you for your contributions!

  4. polyglotAI-bot commented on Nov 28, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    The reader decodes every AggregateFunction state as a groupBitmap state, although the docs support only groupBitmap. So countState fails with an unclear error, and other states give wrong rows with no error. Reading the other states is the separate request #2599.

    Analysis: BinaryStreamReader.java:292 (client-v2, which jdbc-v2 uses) reads each AggregateFunction value with readBitmap (:1572), which takes the type of the first argument: count has no argument, so it throws IndexOutOfBoundsException, and the driver reports only "Failed to read value for column count". For other functions it reads the state bytes as a bitmap, so the stream loses synchronization; an EOFException in the first column then counts as the end of the data (AbstractBinaryFormatReader.java:203), with no error. The Native format fails with an error for the same states.

    Reproduction: complete program and output

    Changed from the issue's steps: added a table with data for the issue's SELECT, each state alone, groupBitmapState, finalizeAggregation, and two client-v2 reads.

    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader;
    import com.clickhouse.client.api.query.QueryResponse;
    import com.clickhouse.client.api.query.QuerySettings;
    import com.clickhouse.data.ClickHouseFormat;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    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", "");
    
        public static void main(String[] args) throws Exception {
            Properties props = new Properties();
            props.setProperty("user", "default");
            props.setProperty("password", PASSWORD);
            String jdbcUrl = "jdbc:clickhouse:" + URL.replaceFirst("^https?:", "") + "/default";
            try (Connection conn = DriverManager.getConnection(jdbcUrl, props); Statement st = conn.createStatement()) {
                st.execute("DROP TABLE IF EXISTS test_table_local");
                st.execute("CREATE TABLE test_table_local (timestamp DateTime, duration UInt64) ENGINE = MergeTree ORDER BY timestamp");
                st.execute("INSERT INTO test_table_local SELECT toDateTime('2025-11-19 00:00:00') + number, number FROM numbers(100)");
                // The SELECT of the materialized view in the issue
                jdbc(st, "SELECT toDate(timestamp) AS date, countState(*) AS count, quantileState(0.9)(duration) AS tp90_duration_ms, "
                        + "quantileState(0.99)(duration) AS tp99_duration_ms, avgState(duration) AS avg_duration_ms, "
                        + "maxState(duration) AS max_duration_ms, minState(duration) AS min_duration_ms FROM test_table_local GROUP BY date");
                // Each state of the issue alone (the server returns 1 row), groupBitmapState, and finalizeAggregation
                for (String f : new String[] {"countState()", "quantileState(0.9)(duration)", "avgState(duration)", "maxState(duration)",
                        "minState(duration)", "groupBitmapState(duration)", "finalizeAggregation(avgState(duration))"}) {
                    jdbc(st, "SELECT " + f + " FROM test_table_local");
                }
            }
            try (Client client = new Client.Builder().addEndpoint(URL).setUsername("default").setPassword(PASSWORD).build()) {
                for (ClickHouseFormat format : new ClickHouseFormat[] {ClickHouseFormat.RowBinaryWithNamesAndTypes, ClickHouseFormat.Native}) {
                    String sql = "SELECT avgState(duration) FROM test_table_local";
                    try (QueryResponse response = client.query(sql, new QuerySettings().setFormat(format)).get()) {
                        ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response);
                        int rows = 0;
                        while (reader.next() != null) rows++;
                        System.out.println("client-v2 " + format + " " + sql + " -> rows=" + rows);
                    } catch (Exception e) {
                        System.out.println("client-v2 " + format + " " + sql + " -> " + e.getClass().getName() + ": " + e.getMessage());
                    }
                }
                client.execute("DROP TABLE test_table_local").get().close();
            }
        }
    
        static void jdbc(Statement st, String sql) {
            String name = sql.length() > 70 ? sql.substring(0, 70) + "…" : sql;
            try (ResultSet rs = st.executeQuery(sql)) {
                int rows = 0;
                Object last = null;
                while (rs.next()) {
                    rows++;
                    last = rs.getObject(1);
                }
                System.out.println("jdbc " + name + " -> rows=" + rows
                        + (last != null ? ", value " + (last instanceof Number ? last : last.getClass().getSimpleName()) : ""));
            } catch (Exception e) {
                System.out.println("jdbc " + name + " -> " + e.getClass().getName() + ": " + e.getMessage()
                        + (e.getCause() != null && e.getCause().getCause() != null ? " | cause " + e.getCause().getCause() : ""));
            }
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.4.11:

    jdbc SELECT toDate(timestamp) AS date, countState(*) AS count, quantileStat… -> java.sql.SQLException: Failed to read value for column count | cause java.lang.IndexOutOfBoundsException: Index: 0
    jdbc SELECT countState() FROM test_table_local -> java.sql.SQLException: Failed to read value for column countState() | cause java.lang.IndexOutOfBoundsException: Index: 0
    jdbc SELECT quantileState(0.9)(duration) FROM test_table_local -> rows=6, value ClickHouseRoaring64NavigableMap
    jdbc SELECT avgState(duration) FROM test_table_local -> rows=0
    jdbc SELECT maxState(duration) FROM test_table_local -> rows=0
    jdbc SELECT minState(duration) FROM test_table_local -> rows=0
    jdbc SELECT groupBitmapState(duration) FROM test_table_local -> rows=1, value ClickHouseRoaring64NavigableMap
    jdbc SELECT finalizeAggregation(avgState(duration)) FROM test_table_local -> rows=1, value 49.5
    client-v2 RowBinaryWithNamesAndTypes SELECT avgState(duration) FROM test_table_local -> rows=0
    client-v2 Native SELECT avgState(duration) FROM test_table_local -> com.clickhouse.client.api.ClientException: Failed to read block
    

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

  5. added
    jdbc
    native-format
    on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugclientdata-typesjdbcnative-format

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions