|
| 1 | +package io.github.dfa1.vortex.reader.array; |
| 2 | + |
| 3 | +import io.github.dfa1.vortex.core.error.VortexException; |
| 4 | +import io.github.dfa1.vortex.core.io.VortexFormat; |
| 5 | +import io.github.dfa1.vortex.core.model.DType; |
| 6 | +import io.github.dfa1.vortex.core.model.PType; |
| 7 | + |
| 8 | +import java.lang.foreign.MemorySegment; |
| 9 | +import java.lang.foreign.SegmentAllocator; |
| 10 | +import java.lang.foreign.ValueLayout; |
| 11 | +import java.util.ArrayList; |
| 12 | +import java.util.List; |
| 13 | + |
| 14 | +/// Stitches the per-chunk arrays of one logical column into a single view, dispatching on the |
| 15 | +/// column's [DType]. Each family gets its zero-copy composite shape (ADR 0012): primitive and |
| 16 | +/// boolean chunks fold into the `ChunkedXxxArray` records, variable-length chunks into |
| 17 | +/// [VarBinArray.ChunkedMode], and list chunks into a stitched [ListArray] whose bulk element data |
| 18 | +/// stays zero-copy (the child element arrays are themselves combined recursively) while only the |
| 19 | +/// small outer offsets table is rebuilt so per-chunk offsets — which each reset to zero — become one |
| 20 | +/// cumulative table. |
| 21 | +/// |
| 22 | +/// Extracted from `ChunkedLayoutDecoder` so the same dispatch drives both the top-level chunked |
| 23 | +/// column and the recursive combine of a chunked list's elements. Every unsupported dtype fails with |
| 24 | +/// a [VortexException] rather than a raw `ClassCastException` — the reader parses untrusted input and |
| 25 | +/// must never leak a JDK runtime exception (issue #268). |
| 26 | +public final class ChunkedArrayCombiner { |
| 27 | + |
| 28 | + private ChunkedArrayCombiner() { |
| 29 | + } |
| 30 | + |
| 31 | + /// Combines the per-chunk arrays of one column into a single logical array, choosing the shape |
| 32 | + /// from `dtype`. Masked chunks keep their per-chunk validity: it is concatenated into one |
| 33 | + /// row-level bitmap and the result re-wrapped in a [MaskedArray], so a nullable column that |
| 34 | + /// spans more than one chunk retains its nulls. |
| 35 | + /// |
| 36 | + /// @param dtype the column's logical type |
| 37 | + /// @param totalRows the total logical row count across all chunks |
| 38 | + /// @param chunks the decoded per-chunk arrays, in row order (non-empty) |
| 39 | + /// @param arena allocator for the combined validity bitmap and, for lists, the rebuilt offsets |
| 40 | + /// @return the combined [Array], masked when any chunk contributes nulls |
| 41 | + /// @throws VortexException on an empty chunk list or a dtype with no chunked shape |
| 42 | + public static Array combine(DType dtype, long totalRows, List<Array> chunks, |
| 43 | + SegmentAllocator arena) { |
| 44 | + if (chunks.isEmpty()) { |
| 45 | + throw new VortexException("chunked combine: empty chunk list"); |
| 46 | + } |
| 47 | + Array data = switch (dtype) { |
| 48 | + case DType.Bool ignored -> ChunkedBoolArray.of(dtype, totalRows, chunks); |
| 49 | + case DType.Utf8 ignored -> VarBinArray.ChunkedMode.of(dtype, totalRows, chunks, arena); |
| 50 | + case DType.Binary ignored -> VarBinArray.ChunkedMode.of(dtype, totalRows, chunks, arena); |
| 51 | + case DType.List list -> combineLists(list, totalRows, chunks, arena); |
| 52 | + case DType.Primitive prim -> combinePrimitive(prim.ptype(), dtype, totalRows, chunks); |
| 53 | + default -> throw new VortexException("unsupported dtype for chunked layout: " + dtype); |
| 54 | + }; |
| 55 | + BoolArray validity = combineChunkValidity(chunks, totalRows, arena); |
| 56 | + return validity != null ? new MaskedArray(data, validity) : data; |
| 57 | + } |
| 58 | + |
| 59 | + private static Array combinePrimitive(PType ptype, DType dtype, long totalRows, |
| 60 | + List<Array> chunks) { |
| 61 | + return switch (ptype) { |
| 62 | + case I64, U64 -> ChunkedLongArray.of(dtype, totalRows, chunks); |
| 63 | + case I32, U32 -> ChunkedIntArray.of(dtype, totalRows, chunks); |
| 64 | + case F64 -> ChunkedDoubleArray.of(dtype, totalRows, chunks); |
| 65 | + case F32 -> ChunkedFloatArray.of(dtype, totalRows, chunks); |
| 66 | + case I16, U16 -> ChunkedShortArray.of(dtype, totalRows, chunks); |
| 67 | + case I8, U8 -> ChunkedByteArray.of(dtype, totalRows, chunks); |
| 68 | + default -> throw new VortexException("unsupported ptype for chunked layout: " + ptype); |
| 69 | + }; |
| 70 | + } |
| 71 | + |
| 72 | + /// Stitches per-chunk [ListArray] chunks into one [ListArray]. The element arrays of every chunk |
| 73 | + /// are combined recursively (staying zero-copy), and one cumulative I64 offsets table of |
| 74 | + /// `totalRows + 1` entries is built in `arena`: each chunk's local offsets are shifted by the |
| 75 | + /// number of elements contributed by earlier chunks, since per-chunk offsets each restart at |
| 76 | + /// zero. |
| 77 | + /// |
| 78 | + /// @param dtype the list's logical type |
| 79 | + /// @param totalRows the total outer-list row count across all chunks |
| 80 | + /// @param chunks the per-chunk list arrays (each a [ListArray], possibly wrapped [MaskedArray]) |
| 81 | + /// @param arena allocator for the rebuilt offsets segment |
| 82 | + /// @return a single [ListArray] over the combined chunks |
| 83 | + private static ListArray combineLists(DType.List dtype, long totalRows, List<Array> chunks, |
| 84 | + SegmentAllocator arena) { |
| 85 | + var listChunks = new ArrayList<ListArray>(chunks.size()); |
| 86 | + for (Array chunk : chunks) { |
| 87 | + Array unwrapped = chunk instanceof MaskedArray m ? m.inner() : chunk; |
| 88 | + if (unwrapped instanceof ListArray la) { |
| 89 | + listChunks.add(la); |
| 90 | + } else { |
| 91 | + throw new VortexException("chunked list: chunk is not a ListArray: " |
| 92 | + + unwrapped.getClass().getSimpleName()); |
| 93 | + } |
| 94 | + } |
| 95 | + long outerRows = 0; |
| 96 | + for (ListArray la : listChunks) { |
| 97 | + outerRows += la.length(); |
| 98 | + } |
| 99 | + if (outerRows != totalRows) { |
| 100 | + throw new VortexException("chunked list: chunk rows sum to " + outerRows |
| 101 | + + ", expected " + totalRows); |
| 102 | + } |
| 103 | + |
| 104 | + var elementChunks = new ArrayList<Array>(listChunks.size()); |
| 105 | + for (ListArray la : listChunks) { |
| 106 | + elementChunks.add(la.elements()); |
| 107 | + } |
| 108 | + Array combinedElements = combine(dtype.elementType(), sumLengths(elementChunks), |
| 109 | + elementChunks, arena); |
| 110 | + |
| 111 | + MemorySegment offsets = arena.allocate((totalRows + 1) * Long.BYTES, Long.BYTES); |
| 112 | + offsets.setAtIndex(VortexFormat.LE_LONG, 0, 0L); |
| 113 | + long outRow = 0; |
| 114 | + long elementBase = 0; |
| 115 | + for (ListArray la : listChunks) { |
| 116 | + long localRows = la.length(); |
| 117 | + Array localOffsets = la.offsets(); |
| 118 | + for (long i = 0; i < localRows; i++) { |
| 119 | + long localEnd = readOffset(localOffsets, i + 1); |
| 120 | + offsets.setAtIndex(VortexFormat.LE_LONG, outRow + i + 1, elementBase + localEnd); |
| 121 | + } |
| 122 | + outRow += localRows; |
| 123 | + elementBase += readOffset(localOffsets, localRows); |
| 124 | + } |
| 125 | + Array offsetsArray = new MaterializedLongArray(DType.I64, totalRows + 1, offsets.asReadOnly()); |
| 126 | + return new ListArray(dtype, totalRows, combinedElements, offsetsArray); |
| 127 | + } |
| 128 | + |
| 129 | + private static long sumLengths(List<Array> arrays) { |
| 130 | + long total = 0; |
| 131 | + for (Array a : arrays) { |
| 132 | + total += a.length(); |
| 133 | + } |
| 134 | + return total; |
| 135 | + } |
| 136 | + |
| 137 | + /// Reads offset `idx` from a list offsets array as a non-negative long, widening whatever integer |
| 138 | + /// ptype the encoder chose (it picks the narrowest that fits the max offset). |
| 139 | + /// |
| 140 | + /// @param offsets the offsets array |
| 141 | + /// @param idx the offset index to read |
| 142 | + /// @return the offset value as a long |
| 143 | + private static long readOffset(Array offsets, long idx) { |
| 144 | + return switch (offsets) { |
| 145 | + case LongArray la -> la.getLong(idx); |
| 146 | + case IntArray ia -> Integer.toUnsignedLong(ia.getInt(idx)); |
| 147 | + case ShortArray sa -> sa.getInt(idx); |
| 148 | + case ByteArray ba -> ba.getInt(idx); |
| 149 | + default -> throw new VortexException("unexpected list offsets type: " |
| 150 | + + offsets.getClass().getSimpleName()); |
| 151 | + }; |
| 152 | + } |
| 153 | + |
| 154 | + /// Concatenates the per-chunk validity of masked chunks into one row-level bitmap, or returns |
| 155 | + /// `null` when no chunk is nullable. Unmasked chunks (and masked chunks with a `null` validity, |
| 156 | + /// which mean all-valid) contribute all-valid rows; an entirely-null [NullArray] chunk (#269) |
| 157 | + /// contributes all-invalid rows. |
| 158 | + /// |
| 159 | + /// @param chunkArrays the decoded per-chunk arrays, in row order |
| 160 | + /// @param totalRows the total logical row count across all chunks |
| 161 | + /// @param arena allocator for the combined bitmap |
| 162 | + /// @return a bit-packed row-validity [BoolArray] of `totalRows` bits, or `null` if all valid |
| 163 | + private static BoolArray combineChunkValidity(List<Array> chunkArrays, long totalRows, |
| 164 | + SegmentAllocator arena) { |
| 165 | + boolean anyNullable = false; |
| 166 | + for (Array chunk : chunkArrays) { |
| 167 | + if ((chunk instanceof MaskedArray m && m.validity() != null) || chunk instanceof NullArray) { |
| 168 | + anyNullable = true; |
| 169 | + break; |
| 170 | + } |
| 171 | + } |
| 172 | + if (!anyNullable) { |
| 173 | + return null; |
| 174 | + } |
| 175 | + MemorySegment bits = arena.allocate((totalRows + 7) >>> 3); |
| 176 | + long row = 0; |
| 177 | + for (Array chunk : chunkArrays) { |
| 178 | + long chunkLen = chunk.length(); |
| 179 | + if (!(chunk instanceof NullArray)) { |
| 180 | + BoolArray validity = chunk instanceof MaskedArray m ? m.validity() : null; |
| 181 | + for (long i = 0; i < chunkLen; i++) { |
| 182 | + if (validity == null || validity.getBoolean(i)) { |
| 183 | + long globalRow = row + i; |
| 184 | + long byteIdx = globalRow >>> 3; |
| 185 | + byte cur = bits.get(ValueLayout.JAVA_BYTE, byteIdx); |
| 186 | + bits.set(ValueLayout.JAVA_BYTE, byteIdx, |
| 187 | + (byte) ((cur & 0xff) | (1 << (globalRow & 7)))); |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + row += chunkLen; |
| 192 | + } |
| 193 | + return new MaterializedBoolArray(DType.BOOL, totalRows, bits.asReadOnly()); |
| 194 | + } |
| 195 | +} |
0 commit comments