@luma.gl/graph 10.0.0-alpha.5 → 10.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +38 -0
  2. package/README.md +7 -1
  3. package/dist/arrow/dggs/dggs-gpu-polygons.cjs +667 -0
  4. package/dist/arrow/dggs/dggs-gpu-polygons.d.ts +75 -0
  5. package/dist/arrow/dggs/dggs-gpu-polygons.d.ts.map +1 -0
  6. package/dist/arrow/dggs/dggs-gpu-polygons.js +651 -0
  7. package/dist/arrow/dggs/dggs-gpu-polygons.js.map +1 -0
  8. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.cjs +411 -0
  9. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.d.ts +31 -0
  10. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.d.ts.map +1 -0
  11. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.js +395 -0
  12. package/dist/arrow/geoarrow/arrow-geoarrow-adapter.js.map +1 -0
  13. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.cjs +304 -0
  14. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.d.ts +32 -0
  15. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.d.ts.map +1 -0
  16. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.js +293 -0
  17. package/dist/arrow/geoarrow/arrow-geoarrow-conversion.js.map +1 -0
  18. package/dist/arrow/geoarrow/arrow-polygon-tessellation.cjs +232 -0
  19. package/dist/arrow/geoarrow/arrow-polygon-tessellation.d.ts +54 -0
  20. package/dist/arrow/geoarrow/arrow-polygon-tessellation.d.ts.map +1 -0
  21. package/dist/arrow/geoarrow/arrow-polygon-tessellation.js +222 -0
  22. package/dist/arrow/geoarrow/arrow-polygon-tessellation.js.map +1 -0
  23. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.cjs +314 -0
  24. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts +42 -0
  25. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.d.ts.map +1 -0
  26. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js +318 -0
  27. package/dist/arrow/gpu/arrow-gpu-analytics-adapters.js.map +1 -0
  28. package/dist/arrow/gpu/arrow-gpu-analytics-readback.cjs +204 -0
  29. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts +30 -0
  30. package/dist/arrow/gpu/arrow-gpu-analytics-readback.d.ts.map +1 -0
  31. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js +195 -0
  32. package/dist/arrow/gpu/arrow-gpu-analytics-readback.js.map +1 -0
  33. package/dist/arrow/gpu/arrow-gpu-table-adapters.cjs +257 -0
  34. package/dist/arrow/gpu/arrow-gpu-table-adapters.d.ts +45 -0
  35. package/dist/arrow/gpu/arrow-gpu-table-adapters.d.ts.map +1 -0
  36. package/dist/arrow/gpu/arrow-gpu-table-adapters.js +257 -0
  37. package/dist/arrow/gpu/arrow-gpu-table-adapters.js.map +1 -0
  38. package/dist/arrow/gpu/arrow-gpu-table-conversion.cjs +230 -0
  39. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts +71 -0
  40. package/dist/arrow/gpu/arrow-gpu-table-conversion.d.ts.map +1 -0
  41. package/dist/arrow/gpu/arrow-gpu-table-conversion.js +215 -0
  42. package/dist/arrow/gpu/arrow-gpu-table-conversion.js.map +1 -0
  43. package/dist/arrow/gpu/arrow-input-schema.cjs +36 -0
  44. package/dist/arrow/gpu/arrow-input-schema.d.ts +41 -0
  45. package/dist/arrow/gpu/arrow-input-schema.d.ts.map +1 -0
  46. package/dist/arrow/gpu/arrow-input-schema.js +17 -0
  47. package/dist/arrow/gpu/arrow-input-schema.js.map +1 -0
  48. package/dist/arrow/index.cjs +90 -0
  49. package/dist/arrow/index.cjs.map +6 -0
  50. package/dist/arrow/index.d.ts +9 -0
  51. package/dist/arrow/index.d.ts.map +1 -0
  52. package/dist/arrow/index.js +12 -0
  53. package/dist/arrow/index.js.map +1 -0
  54. package/dist/arrow/internal.cjs +30 -0
  55. package/dist/arrow/internal.cjs.map +6 -0
  56. package/dist/arrow/internal.d.ts +19 -0
  57. package/dist/arrow/internal.d.ts.map +1 -0
  58. package/dist/arrow/internal.js +7 -0
  59. package/dist/arrow/internal.js.map +1 -0
  60. package/dist/dist.dev.js +283 -12
  61. package/dist/dist.min.js +29 -29
  62. package/dist/geospatial/geospatial-utils.cjs +12 -11
  63. package/dist/geospatial/geospatial-utils.d.ts +1 -1
  64. package/dist/geospatial/geospatial-utils.d.ts.map +1 -1
  65. package/dist/geospatial/geospatial-utils.js +3 -2
  66. package/dist/geospatial/geospatial-utils.js.map +1 -1
  67. package/dist/geospatial/index.cjs.map +2 -2
  68. package/dist/gpu-a5/index.cjs.map +1 -1
  69. package/dist/gpu-dggs/benchmarks.cjs.map +1 -1
  70. package/dist/gpu-dggs/gpu-dggs-cell-projection.cjs +2 -2
  71. package/dist/gpu-dggs/gpu-dggs-cell-projection.js +1 -1
  72. package/dist/gpu-dggs/gpu-dggs-cell-projection.js.map +1 -1
  73. package/dist/gpu-dggs/index.cjs.map +1 -1
  74. package/dist/gpu-h3/index.cjs.map +1 -1
  75. package/dist/gpu-project/benchmarks.cjs.map +2 -2
  76. package/dist/gpu-project/crs.cjs.map +2 -2
  77. package/dist/gpu-project/index.cjs.map +2 -2
  78. package/dist/gpu-project/projection-program.cjs +2 -2
  79. package/dist/gpu-project/projection-program.d.ts +1 -1
  80. package/dist/gpu-project/projection-program.d.ts.map +1 -1
  81. package/dist/gpu-project/projection-program.js +1 -1
  82. package/dist/gpu-project/projection-program.js.map +1 -1
  83. package/dist/gpu-sql/lu-sql.d.ts +1 -1
  84. package/dist/gpu-sql/lu-sql.js +1 -1
  85. package/dist/gpu-tables/engine/gpu-table-shader-bindings.d.ts +1 -1
  86. package/dist/gpu-tables/engine/gpu-table-shader-bindings.d.ts.map +1 -1
  87. package/dist/gpu-vector-search/index.cjs.map +1 -1
  88. package/dist/utils/assemble-compute-kernel.cjs +2 -2
  89. package/dist/utils/assemble-compute-kernel.d.ts +2 -1
  90. package/dist/utils/assemble-compute-kernel.d.ts.map +1 -1
  91. package/dist/utils/assemble-compute-kernel.js +2 -2
  92. package/dist/utils/assemble-compute-kernel.js.map +1 -1
  93. package/package.json +19 -7
  94. package/src/arrow/dggs/dggs-gpu-polygons.ts +820 -0
  95. package/src/arrow/geoarrow/arrow-geoarrow-adapter.ts +519 -0
  96. package/src/arrow/geoarrow/arrow-geoarrow-conversion.ts +415 -0
  97. package/src/arrow/geoarrow/arrow-polygon-tessellation.ts +369 -0
  98. package/src/arrow/gpu/arrow-gpu-analytics-adapters.ts +474 -0
  99. package/src/arrow/gpu/arrow-gpu-analytics-readback.ts +294 -0
  100. package/src/arrow/gpu/arrow-gpu-table-adapters.ts +378 -0
  101. package/src/arrow/gpu/arrow-gpu-table-conversion.ts +324 -0
  102. package/src/arrow/gpu/arrow-input-schema.ts +98 -0
  103. package/src/arrow/index.ts +79 -0
  104. package/src/arrow/internal.ts +23 -0
  105. package/src/geospatial/geospatial-utils.ts +3 -7
  106. package/src/gpu-dggs/gpu-dggs-cell-projection.ts +1 -1
  107. package/src/gpu-project/projection-program.ts +1 -1
  108. package/src/gpu-sql/lu-sql.ts +1 -1
  109. package/src/gpu-tables/engine/gpu-table-shader-bindings.ts +1 -1
  110. package/src/utils/assemble-compute-kernel.ts +3 -7
