Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -216,17 +216,19 @@ private void readBlock() throws IOException {
List<Object> 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
Expand Down Expand Up @@ -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<Object> 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<Object> 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<Object> 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<Object> elements = readQBitColumn(elementColumn, nRows == 0 ? 0 : Math.toIntExact(offsets[nRows - 1]));

List<Object> 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
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -687,28 +687,41 @@ private <T> 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<Object> 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<String> 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).
Expand All @@ -720,15 +733,16 @@ public List<Object> 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);
Expand All @@ -738,23 +752,32 @@ public List<Object> 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.
Expand Down
Loading
Loading