From b61f2ea701bca080cb1317c005a759798331a4f3 Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:25:15 +0000 Subject: [PATCH] [client-v2] Native reader: decode Int8, strided, Nullable and Array QBit columns The Native reader decoded only a plain QBit(Float32|Float64|BFloat16, N) and rejected the other QBit columns. It now also decodes QBit(Int8, N), strided QBit(E, N, S) (element_size bit planes for each of the N / S stride groups, group after group), Nullable(QBit), Array(QBit) and Array(Nullable(QBit)), to the same values as the RowBinary readers. Implements: https://github.com/ClickHouse/clickhouse-java/issues/2980 Co-Authored-By: Claude Opus 5.5 --- .../api/data_formats/NativeFormatReader.java | 105 ++++++++++++++---- .../internal/BinaryStreamReader.java | 79 ++++++++----- .../data_formats/NativeFormatReaderTest.java | 64 +++++++++-- .../internal/BinaryStreamReaderTests.java | 55 ++++++++- .../client/datatypes/DataTypeTests.java | 92 +++++++++++++++ docs/features.md | 2 +- docs/qbit-encoding.md | 83 ++++++++------ history/latest/2980.md | 7 ++ 8 files changed, 394 insertions(+), 93 deletions(-) create mode 100644 history/latest/2980.md diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java index 06b4170e6..2e8f4aa6f 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java @@ -216,17 +216,19 @@ private void readBlock() throws IOException { List values; if (isNativeDecodableQBit(column)) { // Decode the Native bit-plane layout (docs/qbit-encoding.md). - values = binaryStreamReader.readQBitNative(column, nRows); + values = readQBitColumn(column, nRows); + } else if (column.isArray() && column.getArrayNestedLevel() == 1 + && isNativeDecodableQBit(column.getNestedColumns().get(0))) { + values = readQBitArrayColumn(column, nRows); } else if (containsQBit(column)) { - // Any other QBit shape (non-float element, strided, Nullable/LowCardinality, or nested) - // uses a Native layout this reader does not decode; fail loudly rather than misread the - // block and desynchronize the columns that follow (docs/qbit-encoding.md). + // Any other QBit shape uses a Native layout this reader does not decode; fail loudly rather + // than misread the block and desynchronize the columns that follow (docs/qbit-encoding.md). throw new ClientException("Reading column '" + column.getColumnName() + "' (" + column.getOriginalTypeName() + ") from the Native format is not supported: " - + "this reader decodes only a plain top-level QBit column with a Float32, Float64 " - + "or BFloat16 element type. A QBit whose element type is none of those, or that is " - + "strided, wrapped in Nullable/LowCardinality, or nested inside another type " - + "(e.g. Array/Tuple/Map), is not decoded. Use a RowBinary format " + + "this reader decodes a QBit column with an Int8, BFloat16, Float32 or Float64 element " + + "type, also when it is strided, Nullable, or the element of a one-level Array. " + + "A QBit with another element type, in LowCardinality, or inside a Tuple, Map, " + + "Variant, multi-level Array or another container is not decoded. Use a RowBinary format " + "(e.g. RowBinaryWithNamesAndTypes) to read such QBit values"); } else if (isGeo(column)) { // Native writes a geo column column-major: a Point as the two Float64 sub-columns of its @@ -291,31 +293,90 @@ private void readBlock() throws IOException { } /** - * Returns {@code true} for a plain top-level {@code QBit(Float32|Float64|BFloat16, dimension)} the - * reader can decode from the Native bit-plane layout — not {@code Nullable}/{@code LowCardinality}, - * not strided, not nested. Other QBit shapes are caught by {@link #containsQBit} and rejected in - * {@link #readBlock} (see {@code docs/qbit-encoding.md}). + * Returns {@code true} for a {@code QBit(Int8|BFloat16|Float32|Float64, dimension[, stride])} column, also + * {@code Nullable}, that the reader can decode from the Native bit-plane layout. Other QBit shapes are caught + * by {@link #containsQBit} and rejected in {@link #readBlock} (see {@code docs/qbit-encoding.md}). */ private static boolean isNativeDecodableQBit(ClickHouseColumn column) { - if (column.getDataType() != ClickHouseDataType.QBit - || column.isNullable() || column.isLowCardinality() + if (column.getDataType() != ClickHouseDataType.QBit || column.isLowCardinality() || column.getNestedColumns().isEmpty()) { return false; } - // A strided QBit has a third parameter (stride) and a plane count this decoder does not handle. - if (column.getParameters().size() > 2) { - return false; - } switch (column.getNestedColumns().get(0).getDataType()) { + case Int8: + case BFloat16: case Float32: case Float64: - case BFloat16: return true; default: return false; } } + /** + * Reads {@code count} values of a QBit column accepted by {@link #isNativeDecodableQBit}. A {@code Nullable} + * column starts with a null map of {@code count} bytes; a null row still has a placeholder vector after it. + */ + private List readQBitColumn(ClickHouseColumn column, int count) throws IOException { + boolean[] nulls = null; + if (column.isNullable()) { + nulls = new boolean[count]; + for (int j = 0; j < count; j++) { + nulls[j] = binaryStreamReader.readByte() == 1; + } + } + List values = binaryStreamReader.readQBitNative(column, count); + if (nulls != null) { + for (int j = 0; j < count; j++) { + if (nulls[j]) { + values.set(j, null); + } + } + } + return values; + } + + /** + * Reads an {@code Array(QBit(...))} or {@code Array(Nullable(QBit(...)))} column: {@code nRows} cumulative + * offsets, then the QBit column of all elements. Each row is an {@code ArrayValue} with the item class that + * {@link BinaryStreamReader#readArray} gives for the same column over RowBinary. + */ + private List readQBitArrayColumn(ClickHouseColumn column, int nRows) throws IOException { + long[] offsets = new long[nRows]; + for (int j = 0; j < nRows; j++) { + offsets[j] = binaryStreamReader.readLongLE(); + } + ClickHouseColumn elementColumn = column.getNestedColumns().get(0); + List elements = readQBitColumn(elementColumn, nRows == 0 ? 0 : Math.toIntExact(offsets[nRows - 1])); + + List values = new ArrayList<>(nRows); + int start = 0; + for (int j = 0; j < nRows; j++) { + int end = Math.toIntExact(offsets[j]); + int len = end - start; + if (len < 0) { + throw new ClientException("Failed to read column '" + column.getColumnName() + + "': its array offsets decrease at row " + j); + } + BinaryStreamReader.ArrayValue array; + if (len == 0) { + // Reads no bytes; gives the same empty array as the RowBinary read. + array = binaryStreamReader.readArray(column, 0); + } else { + Object first = elements.get(start); + Class itemClass = elementColumn.isNullable() ? Object.class + : first instanceof List ? List.class : first.getClass(); + array = new BinaryStreamReader.ArrayValue(itemClass, len); + for (int k = 0; k < len; k++) { + array.set(k, elements.get(start + k)); + } + } + values.add(array); + start = end; + } + return values; + } + /** * Returns {@code true} for a geo column ({@code Point}, {@code Ring}, {@code LineString}, * {@code MultiPoint}, {@code Polygon}, {@code MultiLineString} or {@code MultiPolygon}). Geo types @@ -340,9 +401,9 @@ private static boolean isGeo(ClickHouseColumn column) { /** * Returns {@code true} if {@code column} is or contains a {@code QBit} anywhere in its nested type - * tree (e.g. {@code Array}/{@code Tuple}/{@code Map(String, QBit(...))}). Used by {@link #readBlock} - * to reject the QBit shapes {@link #isNativeDecodableQBit} does not decode. {@code Nullable}/ - * {@code LowCardinality} are column flags, so a wrapped {@code QBit} still reports + * tree (e.g. {@code Tuple}/{@code Map(String, QBit(...))}). Used by {@link #readBlock} to reject the + * QBit shapes that {@link #isNativeDecodableQBit} and {@link #readQBitArrayColumn} do not decode. + * {@code Nullable}/{@code LowCardinality} are column flags, so a wrapped {@code QBit} still reports * {@code dataType == QBit} here. */ private static boolean containsQBit(ClickHouseColumn column) { diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReader.java index a3516aa8d..1a1b31b8c 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReader.java @@ -687,28 +687,41 @@ private T readQBit(ClickHouseColumn column, Class typeHint) throws IOExce } /** - * Reads a plain, non-strided {@code QBit(Float32|Float64|BFloat16, dimension)} column from the - * Native format, reversing the server's bit-plane transpose into one vector per row. Values match - * the RowBinary path ({@link #readQBit}), so a {@code QBit} round-trips equally through either - * format. See {@code docs/qbit-encoding.md} for the wire layout and the transpose math. + * Reads a {@code QBit(element_type, dimension[, stride])} column from the Native format, reversing the + * server's bit-plane transpose into one vector per row. The element type is {@code Int8}, {@code BFloat16}, + * {@code Float32} or {@code Float64}. Values match the RowBinary path ({@link #readQBit}), so a {@code QBit} + * round-trips equally through either format. The caller reads the null map of a {@code Nullable(QBit)} + * column. See {@code docs/qbit-encoding.md} for the wire layout and the transpose math. * - * @param column QBit column information (element type in the nested column, dimension in precision) - * @param nRows number of rows in the current block - * @return one materialized vector per row, in row order + * @param column QBit column information (element type in the nested column, dimension in precision, + * optional stride in the third parameter) + * @param nRows number of QBit values to read + * @return one materialized vector per value, in order * @throws IOException when an IO error occurs */ public List readQBitNative(ClickHouseColumn column, int nRows) throws IOException { - ClickHouseDataType elementType = column.getNestedColumns().get(0).getDataType(); - final boolean isDouble = elementType == ClickHouseDataType.Float64; - final boolean isBFloat16 = elementType == ClickHouseDataType.BFloat16; - if (!isDouble && !isBFloat16 && elementType != ClickHouseDataType.Float32) { - throw new ClientException("QBit Native decoding supports only Float32, Float64 and BFloat16 " - + "element types, got: " + elementType); + final ClickHouseDataType elementType = column.getNestedColumns().get(0).getDataType(); + switch (elementType) { + case Int8: + case BFloat16: + case Float32: + case Float64: + break; + default: + throw new ClientException("QBit Native decoding supports only Int8, BFloat16, Float32 and Float64 " + + "element types, got: " + elementType); } - final int elementBits = elementType.getByteLength() * 8; // 16 (BFloat16), 32 (Float32), 64 (Float64) + final int elementBits = elementType.getByteLength() * 8; // 8, 16, 32 or 64 bit planes per stride group final int dimension = column.getPrecision(); - final int bytesPerPlane = (dimension + 7) / 8; + final List parameters = column.getParameters(); + final int stride = parameters.size() > 2 ? Integer.parseInt(parameters.get(2).trim()) : dimension; + if (stride <= 0 || dimension % stride != 0) { + throw new ClientException("QBit stride " + stride + " is not a positive divisor of the dimension " + + dimension + " in column '" + column.getColumnName() + "'"); + } + final int groups = dimension / stride; + final int bytesPerPlane = (stride + 7) / 8; final int totalBits = bytesPerPlane * 8; // Planes are column-major: each holds nRows * bytesPerPlane bytes (docs/qbit-encoding.md). @@ -720,15 +733,16 @@ public List readQBitNative(ClickHouseColumn column, int nRows) throws IO + Integer.MAX_VALUE + ")"); } final int planeBytes = (int) planeBytesLong; - byte[][] planes = new byte[elementBits][]; - for (int p = 0; p < elementBits; p++) { + // Group-major: the elementBits planes of stride group 0, then those of group 1, and so on. + byte[][] planes = new byte[groups * elementBits][]; + for (int p = 0; p < planes.length; p++) { planes[p] = readNBytes(input, planeBytes); } - // Per-element byte offset and bit mask within a plane row (docs/qbit-encoding.md). - int[] elementByte = new int[dimension]; - int[] elementMask = new int[dimension]; - for (int j = 0; j < dimension; j++) { + // Per-element byte offset and bit mask within a plane row of a stride group (docs/qbit-encoding.md). + int[] elementByte = new int[stride]; + int[] elementMask = new int[stride]; + for (int j = 0; j < stride; j++) { int bitIndex = (totalBits - 1) - (j ^ 7); elementByte[j] = bitIndex >> 3; elementMask[j] = 1 << (bitIndex & 7); @@ -738,23 +752,32 @@ public List readQBitNative(ClickHouseColumn column, int nRows) throws IO for (int r = 0; r < nRows; r++) { final int rowBase = r * bytesPerPlane; long[] bits = new long[dimension]; - for (int p = 0; p < elementBits; p++) { - final byte[] plane = planes[p]; - final long planeBit = 1L << (elementBits - 1 - p); - for (int j = 0; j < dimension; j++) { - if ((plane[rowBase + elementByte[j]] & elementMask[j]) != 0) { - bits[j] |= planeBit; + for (int g = 0; g < groups; g++) { + final int firstElement = g * stride; + for (int p = 0; p < elementBits; p++) { + final byte[] plane = planes[g * elementBits + p]; + final long planeBit = 1L << (elementBits - 1 - p); + for (int j = 0; j < stride; j++) { + if ((plane[rowBase + elementByte[j]] & elementMask[j]) != 0) { + bits[firstElement + j] |= planeBit; + } } } } ArrayValue vector; - if (isDouble) { + if (elementType == ClickHouseDataType.Float64) { vector = new ArrayValue(double.class, dimension); for (int j = 0; j < dimension; j++) { vector.set(j, Double.longBitsToDouble(bits[j])); } + } else if (elementType == ClickHouseDataType.Int8) { + vector = new ArrayValue(byte.class, dimension); + for (int j = 0; j < dimension; j++) { + vector.set(j, (byte) bits[j]); + } } else { + final boolean isBFloat16 = elementType == ClickHouseDataType.BFloat16; vector = new ArrayValue(float.class, dimension); for (int j = 0; j < dimension; j++) { // BFloat16 carries the high 16 bits of a Float32; widen it the same way readBFloat16LE does. diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java index 968cfc89d..2ccbc76d9 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java @@ -32,9 +32,9 @@ /** * Tests for {@link NativeFormatReader}. *