@@ -0,0 +1,474 @@
1
+ // luma.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {Buffer, type Device} from '@luma.gl/core';
6
+ import {GPUData, GPUVector, type GPUVectorBufferProps} from '@luma.gl/gpgpu/gpu-data';
7
+ import {
8
+ GPURecordBatch,
9
+ GPUTable,
10
+ isGPUTableIndexColumnName,
11
+ type GPUField,
12
+ type GPUTypeMap
13
+ } from '@luma.gl/graph/gpu-tables';
14
+ import {
15
+ DataType,
16
+ Dictionary,
17
+ Precision,
18
+ type Data,
19
+ type Field,
20
+ type Float32,
21
+ type Int32,
22
+ type Table,
23
+ type TypeMap,
24
+ type Uint32,
25
+ type Utf8
26
+ } from 'apache-arrow';
27
+ import {makeGPUDataFromArrowData} from '@luma.gl/gpgpu/arrow';
28
+
29
+ /** Supported WebGPU-native scalar and categorical index storage formats. */
30
+ type GPUAnalyticsVectorFormat = 'float32' | 'sint32' | 'uint32';
31
+
32
+ /** Maps a typed Arrow schema to its exact portable GPU analytics column formats. */
33
+ export type GPUAnalyticsTypeMapForArrow<T extends TypeMap> = {
34
+ [Name in keyof T & string]: T[Name] extends Float32
35
+ ? 'float32'
36
+ : T[Name] extends Int32
37
+ ? 'sint32'
38
+ : T[Name] extends Uint32
39
+ ? 'uint32'
40
+ : T[Name] extends Dictionary<Utf8, infer IndexType>
41
+ ? IndexType extends Int32
42
+ ? 'sint32'
43
+ : IndexType extends Uint32
44
+ ? 'uint32'
45
+ : never
46
+ : never;
47
+ };
48
+
49
+ /** CPU-owned category labels associated with one GPU-resident dictionary-index column. */
50
+ export type GPUAnalyticsDictionary = {
51
+ /** Dictionary labels in the exact order referenced by uploaded integer indices. */
52
+ readonly values: readonly string[];
53
+ /** Whether the Arrow source declares these category labels ordered. */
54
+ readonly ordered: boolean;
55
+ };
56
+
57
+ /** Renderer-independent Arrow analytics upload options. */
58
+ export type GPUAnalyticsTableFromArrowTableProps<T extends GPUTypeMap = GPUTypeMap> = {
59
+ /** Source columns to upload, in the desired order. Defaults to all source fields. */
60
+ columns?: readonly (keyof T & string)[];
61
+ /** Additional buffer properties; required storage and copy usage are always retained. */
62
+ bufferProps?: GPUVectorBufferProps;
63
+ };
64
+
65
+ /** GPU table plus explicit analytical metadata retained outside generic GPU table storage. */
66
+ export type GPUAnalyticsTableFromArrowTableResult<T extends GPUTypeMap = GPUTypeMap> = {
67
+ /** Existing generic GPU table primitives, preserving every source record batch. */
68
+ table: GPUTable<T>;
69
+ /** One source-row-aligned uint32 GPU validity vector for every nullable selected field. */
70
+ validity: Partial<Record<keyof T & string, GPUVector<'uint32'>>>;
71
+ /** Explicit adapter-owned labels for selected UTF-8 dictionary columns. */
72
+ dictionaries: Partial<Record<keyof T & string, GPUAnalyticsDictionary>>;
73
+ /** Per-field Arrow null counts in source record-batch order. */
74
+ nullCounts: Partial<Record<keyof T & string, readonly number[]>>;
75
+ };
76
+
77
+ /** Fully validated source metadata collected before allocating any GPU resources. */
78
+ type PreparedGPUAnalyticsColumn = {
79
+ field: Field;
80
+ format: GPUAnalyticsVectorFormat;
81
+ chunks: Data[];
82
+ validity: Uint32Array[];
83
+ nullCounts: number[];
84
+ dictionary?: GPUAnalyticsDictionary;
85
+ };
86
+
87
+ const GPU_ANALYTICS_BUFFER_USAGE =
88
+ Buffer.VERTEX | Buffer.STORAGE | Buffer.COPY_DST | Buffer.COPY_SRC;
89
+
90
+ /**
91
+ * Uploads Arrow columns for GPU analytics without requiring renderer-specific shader metadata.
92
+ *
93
+ * Numeric values and dictionary indices stay in existing `GPUData`, `GPURecordBatch`, `GPUVector`,
94
+ * and `GPUTable` objects. Nullable rows receive separate batch-aligned uint32 validity vectors,
95
+ * while dictionary labels and source null counts remain explicit adapter-owned metadata.
96
+ */
97
+ export function makeGPUAnalyticsTableFromArrowTable<T extends TypeMap>(
98
+ device: Device,
99
+ table: Table<T>,
100
+ options?: GPUAnalyticsTableFromArrowTableProps<GPUAnalyticsTypeMapForArrow<T>>
101
+ ): GPUAnalyticsTableFromArrowTableResult<GPUAnalyticsTypeMapForArrow<T>>;
102
+ export function makeGPUAnalyticsTableFromArrowTable<T extends GPUTypeMap = GPUTypeMap>(
103
+ device: Device,
104
+ table: Table,
105
+ options: GPUAnalyticsTableFromArrowTableProps<T> = {}
106
+ ): GPUAnalyticsTableFromArrowTableResult<T> {
107
+ validateGPUAnalyticsBufferProps(options.bufferProps);
108
+ const columns = prepareGPUAnalyticsColumns(table, options.columns);
109
+ const requiredBufferProps = {
110
+ ...options.bufferProps,
111
+ usage: (options.bufferProps?.usage ?? 0) | GPU_ANALYTICS_BUFFER_USAGE
112
+ };
113
+ const allocatedData: GPUData[] = [];
114
+ const allocatedValidityData: GPUData<'uint32'>[] = [];
115
+ const validity: GPUAnalyticsTableFromArrowTableResult<T>['validity'] = {};
116
+ const dictionaries: GPUAnalyticsTableFromArrowTableResult<T>['dictionaries'] = {};
117
+ const nullCounts: GPUAnalyticsTableFromArrowTableResult<T>['nullCounts'] = {};
118
+ let gpuTable: GPUTable<T> | undefined;
119
+
120
+ try {
121
+ for (const column of columns) {
122
+ const columnName = column.field.name as keyof T & string;
123
+ nullCounts[columnName] = Object.freeze([...column.nullCounts]);
124
+ if (column.dictionary) {
125
+ dictionaries[columnName] = column.dictionary;
126
+ }
127
+ }
128
+
129
+ let sourceRowIndexOffset = 0;
130
+ const batches = table.batches.map((recordBatch, sourceBatchIndex) => {
131
+ const gpuData: Record<string, GPUData> = {};
132
+
133
+ for (const column of columns) {
134
+ const sourceData = column.chunks[sourceBatchIndex];
135
+ const data = makeGPUAnalyticsData(device, sourceData, column.format, requiredBufferProps);
136
+ allocatedData.push(data);
137
+ gpuData[column.field.name] = data;
138
+ }
139
+
140
+ const batch = new GPURecordBatch<T>({
141
+ gpuData,
142
+ fields: columns.map(column => makeGPUAnalyticsField(column)),
143
+ numRows: recordBatch.numRows,
144
+ metadata: new Map(recordBatch.schema.metadata),
145
+ sourceInfo: {
146
+ sourceBatchIndex,
147
+ sourceRowIndexOffset,
148
+ sourceRowCount: recordBatch.numRows
149
+ },
150
+ nullCount: recordBatch.nullCount
151
+ });
152
+ sourceRowIndexOffset += recordBatch.numRows;
153
+ return batch;
154
+ });
155
+
156
+ gpuTable =
157
+ batches.length > 0
158
+ ? new GPUTable<T>({batches})
159
+ : new GPUTable<T>({
160
+ schema: {
161
+ fields: columns.map(column => makeGPUAnalyticsField(column)) as GPUField<
162
+ keyof T & string
163
+ >[],
164
+ metadata: new Map(table.schema.metadata)
165
+ },
166
+ bufferLayout: columns.map(column => ({
167
+ name: column.field.name,
168
+ format: column.format,
169
+ byteStride: 4
170
+ }))
171
+ });
172
+
173
+ if (batches.length > 0) {
174
+ gpuTable.schema = {
175
+ fields: columns.map(column => makeGPUAnalyticsField(column)) as GPUField<
176
+ keyof T & string
177
+ >[],
178
+ metadata: new Map(table.schema.metadata)
179
+ };
180
+ }
181
+
182
+ for (const column of columns) {
183
+ if (!column.field.nullable || batches.length === 0) {
184
+ continue;
185
+ }
186
+
187
+ const chunks = column.validity.map(values => {
188
+ const data = makeGPUAnalyticsValidityData(device, values, requiredBufferProps);
189
+ allocatedValidityData.push(data);
190
+ return data;
191
+ });
192
+ validity[column.field.name as keyof T & string] = new GPUVector<'uint32'>({
193
+ type: 'data',
194
+ name: `${column.field.name}-validity`,
195
+ format: 'uint32',
196
+ data: chunks,
197
+ ownsData: true
198
+ });
199
+ }
200
+
201
+ return {table: gpuTable, validity, dictionaries, nullCounts};
202
+ } catch (error) {
203
+ gpuTable?.destroy();
204
+ for (const data of allocatedData) {
205
+ data.destroy();
206
+ }
207
+ for (const data of allocatedValidityData) {
208
+ data.destroy();
209
+ }
210
+ throw error;
211
+ }
212
+ }
213
+
214
+ /** Rejects caller props that would alias owned buffers or invalidate their logical layout. */
215
+ function validateGPUAnalyticsBufferProps(bufferProps: GPUVectorBufferProps | undefined): void {
216
+ if (bufferProps?.handle !== undefined && bufferProps.handle !== null) {
217
+ throw new Error('GPU analytics buffers cannot adopt an external buffer handle');
218
+ }
219
+ if (bufferProps?._isHandleBorrowed) {
220
+ throw new Error('GPU analytics buffers cannot borrow an external buffer handle');
221
+ }
222
+ if (bufferProps?.byteOffset) {
223
+ throw new Error('GPU analytics buffers cannot use a nonzero byte offset');
224
+ }
225
+ if (((bufferProps?.usage ?? 0) & (Buffer.MAP_READ | Buffer.MAP_WRITE)) !== 0) {
226
+ throw new Error('GPU analytics storage buffers cannot declare mapped usage');
227
+ }
228
+ }
229
+
230
+ /** Validates every selected field, batch, bitmap, and dictionary before allocating GPU resources. */
231
+ function prepareGPUAnalyticsColumns(
232
+ table: Table,
233
+ selectedNames: readonly string[] | undefined
234
+ ): PreparedGPUAnalyticsColumn[] {
235
+ const sourceFields = new Map<string, Field>();
236
+ for (const field of table.schema.fields) {
237
+ if (sourceFields.has(field.name)) {
238
+ throw new Error(`GPU analytics source contains duplicate column "${field.name}"`);
239
+ }
240
+ sourceFields.set(field.name, field);
241
+ }
242
+
243
+ const columnNames = selectedNames ?? table.schema.fields.map(field => field.name);
244
+ const encounteredNames = new Set<string>();
245
+ return columnNames.map(columnName => {
246
+ if (encounteredNames.has(columnName)) {
247
+ throw new Error(`GPU analytics column "${columnName}" cannot be selected more than once`);
248
+ }
249
+ encounteredNames.add(columnName);
250
+
251
+ const field = sourceFields.get(columnName);
252
+ if (!field) {
253
+ throw new Error(`GPU analytics column "${columnName}" does not exist`);
254
+ }
255
+ if (isGPUTableIndexColumnName(columnName)) {
256
+ throw new Error(`GPU analytics column "${columnName}" is reserved for table indices`);
257
+ }
258
+
259
+ const column: PreparedGPUAnalyticsColumn = {
260
+ field,
261
+ format: getGPUAnalyticsVectorFormat(field.type, columnName),
262
+ chunks: [],
263
+ validity: [],
264
+ nullCounts: []
265
+ };
266
+
267
+ for (const [batchIndex, batch] of table.batches.entries()) {
268
+ const vector = batch.getChild(columnName);
269
+ const data = vector?.data[0];
270
+ if (!vector || !data || vector.data.length !== 1 || data.length !== batch.numRows) {
271
+ throw new Error(
272
+ `GPU analytics column "${columnName}" has an incompatible chunk in batch ${batchIndex}`
273
+ );
274
+ }
275
+
276
+ if (getGPUAnalyticsVectorFormat(data.type, columnName) !== column.format) {
277
+ throw new Error(`GPU analytics column "${columnName}" changes type between batches`);
278
+ }
279
+
280
+ const validity = getGPUAnalyticsValidity(data, field.nullable, columnName);
281
+ if (DataType.isDictionary(field.type)) {
282
+ const dictionary = getGPUAnalyticsDictionary(data, columnName);
283
+ if (column.dictionary && !areGPUAnalyticsDictionariesEqual(column.dictionary, dictionary)) {
284
+ throw new Error(`GPU analytics dictionary column "${columnName}" changes across batches`);
285
+ }
286
+ column.dictionary ??= dictionary;
287
+ validateGPUAnalyticsDictionaryIndices(data, dictionary, validity, columnName);
288
+ }
289
+
290
+ column.chunks.push(data);
291
+ column.validity.push(validity);
292
+ column.nullCounts.push(data.nullCount);
293
+ }
294
+
295
+ return column;
296
+ });
297
+ }
298
+
299
+ /** Maps the intentionally limited portable Arrow analytics surface to canonical GPU formats. */
300
+ function getGPUAnalyticsVectorFormat(type: DataType, columnName: string): GPUAnalyticsVectorFormat {
301
+ if (DataType.isFloat(type) && type.precision === Precision.SINGLE) {
302
+ return 'float32';
303
+ }
304
+ if (DataType.isInt(type) && type.bitWidth === 32) {
305
+ return type.isSigned ? 'sint32' : 'uint32';
306
+ }
307
+ if (
308
+ DataType.isDictionary(type) &&
309
+ DataType.isUtf8(type.dictionary) &&
310
+ DataType.isInt(type.indices) &&
311
+ type.indices.bitWidth === 32
312
+ ) {
313
+ return type.indices.isSigned ? 'sint32' : 'uint32';
314
+ }
315
+ throw new Error(`GPU analytics column "${columnName}" has unsupported Arrow type ${type}`);
316
+ }
317
+
318
+ /** Expands sliced Arrow validity bits into one 0/1 uint32 value per logical source row. */
319
+ function getGPUAnalyticsValidity(data: Data, nullable: boolean, columnName: string): Uint32Array {
320
+ const nullCount = data.nullCount;
321
+ const sourceRowOffset = data.offset ?? 0;
322
+ if (
323
+ !Number.isSafeInteger(sourceRowOffset) ||
324
+ sourceRowOffset < 0 ||
325
+ !Number.isSafeInteger(nullCount) ||
326
+ nullCount < 0 ||
327
+ nullCount > data.length
328
+ ) {
329
+ throw new Error(`GPU analytics column "${columnName}" has malformed validity metadata`);
330
+ }
331
+ if (!nullable && nullCount > 0) {
332
+ throw new Error(`GPU analytics non-nullable column "${columnName}" contains null values`);
333
+ }
334
+
335
+ const bitmap = data.nullBitmap;
336
+ if (nullCount > 0 && (!bitmap || bitmap.byteLength === 0)) {
337
+ throw new Error(`GPU analytics column "${columnName}" is missing its validity bitmap`);
338
+ }
339
+ if (bitmap && bitmap.byteLength > 0 && bitmap.byteLength * 8 < sourceRowOffset + data.length) {
340
+ throw new Error(`GPU analytics column "${columnName}" has a truncated validity bitmap`);
341
+ }
342
+
343
+ const validity = new Uint32Array(data.length);
344
+ let observedNullCount = 0;
345
+ for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
346
+ const sourceBitIndex = sourceRowOffset + rowIndex;
347
+ const valid =
348
+ !bitmap || bitmap.byteLength === 0
349
+ ? true
350
+ : ((bitmap[sourceBitIndex >> 3] ?? 0) & (1 << (sourceBitIndex & 7))) !== 0;
351
+ validity[rowIndex] = valid ? 1 : 0;
352
+ if (!valid) {
353
+ observedNullCount++;
354
+ }
355
+ }
356
+ if (observedNullCount !== nullCount) {
357
+ throw new Error(`GPU analytics column "${columnName}" has inconsistent validity bitmap`);
358
+ }
359
+ return validity;
360
+ }
361
+
362
+ /** Copies dictionary labels into explicit CPU metadata without retaining the Arrow source vector. */
363
+ function getGPUAnalyticsDictionary(data: Data, columnName: string): GPUAnalyticsDictionary {
364
+ if (!(data.type instanceof Dictionary) || !DataType.isUtf8(data.type.dictionary)) {
365
+ throw new Error(`GPU analytics column "${columnName}" requires a UTF-8 dictionary`);
366
+ }
367
+ if (!data.dictionary) {
368
+ throw new Error(`GPU analytics dictionary column "${columnName}" has no dictionary labels`);
369
+ }
370
+
371
+ const values: string[] = [];
372
+ for (const value of data.dictionary) {
373
+ if (typeof value !== 'string') {
374
+ throw new Error(`GPU analytics dictionary column "${columnName}" contains a null label`);
375
+ }
376
+ values.push(value);
377
+ }
378
+ return Object.freeze({values: Object.freeze(values), ordered: data.type.isOrdered});
379
+ }
380
+
381
+ /** Ensures every non-null dictionary row references an existing category label. */
382
+ function validateGPUAnalyticsDictionaryIndices(
383
+ data: Data,
384
+ dictionary: GPUAnalyticsDictionary,
385
+ validity: Uint32Array,
386
+ columnName: string
387
+ ): void {
388
+ const indices = data.values as Int32Array | Uint32Array;
389
+ const sourceOffset = indices.length === data.length ? 0 : (data.offset ?? 0);
390
+ if (sourceOffset + data.length > indices.length) {
391
+ throw new Error(`GPU analytics dictionary column "${columnName}" has truncated indices`);
392
+ }
393
+ for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
394
+ if (!validity[rowIndex]) {
395
+ continue;
396
+ }
397
+ const categoryIndex = indices[sourceOffset + rowIndex];
398
+ if (categoryIndex < 0 || categoryIndex >= dictionary.values.length) {
399
+ throw new Error(`GPU analytics dictionary column "${columnName}" has an invalid index`);
400
+ }
401
+ }
402
+ }
403
+
404
+ /** Verifies independently supplied record batches use the same category encoding. */
405
+ function areGPUAnalyticsDictionariesEqual(
406
+ first: GPUAnalyticsDictionary,
407
+ second: GPUAnalyticsDictionary
408
+ ): boolean {
409
+ return (
410
+ first.ordered === second.ordered &&
411
+ first.values.length === second.values.length &&
412
+ first.values.every((value, index) => value === second.values[index])
413
+ );
414
+ }
415
+
416
+ /** Reuses the existing Arrow GPU uploader while giving zero-row chunks usable storage capacity. */
417
+ function makeGPUAnalyticsData(
418
+ device: Device,
419
+ source: Data,
420
+ format: GPUAnalyticsVectorFormat,
421
+ bufferProps: GPUVectorBufferProps
422
+ ): GPUData {
423
+ if (source.length > 0) {
424
+ return makeGPUDataFromArrowData(device, source, {...bufferProps, format});
425
+ }
426
+
427
+ const buffer = device.createBuffer({...bufferProps, byteLength: 4});
428
+ try {
429
+ return new GPUData({
430
+ buffer,
431
+ format,
432
+ length: 0,
433
+ stride: 1,
434
+ byteStride: 4,
435
+ rowByteLength: 4,
436
+ dataType: source.type,
437
+ ownsBuffer: true
438
+ });
439
+ } catch (error) {
440
+ buffer.destroy();
441
+ throw error;
442
+ }
443
+ }
444
+
445
+ /** Stores row-aligned validity in a separate owned GPU buffer for each source record batch. */
446
+ function makeGPUAnalyticsValidityData(
447
+ device: Device,
448
+ validity: Uint32Array,
449
+ bufferProps: GPUVectorBufferProps
450
+ ): GPUData<'uint32'> {
451
+ const values = validity.length > 0 ? validity : new Uint32Array(1);
452
+ const buffer = device.createBuffer({...bufferProps, data: values});
453
+ try {
454
+ return new GPUData({
455
+ buffer,
456
+ format: 'uint32',
457
+ length: validity.length,
458
+ ownsBuffer: true
459
+ });
460
+ } catch (error) {
461
+ buffer.destroy();
462
+ throw error;
463
+ }
464
+ }
465
+
466
+ /** Copies source field nullability and metadata into the generic Arrow-free GPU schema. */
467
+ function makeGPUAnalyticsField(column: PreparedGPUAnalyticsColumn): GPUField {
468
+ return {
469
+ name: column.field.name,
470
+ format: column.format,
471
+ nullable: column.field.nullable,
472
+ metadata: new Map(column.field.metadata)
473
+ };
474
+ }