- * The QBit tests are driven by Native-format blocks captured from ClickHouse 26.5.1 and by minimal hand-built - * block headers. These run without a live server, so the block-level routing (decode a plain float QBit, reject - * every other shape) stays covered on the coverage build, whose older server skips the QBit integration tests. + * The QBit tests are driven by Native-format blocks captured from ClickHouse 26.5.1 and 26.10, and by minimal + * hand-built block headers. These run without a live server, so the block-level routing (decode the supported + * QBit shapes, reject the other shapes) stays covered on servers that skip the QBit integration tests. */ public class NativeFormatReaderTest extends BaseIntegrationTest { @@ -248,15 +248,63 @@ public void testDecodesPlainQBitColumn(String label, String blockHex, boolean is Assert.assertNull(reader.next(), label); } - // QBit shapes the Native reader cannot decode: nested inside a container, strided, wrapped in Nullable, - // or a non-float element type. Each must be rejected up front instead of misreading the block. + // Three-row Native blocks captured from ClickHouse 26.10: a Nullable QBit column (null map, then a placeholder + // vector for the null row), and a QBit column as the element of a one-level Array (offsets, then the QBit column + // of all elements), with a non-empty, an empty and a one-element row. + @DataProvider(name = "decodableQBitContainerBlocks") + public static Object[][] decodableQBitContainerBlocks() { + return new Object[][] { + {"Nullable(QBit(Float32, 3))", + "0103037665631a4e756c6c61626c65285142697428466c6f617433322c203329290001000202" + + "02060707010000010000010000010000010000010000010000040505040404000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000", + Arrays.asList(Arrays.asList(1f, -2f, 3.5f), null, Arrays.asList(3f, -2f, 3.5f))}, + {"Array(QBit(Float32, 3))", + "010303766563174172726179285142697428466c6f617433322c203329290200000000000000" + + "02000000000000000300000000000000000000060707010000010000010000010000010000010006" + + "01070104040100020100000400000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000", + Arrays.asList( + Arrays.asList(Arrays.asList(1f, 2f, 3f), Arrays.asList(4f, 5f, 6f)), + Collections.emptyList(), + Collections.singletonList(Arrays.asList(7f, 8f, 9f)))}, + {"Array(Nullable(QBit(Float32, 3)))", + "010303766563214172726179284e756c6c61626c65285142697428466c6f617433322c203329" + + "29290200000000000000020000000000000003000000000000000001010000000600000100000100" + + "00010000010000010000010000010000040000000000000000000000000000000000000000000000" + + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + + "0000000000", + Arrays.asList( + Arrays.asList(Arrays.asList(1f, 2f, 3f), null), + Collections.emptyList(), + Collections.singletonList(null))}, + }; + } + + @Test(dataProvider = "decodableQBitContainerBlocks") + public void testDecodesQBitInNullableAndArray(String label, String blockHex, List expectedRows) { + NativeFormatReader reader = nativeReader(fromHex(blockHex)); + + for (int r = 0; r < expectedRows.size(); r++) { + Assert.assertNotNull(reader.next(), label + " row " + r); + Assert.assertEquals(reader.getList("vec"), expectedRows.get(r), label + " row " + r); + } + Assert.assertNull(reader.next(), label); + } + + // QBit shapes the Native reader cannot decode: inside a Tuple, Map or multi-level Array, in LowCardinality, + // or with an element type other than Int8, BFloat16, Float32 and Float64. Each must be rejected up front + // instead of misreading the block. @DataProvider(name = "undecodableQBitTypes") public static Object[][] undecodableQBitTypes() { return new Object[][] { {"m", "Map(String, QBit(Float32, 3))"}, - {"vec", "QBit(Float32, 4, 2)"}, - {"vec", "Nullable(QBit(Float32, 3))"}, - {"vec", "QBit(Int8, 3)"}, + {"t", "Tuple(Int32, QBit(Float32, 3))"}, + {"a", "Array(Array(QBit(Float32, 3)))"}, + {"vec", "LowCardinality(QBit(Float32, 3))"}, + {"vec", "QBit(Int16, 3)"}, + {"a", "Array(QBit(Int16, 3))"}, }; } diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReaderTests.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReaderTests.java index 17cf052ad..603baaa3b 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReaderTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/BinaryStreamReaderTests.java @@ -365,6 +365,54 @@ public void testReadQBitNativeDecodesGoldenBytes(String label, String columnType } } + // Int8 and strided QBit(element_type, dimension, stride) column payloads captured from ClickHouse 26.10. A strided + // column has the bit planes of each stride group in turn, each plane ceil(stride / 8) bytes per row. + @DataProvider(name = "qbitNativeInt8AndStridedGoldenBytes") + public static Object[][] qbitNativeInt8AndStridedGoldenBytes() { + float[] f32Row0 = new float[16]; + float[] f32Row1 = new float[16]; + byte[] int8Strided = new byte[16]; + for (int j = 0; j < 16; j++) { + f32Row0[j] = j; + f32Row1[j] = j + 100; + int8Strided[j] = (byte) (j - 8); + } + return new Object[][] { + {"Int8 dim 5 (8 bit planes)", "QBit(Int8, 5)", 1, "0a06060606060605", + new Object[] {new byte[] {1, -2, 127, -128, 0}}}, + {"Int8 dim 16 stride 8 (2 groups)", "QBit(Int8, 16, 8)", 1, "fffffffffff0ccaa0000000000f0ccaa", + new Object[] {int8Strided}}, + {"Float32 dim 16 stride 8, two rows (2 groups, column-major slicing)", "QBit(Float32, 16, 8)", 2, + "0000fcff020002000200020002ff0200f2ffc8ffa00000f0000f00cc00aa0000000000000000" + + "00000000000000000000000000000000000000000000000000000000ffff000000000000000000ff" + + "ff0000fff0ffccf0aa0f000f00cc00aa000000000000000000000000000000000000000000000000" + + "00000000000000000000", + new Object[] {f32Row0, f32Row1}}, + }; + } + + @Test(dataProvider = "qbitNativeInt8AndStridedGoldenBytes") + public void testReadQBitNativeDecodesInt8AndStridedGoldenBytes(String label, String columnType, int nRows, + String columnDataHex, Object[] expectedRows) throws Exception { + List rows = qbitReader(fromHex(columnDataHex)) + .readQBitNative(ClickHouseColumn.of("vec", columnType), nRows); + + Assert.assertEquals(rows.size(), nRows, label); + for (int r = 0; r < nRows; r++) { + Assert.assertEquals(((BinaryStreamReader.ArrayValue) rows.get(r)).getArray(), expectedRows[r], + label + " row " + r); + } + } + + @Test + public void testReadQBitNativeRejectsStrideThatDoesNotDivideDimension() { + ClickHouseColumn column = ClickHouseColumn.of("vec", "QBit(Float32, 12, 8)"); + ClientException ex = Assert.expectThrows(ClientException.class, + () -> qbitReader(new byte[0]).readQBitNative(column, 1)); + Assert.assertTrue(ex.getMessage().contains("stride"), + "Expected a stride rejection message, got: " + ex.getMessage()); + } + @Test public void testReadQBitNativeDecodesSpecialFloatValues() throws Exception { // NaN, +Inf, -Inf and -0.0 must survive the bit-plane transpose bit-for-bit. @@ -382,9 +430,10 @@ public void testReadQBitNativeDecodesSpecialFloatValues() throws Exception { @Test public void testReadQBitNativeRejectsUnsupportedElementType() { - // readQBitNative reconstructs only float element types; a non-float element is rejected by its own - // guard (the Native reader also filters these earlier), which fires before any read. - ClickHouseColumn column = ClickHouseColumn.of("vec", "QBit(Int8, 3)"); + // readQBitNative reconstructs only the Int8, BFloat16, Float32 and Float64 element types; another + // element type is rejected by its own guard (the Native reader also filters these earlier), which + // fires before any read. + ClickHouseColumn column = ClickHouseColumn.of("vec", "QBit(Int16, 3)"); ClientException ex = Assert.expectThrows(ClientException.class, () -> qbitReader(new byte[0]).readQBitNative(column, 1)); Assert.assertTrue(ex.getMessage().contains("Float32"), diff --git a/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java b/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java index 4f68d2cb5..c0e5fc1a6 100644 --- a/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java @@ -130,6 +130,8 @@ private void writeReadVerify(String table, String tableDef, Class dtoClas // QBit was introduced in ClickHouse 25.10. private static final String QBIT_UNSUPPORTED_VERSIONS = "(,25.9]"; + // The Int8 element type and the stride parameter of QBit were introduced in ClickHouse 26.7. + private static final String QBIT_INT8_STRIDE_UNSUPPORTED_VERSIONS = "(,26.6]"; @Data @AllArgsConstructor @@ -344,6 +346,96 @@ private void assertMultiRowQBit(String sql, List expectedPerRow, boolean } } + @DataProvider(name = "qbitNativeShapes") + public static Object[][] qbitNativeShapes() { + // type, value of row `number` (0, 1, 2), expected value of each row, server versions without the type. + List int8Rows = new ArrayList<>(); + List f32StridedRows = new ArrayList<>(); + List f64StridedRows = new ArrayList<>(); + for (int r = 0; r < 3; r++) { + int8Rows.add(Arrays.asList((byte) r, (byte) -2, (byte) 127, (byte) -128, (byte) 0)); + List f32 = new ArrayList<>(); + for (int j = 0; j < 16; j++) { + f32.add(j + r * 100f); + } + f32StridedRows.add(f32); + List f64 = new ArrayList<>(); + for (int j = 0; j < 24; j++) { + f64.add(-j - r * 0.5d); + } + f64StridedRows.add(f64); + } + return new Object[][] { + {"QBit(Int8, 5)", "[toInt8(number), -2, 127, -128, 0]", int8Rows, QBIT_INT8_STRIDE_UNSUPPORTED_VERSIONS}, + {"QBit(Float32, 16, 8)", "arrayMap(x -> toFloat32(x + number * 100), range(16))", f32StridedRows, + QBIT_INT8_STRIDE_UNSUPPORTED_VERSIONS}, + {"QBit(Float64, 24, 8)", "arrayMap(x -> -x - number * 0.5, range(24))", f64StridedRows, + QBIT_INT8_STRIDE_UNSUPPORTED_VERSIONS}, + {"Nullable(QBit(BFloat16, 3))", "if(number = 1, NULL, CAST([number + 1, -2, 0.5] AS QBit(BFloat16, 3)))", + Arrays.asList(Arrays.asList(1f, -2f, 0.5f), null, Arrays.asList(3f, -2f, 0.5f)), + QBIT_UNSUPPORTED_VERSIONS}, + {"Array(QBit(Float32, 3))", + "arrayMap(i -> CAST([i + 1, -(i + 1), (i + 1) * 0.5] AS QBit(Float32, 3)), " + + "range(multiIf(number = 0, 2, number = 1, 0, 1)))", + Arrays.asList( + Arrays.asList(Arrays.asList(1f, -1f, 0.5f), Arrays.asList(2f, -2f, 1f)), + Collections.emptyList(), + Collections.singletonList(Arrays.asList(1f, -1f, 0.5f))), + QBIT_UNSUPPORTED_VERSIONS}, + {"Array(Nullable(QBit(Int8, 3)))", + "multiIf(number = 0, [CAST([1, -2, 3] AS Nullable(QBit(Int8, 3))), NULL], " + + "number = 1, CAST([] AS Array(Nullable(QBit(Int8, 3)))), " + + "[CAST(NULL AS Nullable(QBit(Int8, 3)))])", + Arrays.asList( + Arrays.asList(Arrays.asList((byte) 1, (byte) -2, (byte) 3), null), + Collections.emptyList(), + Collections.singletonList(null)), + QBIT_INT8_STRIDE_UNSUPPORTED_VERSIONS}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "qbitNativeShapes") + public void testQBitNativeFormatShapes(String type, String valueSql, List expectedRows, + String unsupportedVersions) throws Exception { + if (isVersionMatch(unsupportedVersions)) { + throw new SkipException(type + " is not supported by this ClickHouse version"); + } + + // The rows go into a table, so that the server converts the values to the column type and the + // Native block holds the real QBit layout. The QBit column is between two fixed-width columns. + String table = "test_qbit_native_shapes"; + CommandSettings ddl = (CommandSettings) new CommandSettings() + .serverSetting("allow_experimental_qbit_type", "1"); + client.execute("DROP TABLE IF EXISTS " + table).get(); + client.execute(tableDefinition(table, "rowId Int64", "vec " + type, "tail Int32"), ddl).get(); + client.execute("INSERT INTO " + table + " SELECT number, " + valueSql + ", 42 FROM numbers(3)", ddl).get(); + + Map> valueClasses = new HashMap<>(); + for (ClickHouseFormat format : new ClickHouseFormat[] { + ClickHouseFormat.Native, ClickHouseFormat.RowBinaryWithNamesAndTypes}) { + List classes = new ArrayList<>(); + QuerySettings settings = new QuerySettings().setFormat(format); + try (QueryResponse response = client.query("SELECT * FROM " + table + " ORDER BY rowId", settings).get()) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + for (int r = 0; r < expectedRows.size(); r++) { + Assert.assertNotNull(reader.next(), format + " row " + r); + Assert.assertEquals(reader.getLong("rowId"), (long) r, format + " row " + r); + Assert.assertEquals(reader.getList("vec"), expectedRows.get(r), format + " row " + r); + Assert.assertEquals(reader.getInteger("tail"), 42, format + " row " + r); + Object value = reader.readValue("vec"); + classes.add(value instanceof BinaryStreamReader.ArrayValue + ? ((BinaryStreamReader.ArrayValue) value).getArray().getClass().getName() + : String.valueOf(value)); + } + Assert.assertFalse(reader.hasNext(), format.toString()); + } + valueClasses.put(format, classes); + } + // The Native read gives each row the same Java array class as the RowBinary read. + Assert.assertEquals(valueClasses.get(ClickHouseFormat.Native), + valueClasses.get(ClickHouseFormat.RowBinaryWithNamesAndTypes)); + } + @Test(groups = {"integration"}) public void testQBitInDynamicColumn() throws Exception { if (isVersionMatch(QBIT_UNSUPPORTED_VERSIONS)) { diff --git a/docs/features.md b/docs/features.md index b4d90370b..6a65d229c 100644 --- a/docs/features.md +++ b/docs/features.md @@ -23,7 +23,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t - JSONEachRow text reader: Can stream `JSONEachRow` responses through a caller-supplied `JsonParser`, with Jackson and Gson parser factory implementations available as optional classpath dependencies, and infers a best-effort schema from the first row. - Data type conversion: Maps ClickHouse types to Java values for binary reads, POJO binding, and SQL parameter formatting, including date/time handling. - BFloat16 type support: For ClickHouse `24.11+`, reads and writes the `BFloat16` type through generic records, binary readers, POJO binding, and `Nullable`/`Dynamic`/`Variant` wrappers. `BFloat16` maps to the Java `float` type: a read widens the stored 16-bit value losslessly, while a write keeps the high 16 bits of the `float`. In `jdbc-v2`, `BFloat16` maps to `java.sql.Types.FLOAT` / `java.lang.Float` and is read and written through the standard `getFloat`/`setFloat` and `getObject` accessors. -- QBit type support: For ClickHouse `25.10+` (requires the `allow_experimental_qbit_type` server setting to create a column), reads and writes the experimental `QBit(element_type, dimension[, stride])` vector type. The type-name parser accepts two or three parameters (the optional third parameter is the stride) and recognizes the documented element types `Int8`, `BFloat16`, `Float32`, and `Float64`; an element type outside that documented set is parsed with a warning rather than rejected, so a newer server-side element type does not require a client change to parse. On the wire a `QBit` value is encoded exactly like `Array(element_type)` (a length-prefixed list of elements), so the client reads and writes it as a Java array of the element type — `float[]` for `BFloat16`/`Float32`, `double[]` for `Float64` — through generic records, binary readers, and POJO binding, using a dedicated `QBit` read/serialize path (the shared `Array`-like wire encoding is an implementation detail, not a type equivalence). A `QBit` held inside a `Dynamic`/`Variant`/`JSON` column is decoded on read: its binary type encoding (`0x36 `) is read back to the concrete `QBit(...)` type. The client never infers a `QBit` from a Java value, so writing a `QBit` into a `Dynamic` column is not supported and is rejected with a clear `ClientException` rather than emitting an incomplete tag that would desynchronize the stream. This `Array`-like encoding is what the server uses over `RowBinary` formats; the `Native` format instead transmits `QBit` using its internal bit-plane-transposed `Tuple(FixedString(ceil(dimension/8)))` layout (`element_size` bit planes, most-significant plane first, each plane an `element_size`-independent `FixedString` serialized column-major). A plain top-level `QBit(element_type, dimension)` column whose element type is `Float32`, `Float64`, or `BFloat16` (the element types ClickHouse supports for `QBit`) is decoded from that layout on read: the client reverses the bit-plane transposition (the exact inverse of the server's `SerializationQBit` transpose) to reconstruct the same `float[]`/`double[]` vector it produces over `RowBinary`, so a `QBit` column round-trips identically through either format. A `QBit` that is strided (`QBit(element_type, dimension, stride)`), wrapped in `Nullable`/`LowCardinality`, nested inside another type (e.g. `Array`/`Tuple`/`Map(String, QBit(...))`), or carrying any other element type is not decoded over `Native` and is rejected with a clear `ClientException` (use a `RowBinary` format such as `RowBinaryWithNamesAndTypes` instead). See [qbit-encoding.md](qbit-encoding.md) for the RowBinary and Native wire layouts. +- QBit type support: For ClickHouse `25.10+` (requires the `allow_experimental_qbit_type` server setting to create a column), reads and writes the experimental `QBit(element_type, dimension[, stride])` vector type. The type-name parser accepts two or three parameters (the optional third parameter is the stride) and recognizes the documented element types `Int8`, `BFloat16`, `Float32`, and `Float64`; an element type outside that documented set is parsed with a warning rather than rejected, so a newer server-side element type does not require a client change to parse. On the wire a `QBit` value is encoded exactly like `Array(element_type)` (a length-prefixed list of elements), so the client reads and writes it as a Java array of the element type — `byte[]` for `Int8`, `float[]` for `BFloat16`/`Float32`, `double[]` for `Float64` — through generic records, binary readers, and POJO binding, using a dedicated `QBit` read/serialize path (the shared `Array`-like wire encoding is an implementation detail, not a type equivalence). A `QBit` held inside a `Dynamic`/`Variant`/`JSON` column is decoded on read: its binary type encoding (`0x36 `) is read back to the concrete `QBit(...)` type. The client never infers a `QBit` from a Java value, so writing a `QBit` into a `Dynamic` column is not supported and is rejected with a clear `ClientException` rather than emitting an incomplete tag that would desynchronize the stream. This `Array`-like encoding is what the server uses over `RowBinary` formats; the `Native` format instead transmits `QBit` using its internal bit-plane-transposed `Tuple(FixedString(...))` layout (`element_size` bit planes, most-significant plane first, each plane an `element_size`-independent `FixedString` serialized column-major). A `QBit(element_type, dimension[, stride])` column whose element type is `Int8`, `BFloat16`, `Float32`, or `Float64` is decoded from that layout on read, also when it is strided, wrapped in `Nullable`, or the element of a one-level `Array` (`Array(QBit(...))`, `Array(Nullable(QBit(...)))`): the client reverses the bit-plane transposition (the exact inverse of the server's `SerializationQBit` transpose) to reconstruct the same `byte[]`/`float[]`/`double[]` vector (and, for an `Array` row, the same item class) that it produces over `RowBinary`, so a `QBit` column round-trips identically through either format. A strided `QBit(element_type, dimension, stride)` has `element_size` bit planes for each of its `dimension / stride` stride groups. The `Int8` element type and the stride need ClickHouse `26.7+`. A `QBit` in `LowCardinality`, inside a `Tuple`, `Map`, `Variant`, multi-level `Array`, or another container, or carrying any other element type is not decoded over `Native` and is rejected with a clear `ClientException` (use a `RowBinary` format such as `RowBinaryWithNamesAndTypes` instead). See [qbit-encoding.md](qbit-encoding.md) for the RowBinary and Native wire layouts. - Geometry type support: For ClickHouse `25.11+`, where `Geometry` changed from a string alias to `Variant(Point, Ring, LineString, MultiLineString, Polygon, MultiPolygon)`, the client reads and writes `Geometry` values through generic records, binary readers, POJO binding, and SQL parameter formatting, using Java array dimensionality to represent the geometry shape. ClickHouse `26.8+` adds `MultiPoint` to that variant, appended after the existing six so their discriminators are unchanged; a `MultiPoint` value read from a `Geometry` column is returned as `double[][]`, the same shape as `Ring` and `LineString`. - MultiPoint type support: For ClickHouse `26.8+`, reads and writes the `MultiPoint` geo type, which is transmitted exactly like `Ring` and `LineString` (`Array(Point)`) and is represented as `double[][]` through generic records, binary readers, POJO binding, and SQL parameter formatting. A `MultiPoint` held in a `Dynamic` column is decoded on read; it cannot be written into a `Dynamic` column, because the client infers the type from the Java value and `double[][]` resolves to `Ring`. - Nested type support: Un-flattened `Nested(f1 T1, ..., fN TN)` columns (tables created with `flatten_nested = 0`) can be written through the insert path (`Client#insert`) using `RowBinaryFormatWriter#setValue`, and are read back through the binary readers and generic records. The column is serialized the same way it is read — identically to `Array(Tuple(T1, ..., TN))`, a var-uint row count followed by one tuple per nested row — so the value supplied for the column is a `List` (or array) of tuples, one tuple per nested row, each carrying the N field values in declaration order. diff --git a/docs/qbit-encoding.md b/docs/qbit-encoding.md index 501a4c82c..aff94a175 100644 --- a/docs/qbit-encoding.md +++ b/docs/qbit-encoding.md @@ -1,6 +1,7 @@ # QBit encoding: RowBinary vs Native -`QBit(element_type, dimension)` is a fixed-length vector type (ClickHouse `25.10+`). The same +`QBit(element_type, dimension)` is a fixed-length vector type (ClickHouse `25.10+`; the `Int8` element +type and the `stride` parameter need ClickHouse `26.7+`). The same logical value is put on the wire two different ways depending on the output format, which is why `client-v2` has a dedicated read path for each. This document describes both encodings and the "problem" the Native path has to solve. @@ -20,19 +21,31 @@ detail of the wire format, not a type equivalence.) ## Native — the bit-plane transposed layout Over the `Native` format the server does **not** send the elements contiguously. It stores a `QBit` -column as a nested `Tuple(FixedString(ceil(N/8)))` with one field per **bit plane**, and serializes -that tuple **column-major**. Concretely, for a block of `nRows` rows: - -- Let `element_size` be the element bit width: `16` (`BFloat16`), `32` (`Float32`), `64` (`Float64`). -- Let `bytesPerPlane = ceil(N / 8)` and `totalBits = bytesPerPlane * 8`. -- There are `element_size` **bit planes**, most-significant plane first: plane `p` (0-based) carries - element bit `element_size - 1 - p` of every element. -- Each plane is a `FixedString(bytesPerPlane)` per row, and the tuple is column-major, so plane `p` +column as a nested `Tuple(FixedString(...))` with one field per **bit plane**, and serializes that +tuple **column-major**. Concretely, for a block of `nRows` rows of `QBit(E, N, S)` (the stride `S` is +`N` when the type has no third parameter): + +- Let `element_size` be the element bit width: `8` (`Int8`), `16` (`BFloat16`), `32` (`Float32`), + `64` (`Float64`). +- The `N` elements are split into `N / S` **stride groups** of `S` consecutive elements. A QBit + without a stride has one group. +- Let `bytesPerPlane = ceil(S / 8)` and `totalBits = bytesPerPlane * 8`. +- Each group has `element_size` **bit planes**, most-significant plane first: plane `p` (0-based) of a + group carries element bit `element_size - 1 - p` of every element in that group. The planes are + group-major: the planes of group 0, then the planes of group 1, and so on. +- Each plane is a `FixedString(bytesPerPlane)` per row, and the tuple is column-major, so a plane occupies `nRows * bytesPerPlane` contiguous bytes; row `r`'s slice for a plane starts at `r * bytesPerPlane`. -- Within a plane row, element `j`'s bit is stored MSB-first with a `j ^ 7` flip inside each byte: - its bit index is `bitIndex = (totalBits - 1) - (j ^ 7)`, i.e. byte `bitIndex >> 3`, bit - `bitIndex & 7`. +- Within a plane row, the bit of element `j` of the group (0-based in the group) is stored MSB-first + with a `j ^ 7` flip inside each byte: its bit index is `bitIndex = (totalBits - 1) - (j ^ 7)`, i.e. + byte `bitIndex >> 3`, bit `bitIndex & 7`. + +Containers use the usual Native layout around this column: + +- `Nullable(QBit(...))`: a null map of `nRows` bytes, then the QBit column of all `nRows` rows. A null + row also has a vector in the QBit column; its value is not specified, and the reader discards it. +- `Array(QBit(...))`: `nRows` cumulative `UInt64` offsets, then the QBit column of all elements of the + block (`Array(Nullable(QBit(...)))`: the null map of all elements comes before it). ### Why the client can't reuse the Array path @@ -43,29 +56,37 @@ Native reader must either fully reconstruct the vector or fail loudly. ### Decoding (the inverse transpose) -`BinaryStreamReader#readQBitNative` reverses the transpose, producing the **same** `float[]`/`double[]` -`readQBit` produces over RowBinary (so a `QBit` round-trips identically through either format): +`BinaryStreamReader#readQBitNative` reverses the transpose, producing the **same** `byte[]`/`float[]`/ +`double[]` `readQBit` produces over RowBinary (so a `QBit` round-trips identically through either +format): -1. Read the `element_size` planes, each `nRows * bytesPerPlane` bytes. -2. Precompute, per element `j`, its byte offset `bitIndex >> 3` and bit mask `1 << (bitIndex & 7)` - within a plane row (constant across planes and rows). -3. For each row `r` and plane `p`, for each element `j`: if the masked bit is set, OR bit - `element_size - 1 - p` into element `j`'s accumulated bits. -4. Reinterpret each element's bits as the value: `Double.longBitsToDouble` for `Float64`, - `Float.intBitsToFloat` for `Float32`, and for `BFloat16` widen the 16 stored bits to a `float` by - shifting them into the high half (`bits << 16`), matching `readBFloat16LE`. +1. Read the `element_size * (N / S)` planes, each `nRows * bytesPerPlane` bytes. +2. Precompute, per group element `j`, its byte offset `bitIndex >> 3` and bit mask + `1 << (bitIndex & 7)` within a plane row (constant across groups, planes and rows). +3. For each row `r`, group `g` and plane `p`, for each group element `j`: if the masked bit is set, + OR bit `element_size - 1 - p` into the accumulated bits of element `g * S + j`. +4. Reinterpret each element's bits as the value: the low 8 bits as a `byte` for `Int8`, + `Double.longBitsToDouble` for `Float64`, `Float.intBitsToFloat` for `Float32`, and for `BFloat16` + widen the 16 stored bits to a `float` by shifting them into the high half (`bits << 16`), matching + `readBFloat16LE`. This is the exact inverse of the server's `SerializationQBit::transposeBits`. ## What client-v2 decodes over Native -`client-v2` decodes a **plain, top-level** `QBit(Float32|Float64|BFloat16, dimension)` column from the -Native format (`NativeFormatReader#isNativeDecodableQBit` selects it). Every other shape is **rejected -up front** with a clear `ClientException` (rather than misread) — read it through a `RowBinary` format -instead: +`client-v2` decodes these `QBit` columns from the Native format (`NativeFormatReader#isNativeDecodableQBit` +selects them): + +- `QBit(E, N)` and strided `QBit(E, N, S)`, where `E` is `Int8`, `BFloat16`, `Float32` or `Float64`; +- such a `QBit` in `Nullable`; +- such a `QBit` (or `Nullable` `QBit`) as the element of a one-level `Array`. Each row has the same + item class as the `RowBinary` read of the array. + +Every other shape is **rejected up front** with a clear `ClientException` (rather than misread). Read +it through a `RowBinary` format instead: -- **strided** `QBit(element_type, dimension, stride)` — its Native layout has - `element_size * (dimension / stride)` planes, which this decoder does not reconstruct; -- `QBit` wrapped in **`Nullable`** / **`LowCardinality`**; -- `QBit` **nested** inside another type (e.g. `Array`/`Tuple`/`Map(String, QBit(...))`); -- a `QBit` with any **non-float element type**. +- a `QBit` in `LowCardinality` (the server does not create this type); +- a `QBit` inside a `Tuple`, `Map`, `Variant`, multi-level `Array` or another container. The Native + reader does not decode these containers column-major + ([#3156](https://github.com/ClickHouse/clickhouse-java/issues/3156)); +- a `QBit` with another element type. diff --git a/history/latest/2980.md b/history/latest/2980.md new file mode 100644 index 000000000..7f0bdee0a --- /dev/null +++ b/history/latest/2980.md @@ -0,0 +1,7 @@ +## New Features + +- **[client-v2]** The `Native` format reader now decodes `QBit(Int8, ...)`, strided `QBit(element_type, dimension, stride)`, + `Nullable(QBit(...))`, `Array(QBit(...))` and `Array(Nullable(QBit(...)))` columns to the same values as the + `RowBinary` readers. Before, it rejected these columns with a `ClientException`. A `QBit` inside a `Tuple`, `Map`, + `Variant` or multi-level `Array` is still rejected. + (https://github.com/ClickHouse/clickhouse-java/issues/2980)