Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat: restore progressive GeoArrow rendering with web workers (#3844)

Igor Dykhta30196cea4572
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index c0870b0cc..2c54d29ff 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -2427,6 +2427,7 @@ type FileContent = {
fileName: string;
header: string[];
data: any;
+ prepareProgressiveReplay?: boolean;
};
export type NextFileBatchUpdaterAction = {
payload: {
diff --git a/src/layers/src/geojson-layer/geojson-layer.ts b/src/layers/src/geojson-layer/geojson-layer.ts
index 9b52bc9b1..599dc089f 100644
--- a/src/layers/src/geojson-layer/geojson-layer.ts
+++ b/src/layers/src/geojson-layer/geojson-layer.ts
@@ -740,6 +740,7 @@ export default class GeoJsonLayer extends Layer {
dataContainer,
geoColumn,
geoField,
+ columnIndex: this.config.columns.geojson.fieldIdx,
...(isIncrementalLoad ? {chunkIndex: this.dataToFeature.length} : null)
});
if (isIncrementalLoad) {
diff --git a/src/layers/src/layer-utils.ts b/src/layers/src/layer-utils.ts
index 30390abde..a5db34cdf 100644
--- a/src/layers/src/layer-utils.ts
+++ b/src/layers/src/layer-utils.ts
@@ -177,16 +177,33 @@ function getBinaryGeometriesFromWKBArrow(
}
export function getGeojsonLayerMetaFromArrow({
+ dataContainer,
geoColumn,
geoField,
+ columnIndex,
chunkIndex
}: {
dataContainer: DataContainerInterface;
geoColumn: arrow.Vector;
geoField: ProtoDatasetField;
+ columnIndex: number;
chunkIndex?: number;
}): GeojsonLayerMetaProps {
const encoding = geoField?.metadata?.get(GEOARROW_METADATA_KEY);
+ const cached =
+ dataContainer instanceof ArrowDataContainer
+ ? dataContainer.getGeoArrowBinaryData(columnIndex, chunkIndex)
+ : undefined;
+ if (cached) {
+ return {
+ dataToFeature: cached.binaryGeometries,
+ featureTypes: cached.featureTypes,
+ bounds: cached.bounds,
+ fixedRadius: false,
+ centroids: cached.meanCenters
+ };
+ }
+
const options: BinaryGeometriesFromArrowOptions = {
...(chunkIndex !== undefined && chunkIndex >= 0
? {
diff --git a/src/processors/src/file-handler.ts b/src/processors/src/file-handler.ts
index 0c6586270..b947ea5b7 100644
--- a/src/processors/src/file-handler.ts
+++ b/src/processors/src/file-handler.ts
@@ -3,6 +3,13 @@
import {parseInBatches} from '@loaders.gl/core';
import {Loader} from '@loaders.gl/loader-utils';
+import * as arrow from 'apache-arrow';
+import {
+ hardClone,
+ parseGeoArrowOnWorker,
+ ParseGeoArrowInput,
+ ParseGeoArrowResult
+} from '@loaders.gl/arrow';
import {
isPlainObject,
generateHashIdFromString,
@@ -11,10 +18,17 @@ import {
isArrowTable
} from '@kepler.gl/utils';
import {generateHashId} from '@kepler.gl/common-utils';
-import {DATASET_FORMATS, DatasetType, REMOTE_FILE_EXTENSIONS} from '@kepler.gl/constants';
+import {
+ DATASET_FORMATS,
+ DatasetType,
+ GEOARROW_EXTENSIONS,
+ GEOARROW_METADATA_KEY,
+ REMOTE_FILE_EXTENSIONS
+} from '@kepler.gl/constants';
import {
AddDataToMapOptions,
AddDataToMapPayload,
+ GeoArrowBinaryData,
LoadedMap,
ProcessorResult
} from '@kepler.gl/types';
@@ -75,6 +89,15 @@ const GIS_TABLE_LOADER_OPTIONS = {
shape: 'geojson-table'
};
+const WORKER_GEOARROW_ENCODINGS = new Set<string>([
+ GEOARROW_EXTENSIONS.POINT,
+ GEOARROW_EXTENSIONS.LINESTRING,
+ GEOARROW_EXTENSIONS.POLYGON,
+ GEOARROW_EXTENSIONS.MULTIPOINT,
+ GEOARROW_EXTENSIONS.MULTILINESTRING,
+ GEOARROW_EXTENSIONS.MULTIPOLYGON
+]);
+
const EXCEL_LOADER_OPTIONS = {
shape: 'object-row-table'
};
@@ -103,10 +126,200 @@ export type ProcessFileDataContent = {
* progressive Arrow loads so each batch does not copy the growing table.
*/
skipArrowCompact?: boolean;
+ /** Build cumulative Arrow snapshots that can be replayed after Add Data confirmation. */
+ prepareProgressiveReplay?: boolean;
};
export {isArrowTable};
+type ParseGeoArrowWorker = (data: ParseGeoArrowInput) => Promise<ParseGeoArrowResult>;
+
+function combineGeoArrowWorkerChunks(parsed: GeoArrowBinaryData): GeoArrowBinaryData | undefined {
+ const combined: GeoArrowBinaryData = {};
+
+ Object.entries(parsed).forEach(([columnIndex, chunks]) => {
+ const ordered = Object.entries(chunks)
+ .map(([chunkIndex, data]) => ({chunkIndex: Number(chunkIndex), data}))
+ .sort((a, b) => a.chunkIndex - b.chunkIndex);
+ if (!ordered.length) {
+ return;
+ }
+
+ const featureTypes = {point: false, line: false, polygon: false};
+ const bounds: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity];
+ const binaryGeometries: any[] = [];
+ const meanCenters: Array<number[] | null> = [];
+ let hasMeanCenters = true;
+
+ ordered.forEach(({data}) => {
+ data.binaryGeometries.forEach(geometry => binaryGeometries.push(geometry));
+ featureTypes.point ||= data.featureTypes.point;
+ featureTypes.line ||= data.featureTypes.line;
+ featureTypes.polygon ||= data.featureTypes.polygon;
+ bounds[0] = Math.min(bounds[0], data.bounds[0]);
+ bounds[1] = Math.min(bounds[1], data.bounds[1]);
+ bounds[2] = Math.max(bounds[2], data.bounds[2]);
+ bounds[3] = Math.max(bounds[3], data.bounds[3]);
+ if (data.meanCenters) {
+ data.meanCenters.forEach(center => meanCenters.push(center));
+ } else {
+ hasMeanCenters = false;
+ }
+ });
+
+ combined[Number(columnIndex)] = {
+ 0: {
+ binaryGeometries,
+ featureTypes,
+ bounds,
+ ...(hasMeanCenters ? {meanCenters} : {})
+ }
+ };
+ });
+
+ return Object.keys(combined).length ? combined : undefined;
+}
+
+function geoArrowWorkerChunksThrough(
+ parsed: GeoArrowBinaryData | undefined,
+ lastChunkIndex: number
+): GeoArrowBinaryData | undefined {
+ if (!parsed) {
+ return undefined;
+ }
+
+ const selected: GeoArrowBinaryData = {};
+ Object.entries(parsed).forEach(([columnIndex, chunks]) => {
+ const selectedChunks = Object.fromEntries(
+ Object.entries(chunks).filter(([chunkIndex]) => Number(chunkIndex) <= lastChunkIndex)
+ );
+ if (Object.keys(selectedChunks).length) {
+ selected[Number(columnIndex)] = selectedChunks;
+ }
+ });
+ return Object.keys(selected).length ? selected : undefined;
+}
+
+function createProgressiveArrowData(
+ source: NonNullable<ProcessorResult>,
+ finalData: NonNullable<ProcessorResult>,
+ geoArrowBinaryData?: GeoArrowBinaryData
+): Array<NonNullable<ProcessorResult>> | undefined {
+ const chunks = source.cols?.[0]?.data;
+ if (!Array.isArray(chunks) || chunks.length < 2 || !source.cols) {
+ return undefined;
+ }
+
+ const {geoArrowBinaryData: _sourceCache, ...sourceWithoutCache} = source;
+ const snapshots: Array<NonNullable<ProcessorResult>> = [];
+ let rowCount = 0;
+ // The final snapshot uses the normally processed (and usually compacted)
+ // table. Intermediate snapshots retain record-batch boundaries.
+ for (let chunkIndex = 0; chunkIndex < chunks.length - 1; chunkIndex++) {
+ rowCount += chunks[chunkIndex].length;
+ const cols = source.cols.map(column => column.slice(0, rowCount));
+ const snapshotCache = geoArrowWorkerChunksThrough(geoArrowBinaryData, chunkIndex);
+ snapshots.push({
+ ...sourceWithoutCache,
+ cols,
+ ...(snapshotCache ? {geoArrowBinaryData: snapshotCache} : {})
+ });
+ }
+ snapshots.push(finalData);
+ return snapshots;
+}
+
+/**
+ * Convert native GeoArrow chunks to deck.gl binary features without blocking
+ * the main thread. WKB/WKT remain on the synchronous fallback because the
+ * loaders.gl triangulation worker only supports native GeoArrow encodings.
+ */
+export async function parseGeoArrowBatchesOnWorkers(
+ data: NonNullable<ProcessorResult>,
+ options: {
+ latestOnly?: boolean;
+ parseOnWorker?: ParseGeoArrowWorker;
+ /** Merge per-batch worker output when the final Arrow table was compacted to one chunk. */
+ targetChunkCount?: number;
+ } = {}
+): Promise<GeoArrowBinaryData | undefined> {
+ const parseOnWorker = options.parseOnWorker || parseGeoArrowOnWorker;
+ if (!options.parseOnWorker && typeof globalThis.Worker === 'undefined') {
+ return undefined;
+ }
+
+ const jobs: Array<Promise<{columnIndex: number; result: ParseGeoArrowResult}>> = [];
+ data.fields.forEach((field, columnIndex) => {
+ const encoding = field.metadata?.get?.(GEOARROW_METADATA_KEY);
+ const geoColumn = data.cols?.[columnIndex];
+ if (!WORKER_GEOARROW_ENCODINGS.has(encoding) || !geoColumn?.data?.length) {
+ return;
+ }
+
+ const chunkIndexes = options.latestOnly
+ ? [geoColumn.data.length - 1]
+ : geoColumn.data.map((_, index) => index);
+ chunkIndexes.forEach(chunkIndex => {
+ const geometryChunk = geoColumn.data[chunkIndex];
+ const chunkCopy = hardClone(geometryChunk, true);
+ const chunkOffset = geoColumn.data
+ .slice(0, chunkIndex)
+ .reduce((offset, chunk) => offset + chunk.length, 0);
+ const chunkType = chunkCopy.type as typeof chunkCopy.type & {listSize?: number};
+ const transferableType = {
+ ...chunkType,
+ typeId: chunkType.typeId,
+ ...(chunkType.listSize !== undefined ? {listSize: chunkType.listSize} : {})
+ } as ParseGeoArrowInput['chunkData']['type'];
+ const sourceData: ParseGeoArrowInput = {
+ operation: 'parse-geoarrow',
+ chunkData: {
+ type: transferableType,
+ offset: chunkCopy.offset,
+ length: chunkCopy.length,
+ nullCount: chunkCopy.nullCount,
+ buffers: chunkCopy.buffers,
+ children: chunkCopy.children,
+ dictionary: chunkCopy.dictionary
+ },
+ chunkIndex,
+ chunkOffset,
+ geometryEncoding: encoding,
+ calculateMeanCenters: true,
+ triangle: true
+ };
+ jobs.push(parseOnWorker(sourceData).then(result => ({columnIndex, result})));
+ });
+ });
+
+ if (!jobs.length) {
+ return undefined;
+ }
+
+ const parsed: GeoArrowBinaryData = {};
+ const results = await Promise.allSettled(jobs);
+ results.forEach(result => {
+ if (result.status !== 'fulfilled') {
+ return;
+ }
+ const {columnIndex, result: workerResult} = result.value;
+ const binaryData = workerResult.binaryDataFromGeoArrow;
+ if (!binaryData) {
+ return;
+ }
+ parsed[columnIndex] = parsed[columnIndex] || {};
+ parsed[columnIndex][workerResult.chunkIndex] = binaryData;
+ });
+
+ if (!Object.keys(parsed).length) {
+ return undefined;
+ }
+
+ return options.targetChunkCount === 1 && !options.latestOnly
+ ? combineGeoArrowWorkerChunks(parsed)
+ : parsed;
+}
+
/**
* check if data is an ArrowData object, which is an array of RecordBatch
* @param data - object to check
@@ -507,6 +720,41 @@ export async function processFileData({
throw new Error(`Can not process uploaded file, ${getError(error as Error)}`);
}
+ let progressiveData: Array<NonNullable<ProcessorResult>> | undefined;
+ if (format === DATASET_FORMATS.arrow && result?.cols) {
+ const latestOnly = Boolean(content.skipArrowCompact);
+ const targetChunkCount = result.cols[0]?.data?.length ?? 0;
+ let workerSource = result;
+
+ // Final file processing compacts Arrow batches to keep the number of deck.gl
+ // sublayers low. Schedule worker jobs from the original batches first so
+ // geometry conversion and triangulation can still run in parallel, then
+ // combine their output to match the single compacted table chunk.
+ if (!latestOnly && Array.isArray(data) && data.length > targetChunkCount) {
+ const sourceTable = new arrow.Table(data as arrow.RecordBatch[]);
+ const cols = [...Array(sourceTable.numCols).keys()].map(i => sourceTable.getChildAt(i));
+ workerSource = {...result, cols};
+ }
+
+ const workerGeoArrowBinaryData = await parseGeoArrowBatchesOnWorkers(workerSource, {
+ latestOnly
+ });
+ const geoArrowBinaryData =
+ targetChunkCount === 1 && !latestOnly && workerGeoArrowBinaryData
+ ? combineGeoArrowWorkerChunks(workerGeoArrowBinaryData)
+ : workerGeoArrowBinaryData;
+ if (geoArrowBinaryData) {
+ result = {...result, geoArrowBinaryData};
+ }
+ if (content.prepareProgressiveReplay && !latestOnly) {
+ progressiveData = createProgressiveArrowData(
+ workerSource,
+ result,
+ workerGeoArrowBinaryData
+ );
+ }
+ }
+
const sourceUrl = content.sourceUrl;
const remoteFormat = getPersistedRemoteFormat(content.keplerFormat, content.fileName);
const fileSize = typeof content.fileSize === 'number' ? content.fileSize : undefined;
@@ -531,6 +779,7 @@ export async function processFileData({
...fileCache,
{
data: result,
+ ...(progressiveData ? {progressiveData} : {}),
info: {
id,
label: content.fileName,
@@ -545,6 +794,25 @@ export async function processFileData({
}
}
+/**
+ * Expand staged files into cumulative payloads for one redraw per Arrow batch.
+ * Non-progressive files are present only in the first payload.
+ */
+export function fileCacheToProgressiveSteps(fileCache: FileCacheItem[]): FileCacheItem[][] {
+ const numberOfSteps = Math.max(1, ...fileCache.map(file => file.progressiveData?.length || 1));
+
+ return Array.from({length: numberOfSteps}, (_, stepIndex) =>
+ fileCache.flatMap(file => {
+ const {progressiveData, ...fileWithoutProgressiveData} = file;
+ if (!progressiveData) {
+ return stepIndex === 0 ? [fileWithoutProgressiveData] : [];
+ }
+ const data = progressiveData[stepIndex];
+ return data ? [{...fileWithoutProgressiveData, data}] : [];
+ })
+ ).filter(step => step.length);
+}
+
export function filesToDataPayload(
fileCache: FileCacheItem[],
options?: AddDataToMapOptions
diff --git a/src/processors/src/types.ts b/src/processors/src/types.ts
index 3e9cbab37..abe64903f 100644
--- a/src/processors/src/types.ts
+++ b/src/processors/src/types.ts
@@ -3,6 +3,12 @@
export type FileCacheItem = {
data: any;
+ /**
+ * Cumulative Arrow snapshots replayed after the user confirms Add Data.
+ * Kept outside `data` so the final staged dataset remains available for
+ * validation and row-count display without being added to the map early.
+ */
+ progressiveData?: any[];
info: {
id?: string;
label: string;
diff --git a/src/reducers/src/combined-updaters.ts b/src/reducers/src/combined-updaters.ts
index 11d6af901..a03f3c7b5 100644
--- a/src/reducers/src/combined-updaters.ts
+++ b/src/reducers/src/combined-updaters.ts
@@ -25,7 +25,8 @@ import {
mapStyleChangeUpdater,
receiveMapConfigUpdater as styleMapConfigUpdater
} from './map-style-updaters';
-import {filesToDataPayload} from '@kepler.gl/processors';
+import {fileCacheToProgressiveSteps, filesToDataPayload} from '@kepler.gl/processors';
+import type {FileCacheItem} from '@kepler.gl/processors';
import {payload_, apply_, with_, if_, compose_, merge_, pick_} from './composer-helpers';
import {MapState, UiState, AddDataToMapPayload, ParsedConfig, ProtoDataset} from '@kepler.gl/types';
import {MapStyle} from './map-style-updaters';
@@ -34,6 +35,7 @@ import {
loadFilesSuccessUpdaterAction,
ConfirmReplaceDatasetUpdaterAction,
StageLoadedFilesUpdaterAction,
+ loadFilesSuccess,
MapStyleChangeUpdaterAction,
LayerTypeChangeUpdaterAction,
ToggleSplitMapUpdaterAction,
@@ -61,6 +63,14 @@ export type KeplerGlState = {
providerState: ProviderState;
};
+type ProgressiveLoadFilesSuccessAction = loadFilesSuccessUpdaterAction & {
+ progressiveSteps?: FileCacheItem[][];
+};
+
+type ProgressiveLoadContinuation = ReturnType<typeof loadFilesSuccess> & {
+ progressiveSteps: FileCacheItem[][];
+};
+
// compose action to apply result multiple reducers, with the output of one
/**
@@ -147,7 +157,7 @@ export const defaultAddDataToMapOptions = {
*/
export const addDataToMapUpdater = (
state: KeplerGlState,
- {payload}: {payload: AddDataToMapPayload}
+ {payload, onFinish}: {payload: AddDataToMapPayload; onFinish?: ProgressiveLoadContinuation}
): KeplerGlState => {
const {datasets, config, info} = payload;
@@ -168,7 +178,8 @@ export const addDataToMapUpdater = (
apply_<VisState, any>(visStateUpdateVisDataUpdater, {
datasets,
options,
- config
+ config,
+ onFinish
})
)
])(state);
@@ -198,7 +209,8 @@ export const addDataToMapUpdater = (
apply_<VisState, any>(visStateUpdateVisDataUpdater, {
datasets,
options,
- config: parsedConfig
+ config: parsedConfig,
+ onFinish
})
),
@@ -236,13 +248,25 @@ export const addDataToMapUpdater = (
export const loadFilesSuccessUpdater = (
state: KeplerGlState,
- action: loadFilesSuccessUpdaterAction
+ action: ProgressiveLoadFilesSuccessAction
): KeplerGlState => {
if (isStaleFileLoadFinish(state.visState.fileLoading, action.loadId)) {
return state;
}
- // still more to load
- const payloads = filesToDataPayload(action.result, action.options);
+ const progressiveSteps = Object.prototype.hasOwnProperty.call(action, 'progressiveSteps')
+ ? [action.result, ...(action.progressiveSteps || [])]
+ : fileCacheToProgressiveSteps(action.result);
+ const [currentStep = action.result, ...remainingSteps] = progressiveSteps;
+ const payloads = filesToDataPayload(currentStep, action.options);
+ // The first progressive snapshot may fit the map to the newly created layer.
+ // Later snapshots only replace that layer's data and must not keep moving the viewport.
+ const continuationOptions = {...action.options, centerMap: false};
+ const onFinish: ProgressiveLoadContinuation | undefined = remainingSteps.length
+ ? {
+ ...loadFilesSuccess(remainingSteps[0], continuationOptions),
+ progressiveSteps: remainingSteps.slice(1)
+ }
+ : undefined;
const nextState = compose_([
pick_('visState')(
merge_({
@@ -253,9 +277,14 @@ export const loadFilesSuccessUpdater = (
)
])(state);
// make multiple add data to map calls
- const stateWithData = compose_(payloads.map(p => apply_(addDataToMapUpdater, payload_(p))))(
- nextState
- );
+ const stateWithData = compose_(
+ payloads.map((p, index) =>
+ apply_(addDataToMapUpdater, {
+ ...payload_(p),
+ ...(onFinish && index === payloads.length - 1 ? {onFinish} : {})
+ })
+ )
+ )(nextState);
return stateWithData as KeplerGlState;
};
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index cfa5d6125..263c09b32 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -178,6 +178,7 @@ import {
isZipFileName,
loadExternallyHostedDataset,
processGeojson,
+ type FileCacheItem,
ZipArchiveExpansion
} from '@kepler.gl/processors';
@@ -4111,6 +4112,18 @@ export function refreshDatasetErrorUpdater(
* @memberof visStateUpdaters
* @public
*/
+type ProgressiveLoadContinuation = ReturnType<typeof loadFilesSuccess> & {
+ progressiveSteps: FileCacheItem[][];
+};
+
+type ProgressiveUpdateVisDataUpdaterAction = VisStateActions.UpdateVisDataUpdaterAction & {
+ onFinish?: ProgressiveLoadContinuation;
+};
+
+type ProgressiveCreateNewDatasetSuccessPayload = CreateNewDatasetSuccessPayload & {
+ onFinish?: ProgressiveLoadContinuation;
+};
+
// eslint-disable-next-line complexity
export const updateVisDataUpdater = (
state: VisState,
@@ -4188,14 +4201,17 @@ export const updateVisDataUpdater = (
}
return withTask(updatedState, [
- ...batches.map(batch =>
- Task.allSettled(batch.tasks).map(results =>
- createNewDatasetSuccess({
+ ...batches.map((batch, batchIndex) =>
+ Task.allSettled(batch.tasks).map(results => {
+ const onFinish = (action as ProgressiveUpdateVisDataUpdaterAction).onFinish;
+ const payload: ProgressiveCreateNewDatasetSuccessPayload = {
results,
addToMapOptions: options,
- progressIds: batch.progressIds
- })
- )
+ progressIds: batch.progressIds,
+ ...(onFinish && batchIndex === batches.length - 1 ? {onFinish} : {})
+ };
+ return createNewDatasetSuccess(payload);
+ })
),
...notificationTasks
]);
@@ -4205,7 +4221,8 @@ export const createNewDatasetSuccessUpdater = (
state: VisState,
action: PayloadAction<CreateNewDatasetSuccessPayload>
): VisState => {
- const {results, addToMapOptions, progressIds} = action.payload;
+ const {results, addToMapOptions, progressIds, onFinish} =
+ action.payload as ProgressiveCreateNewDatasetSuccessPayload;
const notificationTasks: TaskDescriptor[] = [];
const newDataEntries = results.reduce((accu, result, idx) => {
@@ -4255,7 +4272,12 @@ export const createNewDatasetSuccessUpdater = (
setLoadingIndicatorUpdater(updatedState, payload_({change: -1})),
progressIds
),
- notificationTasks
+ [
+ ...notificationTasks,
+ // Match the original Arrow batching cadence: cross an event-loop turn so
+ // React/deck.gl can paint this snapshot before the next table update.
+ ...(onFinish ? [DELAY_TASK(10).map(() => onFinish)] : [])
+ ]
);
};
@@ -5315,7 +5337,12 @@ export function makeLoadFileTask(
fileName: displayName,
onFinish: result =>
processFileContent({
- content: result,
+ content: {
+ ...result,
+ ...(addDataOptions?.deferAddToMap && getApplicationConfig().useArrowProgressiveLoading
+ ? {prepareProgressiveReplay: true}
+ : {})
+ },
fileCache
}),
...(addDataOptions ? {options: addDataOptions} : {})
diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.ts
index b629fece8..fee0da7d1 100644
--- a/src/table/src/kepler-table.ts
+++ b/src/table/src/kepler-table.ts
@@ -257,6 +257,7 @@ class KeplerTable<F extends Field = Field> {
const dataContainer = createDataContainer(dataContainerData, {
fields: data.fields,
arrowTable: data.arrowTable,
+ geoArrowBinaryData: data.geoArrowBinaryData,
inputDataFormat
});
@@ -304,7 +305,9 @@ class KeplerTable<F extends Field = Field> {
const dataContainerData = isRowSnapshot ? data.rows : data.arrowTable ?? data.cols ?? data.rows;
if (typeof this.dataContainer.update === 'function') {
- this.dataContainer.update(dataContainerData);
+ this.dataContainer.update(dataContainerData, {
+ geoArrowBinaryData: data.geoArrowBinaryData
+ });
} else if (isRowSnapshot) {
this.dataContainer = createDataContainer(dataContainerData, {
fields: data.fields || this.fields,
diff --git a/src/types/actions.d.ts b/src/types/actions.d.ts
index f9137cbf3..aef93215b 100644
--- a/src/types/actions.d.ts
+++ b/src/types/actions.d.ts
@@ -45,6 +45,20 @@ export type ProtoDatasetField = {
id?: string;
metadata?: Record<string, any>;
};
+
+export type GeoArrowBinaryData = Record<
+ number,
+ Record<
+ number,
+ {
+ binaryGeometries: any[];
+ bounds: [number, number, number, number];
+ featureTypes: {point: boolean; line: boolean; polygon: boolean};
+ meanCenters?: Array<number[] | null>;
+ }
+ >
+>;
+
export type ProtoDataset = {
info: {
id?: string;
@@ -59,6 +73,8 @@ export type ProtoDataset = {
rows: any[][];
cols?: any[];
arrowTable?: arrow.Table;
+ /** GeoArrow chunks already converted to deck.gl binary features on workers. */
+ geoArrowBinaryData?: GeoArrowBinaryData;
/** Existing table in the configured DuckDB database; avoids re-importing its rows. */
duckdbTableName?: string;
};
diff --git a/src/types/types.d.ts b/src/types/types.d.ts
index a6a23fb32..6362be84c 100644
--- a/src/types/types.d.ts
+++ b/src/types/types.d.ts
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
+import type {GeoArrowBinaryData} from './actions';
+
export type RGBColor = [number, number, number];
export type RGBAColor = [number, number, number, number];
export type HexColor = string; // this is the best typescript can do at the moment
@@ -52,6 +54,8 @@ export type ProcessorResult = {
rows: any[][];
cols?: any[];
metadata?: any;
+ /** GeoArrow chunks already converted to deck.gl binary features on workers. */
+ geoArrowBinaryData?: GeoArrowBinaryData;
/** Optional schema for arrow tables with metadata preserved. */
// TODO: Should we use a loaded arrow.Table in cols instead of an array of arrow.Vectors? Why was an array of arrow.Vectors chosen?
arrowSchema?: any;
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 1a3d52211..67e9b7d18 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -430,7 +430,7 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
table: null,
database: null,
- useArrowProgressiveLoading: true,
+ useArrowProgressiveLoading: false,
showReleaseBanner: true,
useOnFilteredItemsChange: false,
diff --git a/src/utils/src/arrow-data-container.ts b/src/utils/src/arrow-data-container.ts
index 6de64ebdd..a4cfc9712 100644
--- a/src/utils/src/arrow-data-container.ts
+++ b/src/utils/src/arrow-data-container.ts
@@ -2,7 +2,7 @@
// Copyright contributors to the kepler.gl project
import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
-import {ProtoDatasetField} from '@kepler.gl/types';
+import {GeoArrowBinaryData, ProtoDatasetField} from '@kepler.gl/types';
import * as arrow from 'apache-arrow';
import {console as globalConsole} from 'global/window';
import {DATA_TYPES as AnalyzerDATA_TYPES} from 'type-analyzer';
@@ -15,6 +15,11 @@ type ArrowDataContainerInput = {
cols: arrow.Vector[];
fields?: ProtoDatasetField[];
arrowTable?: arrow.Table;
+ geoArrowBinaryData?: GeoArrowBinaryData;
+};
+
+type ArrowDataContainerUpdateOptions = {
+ geoArrowBinaryData?: GeoArrowBinaryData;
};
/**
@@ -323,6 +328,7 @@ export class ArrowDataContainer implements DataContainerInterface {
_numRows: number;
_fields: ProtoDatasetField[];
_numChunks: number;
+ _geoArrowBinaryData: GeoArrowBinaryData;
// cache column data to make valueAt() faster
// _colData: any[][];
@@ -343,6 +349,7 @@ export class ArrowDataContainer implements DataContainerInterface {
this._numColumns = this._cols.length;
this._numRows = this._cols[0]?.length ?? 0;
this._numChunks = this._cols[0]?.data?.length ?? 0;
+ this._geoArrowBinaryData = data.geoArrowBinaryData || {};
const table = compactArrowTable(data.arrowTable || this._createTable());
this._arrowTable = table;
if (table.numCols > 0) {
@@ -377,10 +384,14 @@ export class ArrowDataContainer implements DataContainerInterface {
this._numChunks = this._cols[0]?.data?.length ?? 0;
}
- update(updateData: arrow.Vector<any>[] | arrow.Table) {
+ update(
+ updateData: arrow.Vector<any>[] | arrow.Table,
+ options: ArrowDataContainerUpdateOptions = {}
+ ) {
// Incremental Arrow loads append batches here. Compacting on every update
// would copy the growing table (Builder over every cell). Skip collapse;
// processArrowBatches compact once when the file is fully loaded.
+ const previousNumChunks = this._numChunks;
const isArrow = isArrowTable(updateData);
if (isArrow) {
this._assignTable(updateData);
@@ -397,6 +408,20 @@ export class ArrowDataContainer implements DataContainerInterface {
}
}
+ // Progressive snapshots add one record batch at a time, so keep already
+ // parsed chunks and merge the new worker result. A compaction/replacement
+ // resets chunk numbering and must replace the cache instead.
+ if (this._numChunks > previousNumChunks) {
+ Object.entries(options.geoArrowBinaryData || {}).forEach(([columnIndex, chunks]) => {
+ this._geoArrowBinaryData[Number(columnIndex)] = {
+ ...this._geoArrowBinaryData[Number(columnIndex)],
+ ...chunks
+ };
+ });
+ } else {
+ this._geoArrowBinaryData = options.geoArrowBinaryData || {};
+ }
+
// cache column data to make valueAt() faster
// this._colData = this._cols.map(c => c.toArray());
}
@@ -405,6 +430,52 @@ export class ArrowDataContainer implements DataContainerInterface {
return this._numChunks;
}
+ getGeoArrowBinaryData(columnIndex: number, chunkIndex?: number) {
+ const columnData = this._geoArrowBinaryData[columnIndex];
+ if (!columnData) {
+ return undefined;
+ }
+ if (chunkIndex !== undefined) {
+ return columnData[chunkIndex];
+ }
+
+ const chunks = Object.entries(columnData)
+ .map(([index, data]) => ({index: Number(index), data}))
+ .sort((a, b) => a.index - b.index);
+ if (chunks.length !== this._numChunks) {
+ return undefined;
+ }
+
+ const featureTypes = {point: false, line: false, polygon: false};
+ const bounds: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity];
+ const binaryGeometries: any[] = [];
+ const meanCenters: Array<number[] | null> = [];
+ let hasMeanCenters = true;
+
+ chunks.forEach(({data}) => {
+ data.binaryGeometries.forEach(geometry => binaryGeometries.push(geometry));
+ featureTypes.point ||= data.featureTypes.point;
+ featureTypes.line ||= data.featureTypes.line;
+ featureTypes.polygon ||= data.featureTypes.polygon;
+ bounds[0] = Math.min(bounds[0], data.bounds[0]);
+ bounds[1] = Math.min(bounds[1], data.bounds[1]);
+ bounds[2] = Math.max(bounds[2], data.bounds[2]);
+ bounds[3] = Math.max(bounds[3], data.bounds[3]);
+ if (data.meanCenters) {
+ data.meanCenters.forEach(center => meanCenters.push(center));
+ } else {
+ hasMeanCenters = false;
+ }
+ });
+
+ return {
+ binaryGeometries,
+ featureTypes,
+ bounds,
+ ...(hasMeanCenters ? {meanCenters} : {})
+ };
+ }
+
numRows(): number {
return this._numRows;
}
diff --git a/src/utils/src/data-container-interface.ts b/src/utils/src/data-container-interface.ts
index 31b254f82..61b437ef9 100644
--- a/src/utils/src/data-container-interface.ts
+++ b/src/utils/src/data-container-interface.ts
@@ -17,7 +17,7 @@ export interface DataContainerInterface {
* Updates the data container with new data.
* @param updateData updated data, e.g. for arrow data container, it's an array of arrow columns or an arrow.Table; for row data container, it's an array of rows.
*/
- update?(updateData: any[] | arrow.Table): void;
+ update?(updateData: any[] | arrow.Table, options?: Record<string, unknown>): void;
/**
* Append rows in place. Implemented by row containers; Arrow/DuckDB omit this.
diff --git a/src/utils/src/data-container-utils.ts b/src/utils/src/data-container-utils.ts
index e55cc3151..92203d631 100644
--- a/src/utils/src/data-container-utils.ts
+++ b/src/utils/src/data-container-utils.ts
@@ -6,13 +6,14 @@ import {RowDataContainer} from './row-data-container';
import {IndexedDataContainer} from './indexed-data-container';
import {DataContainerInterface} from './data-container-interface';
-import {ProtoDatasetField} from '@kepler.gl/types';
+import {GeoArrowBinaryData, ProtoDatasetField} from '@kepler.gl/types';
import * as arrow from 'apache-arrow';
export type DataContainerOptions = {
inputDataFormat?: string; // one of DataForm
fields?: ProtoDatasetField[];
arrowTable?: arrow.Table;
+ geoArrowBinaryData?: GeoArrowBinaryData;
};
export const DataForm = {
@@ -42,7 +43,8 @@ export function createDataContainer(
return new ArrowDataContainer({
cols: data,
fields: options.fields,
- arrowTable: options.arrowTable
+ arrowTable: options.arrowTable,
+ geoArrowBinaryData: options.geoArrowBinaryData
});
}
diff --git a/src/utils/src/dataset-utils.ts b/src/utils/src/dataset-utils.ts
index a0ebf6804..922ea7994 100644
--- a/src/utils/src/dataset-utils.ts
+++ b/src/utils/src/dataset-utils.ts
@@ -248,7 +248,7 @@ export function validateInputData(data: ProtoDataset['data']): ProcessorResult {
return null;
}
- const {fields, rows, cols} = data;
+ const {fields, rows, cols, geoArrowBinaryData} = data;
// check if all fields has name, format and type
const allValid = fields.every((f, i) => {
@@ -294,7 +294,12 @@ export function validateInputData(data: ProtoDataset['data']): ProcessorResult {
});
if (allValid) {
- return {rows, fields, cols};
+ return {
+ rows,
+ fields,
+ cols,
+ ...(geoArrowBinaryData ? {geoArrowBinaryData} : {})
+ };
}
// if any field has missing type, recalculate it for everyone
@@ -317,7 +322,12 @@ export function validateInputData(data: ProtoDataset['data']): ProcessorResult {
analyzerType: meta[i].analyzerType
}));
- return {fields: updatedFields, rows, ...(cols ? {cols} : {})};
+ return {
+ fields: updatedFields,
+ rows,
+ ...(cols ? {cols} : {}),
+ ...(geoArrowBinaryData ? {geoArrowBinaryData} : {})
+ };
}
function findNonEmptyRowsAtField(rows: unknown[][], fieldIdx: number, total: number): any[] {
diff --git a/test/node/processors/file-handler-test.js b/test/node/processors/file-handler-test.js
index 1e64974d7..be194ca12 100644
--- a/test/node/processors/file-handler-test.js
+++ b/test/node/processors/file-handler-test.js
@@ -6,13 +6,19 @@ import {
isKeplerGlMap,
makeProgressIterator,
filesToDataPayload,
+ fileCacheToProgressiveSteps,
processFileData,
+ parseGeoArrowBatchesOnWorkers,
remoteDatasetFromUrl,
processArrowBatches,
getGeoJsonFromLoaderResult,
readBatch
} from '@kepler.gl/processors';
-import {getDatasetRefreshIntervalMs} from '@kepler.gl/constants';
+import {
+ GEOARROW_EXTENSIONS,
+ GEOARROW_METADATA_KEY,
+ getDatasetRefreshIntervalMs
+} from '@kepler.gl/constants';
import * as arrow from 'apache-arrow';
import {convertArrowToSchema} from '@loaders.gl/schema-utils';
import {parsedFields, parsedRows} from 'test/fixtures/row-object';
@@ -455,6 +461,135 @@ test('#file-handler -> processArrowBatches skip compact for incremental loads',
t.end();
});
+test('#file-handler -> parseGeoArrowBatchesOnWorkers parses the latest chunk', async t => {
+ const pointType = new arrow.FixedSizeList(2, new arrow.Field('xy', new arrow.Float64(), false));
+ const batchA = new arrow.Table({
+ geometry: arrow.vectorFromArray([[-122.4, 37.8]], pointType)
+ });
+ const batchB = new arrow.Table({
+ geometry: arrow.vectorFromArray(
+ [
+ [-122.5, 37.9],
+ [-122.6, 38]
+ ],
+ pointType
+ )
+ });
+ batchA.schema.fields[0].metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
+ batchB.schema.fields[0].metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
+ const combined = batchA.concat(batchB);
+ const processed = processArrowBatches(combined.batches, {compact: false});
+ const calls = [];
+ const binaryDataFromGeoArrow = {
+ binaryGeometries: [{shape: 'binary-feature-collection'}],
+ bounds: [-122.6, 37.9, -122.5, 38],
+ featureTypes: {point: true, line: false, polygon: false},
+ meanCenters: [
+ [-122.5, 37.9],
+ [-122.6, 38]
+ ]
+ };
+
+ const parsed = await parseGeoArrowBatchesOnWorkers(processed, {
+ latestOnly: true,
+ parseOnWorker: async input => {
+ calls.push(input);
+ return {chunkIndex: input.chunkIndex, binaryDataFromGeoArrow};
+ }
+ });
+
+ t.equal(calls.length, 1, 'should schedule one worker for the newest chunk');
+ t.equal(calls[0].chunkIndex, 1, 'should parse the second record batch');
+ t.equal(calls[0].chunkOffset, 1, 'should offset global feature ids by earlier row counts');
+ t.equal(
+ calls[0].geometryEncoding,
+ GEOARROW_EXTENSIONS.POINT,
+ 'should preserve the native GeoArrow encoding'
+ );
+ t.equal(parsed[0][1], binaryDataFromGeoArrow, 'should cache worker output by column and chunk');
+ t.end();
+});
+
+test('#file-handler -> parseGeoArrowBatchesOnWorkers combines compacted worker chunks', async t => {
+ const pointType = new arrow.FixedSizeList(2, new arrow.Field('xy', new arrow.Float64(), false));
+ const batchA = new arrow.Table({
+ geometry: arrow.vectorFromArray([[-122.4, 37.8]], pointType)
+ });
+ const batchB = new arrow.Table({
+ geometry: arrow.vectorFromArray([[-122.5, 37.9]], pointType)
+ });
+ batchA.schema.fields[0].metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
+ batchB.schema.fields[0].metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
+ const processed = processArrowBatches(batchA.concat(batchB).batches, {compact: false});
+ const calls = [];
+
+ const parsed = await parseGeoArrowBatchesOnWorkers(processed, {
+ targetChunkCount: 1,
+ parseOnWorker: async input => {
+ calls.push(input);
+ const x = input.chunkIndex === 0 ? -122.4 : -122.5;
+ const y = input.chunkIndex === 0 ? 37.8 : 37.9;
+ return {
+ chunkIndex: input.chunkIndex,
+ binaryDataFromGeoArrow: {
+ binaryGeometries: [{chunkIndex: input.chunkIndex}],
+ bounds: [x, y, x, y],
+ featureTypes: {point: true, line: false, polygon: false},
+ meanCenters: [[x, y]]
+ }
+ };
+ }
+ });
+
+ t.equal(calls.length, 2, 'should schedule one worker job per original record batch');
+ t.deepEqual(Object.keys(parsed[0]), ['0'], 'should expose one cache chunk after compaction');
+ t.deepEqual(
+ parsed[0][0].binaryGeometries,
+ [{chunkIndex: 0}, {chunkIndex: 1}],
+ 'should retain worker geometry in record-batch order'
+ );
+ t.deepEqual(parsed[0][0].bounds, [-122.5, 37.8, -122.4, 37.9], 'should merge bounds');
+ t.deepEqual(
+ parsed[0][0].meanCenters,
+ [
+ [-122.4, 37.8],
+ [-122.5, 37.9]
+ ],
+ 'should merge mean centers'
+ );
+ t.end();
+});
+
+test('#file-handler -> compacted worker cache handles large centroid arrays', async t => {
+ const pointType = new arrow.FixedSizeList(2, new arrow.Field('xy', new arrow.Float64(), false));
+ const table = new arrow.Table({
+ geometry: arrow.vectorFromArray([[-122.4, 37.8]], pointType)
+ });
+ table.schema.fields[0].metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
+ const processed = processArrowBatches(table.batches, {compact: false});
+ const largeMeanCenters = Array.from({length: 150000}, () => [-122.4, 37.8]);
+
+ const parsed = await parseGeoArrowBatchesOnWorkers(processed, {
+ targetChunkCount: 1,
+ parseOnWorker: async input => ({
+ chunkIndex: input.chunkIndex,
+ binaryDataFromGeoArrow: {
+ binaryGeometries: [],
+ bounds: [-122.4, 37.8, -122.4, 37.8],
+ featureTypes: {point: true, line: false, polygon: false},
+ meanCenters: largeMeanCenters
+ }
+ })
+ });
+
+ t.equal(
+ parsed[0][0].meanCenters.length,
+ largeMeanCenters.length,
+ 'should combine every centroid without spreading them into function arguments'
+ );
+ t.end();
+});
+
test('#file-handler -> processArrowBatches Int64/Uint64 columns', async t => {
const table = arrow.tableFromArrays({
hexId: new BigUint64Array([610625465232654335n, 610625465081659391n]),
@@ -671,7 +806,8 @@ test('#file-handler -> rows with type Feature but no geometry stay tables', asyn
test('#file-handler -> processFileData skipArrowCompact', async t => {
const batchA = arrow.tableFromJSON([{lng: -122.4, lat: 37.8}]);
const batchB = arrow.tableFromJSON([{lng: -122.5, lat: 37.9}]);
- const combined = batchA.concat(batchB);
+ const batchC = arrow.tableFromJSON([{lng: -122.6, lat: 38.0}]);
+ const combined = batchA.concat(batchB).concat(batchC);
const incremental = await processFileData({
content: {
@@ -700,5 +836,35 @@ test('#file-handler -> processFileData skipArrowCompact', async t => {
'final processFileData should compact Arrow batches'
);
+ const staged = await processFileData({
+ content: {
+ fileName: 'points.arrow',
+ data: combined.batches,
+ prepareProgressiveReplay: true
+ },
+ fileCache: []
+ });
+ t.equal(staged[0].progressiveData.length, 3, 'should keep one replay snapshot per batch');
+ t.deepEqual(
+ staged[0].progressiveData.map(data => data.cols[0].length),
+ [1, 2, 3],
+ 'replay snapshots should grow by one batch at a time'
+ );
+ t.deepEqual(
+ staged[0].progressiveData.map(data => data.cols[0].data.length),
+ [1, 2, 1],
+ 'only the completed replay snapshot should be compacted'
+ );
+
+ const csv = {
+ data: {fields: [], rows: [[1]]},
+ info: {id: 'csv', label: 'points.csv', format: 'csv'}
+ };
+ const steps = fileCacheToProgressiveSteps([staged[0], csv]);
+ t.equal(steps.length, 3, 'should create one confirmed Add Data update per Arrow batch');
+ t.equal(steps[0].length, 2, 'non-progressive files should be included in the first update');
+ t.equal(steps[1].length, 1, 'later updates should contain only the Arrow dataset');
+ t.notOk(steps[0][0].progressiveData, 'internal replay data should not enter map state');
+
t.end();
});
diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.js
index c71d68125..551281078 100644
--- a/test/node/reducers/composer-state-test.js
+++ b/test/node/reducers/composer-state-test.js
@@ -3,7 +3,7 @@
/* eslint-disable max-statements */
-import {drainTasksForTesting, succeedTaskWithValues} from '@kepler.gl/tasks';
+import {drainTasksForTesting, succeedTaskInTest, succeedTaskWithValues} from '@kepler.gl/tasks';
import test from 'tape';
import {
@@ -25,6 +25,7 @@ import keplerGlReducer, {
} from '@kepler.gl/reducers';
import {MapSplitMode} from '@kepler.gl/constants';
import KeplerGlSchema from '@kepler.gl/schemas';
+import {KeplerTable} from '@kepler.gl/table';
import {getTimeBins} from '@kepler.gl/utils';
import testCsvData, {sampleConfig, dataWithNulls} from 'test/fixtures/test-csv-data';
@@ -1402,6 +1403,53 @@ test('#composerStateReducer -> stageLoadedFilesUpdater keeps the modal open', t
t.end();
});
+test('#composerStateReducer -> progressive Arrow confirmation queues the next snapshot', t => {
+ const base = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;
+ const first = {
+ info: {id: 'progressive-arrow', label: 'progressive.arrow', format: 'arrow'},
+ data: {...mockRawData, rows: mockRawData.rows.slice(0, 1)}
+ };
+ const final = {
+ ...first,
+ data: {...mockRawData, rows: mockRawData.rows.slice(0, 2)}
+ };
+ const staged = {
+ ...final,
+ progressiveData: [first.data, final.data]
+ };
+ const afterFirstDispatch = combinedUpdaters.loadFilesSuccessUpdater(
+ base,
+ loadFilesSuccess([staged], {autoCreateLayers: false, centerMap: true})
+ );
+
+ const afterFirstCommit = applyExistingDatasetTasks(visStateReducer, afterFirstDispatch.visState);
+ const continuation = drainTasksForTesting().find(task => task.label === 'DELAY_TASK');
+ const nextAction = succeedTaskInTest(continuation, undefined);
+ const afterFinalDispatch = combinedUpdaters.loadFilesSuccessUpdater(
+ {...afterFirstDispatch, visState: afterFirstCommit},
+ nextAction
+ );
+ const [updateTask] = drainTasksForTesting();
+ const finalTable = new KeplerTable({info: final.info});
+ finalTable.importData({data: final.data});
+ const afterFinalCommit = visStateReducer(
+ afterFinalDispatch.visState,
+ succeedTaskWithValues(updateTask, [finalTable])
+ );
+
+ t.equal(afterFirstCommit.datasets['progressive-arrow'].length, 1, 'commits the first snapshot');
+ t.equal(nextAction.result[0].data.rows.length, 2, 'queues the next cumulative snapshot');
+ t.deepEqual(
+ nextAction.progressiveSteps,
+ [],
+ 'marks the final step without queueing another snapshot'
+ );
+ t.equal(nextAction.options.centerMap, false, 'does not center subsequent snapshots');
+ t.equal(afterFinalCommit.datasets['progressive-arrow'].length, 2, 'commits the final snapshot');
+ t.equal(drainTasksForTesting().length, 0, 'does not leave another continuation queued');
+ t.end();
+});
+
test('#composerStateReducer - replaceDataInMapUpdater keeps the original dataset when asked', t => {
const dataIdToReplace = 'dataset_to_replace';
const datasets = {
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index 993a43629..db4d57948 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -8547,6 +8547,7 @@ test('#visStateReducer -> deferred empty queue stages the parsed files', t => {
test('#visStateReducer -> deferred arrow batches are not added early', t => {
drainTasksForTesting();
+ const previousProgressiveLoading = getApplicationConfig().useArrowProgressiveLoading;
const batch = {
gen: {next: () => Promise.resolve({done: true, value: null})},
fileName: 'data.arrow',
@@ -8554,24 +8555,38 @@ test('#visStateReducer -> deferred arrow batches are not added early', t => {
accumulated: {data: [{value: 1}], fileName: 'data.arrow'},
onFinish: VisStateActions.stageLoadedFiles
};
- reducer(
- CloneDeep(InitialState).visState,
- VisStateActions.nextFileBatch({...batch, options: {deferAddToMap: true}})
- );
- const deferredTasks = drainTasksForTesting();
- t.equal(
- deferredTasks.some(task => task.type === 'PROCESS_FILE_CONTENT'),
- false,
- 'a deferred arrow file waits until parsing finishes'
- );
+ try {
+ reducer(
+ CloneDeep(InitialState).visState,
+ VisStateActions.nextFileBatch({...batch, options: {deferAddToMap: true}})
+ );
+ const deferredTasks = drainTasksForTesting();
+ t.equal(
+ deferredTasks.some(task => task.type === 'PROCESS_FILE_CONTENT'),
+ false,
+ 'a deferred arrow file waits until parsing finishes'
+ );
- reducer(CloneDeep(InitialState).visState, VisStateActions.nextFileBatch(batch));
- const immediateTasks = drainTasksForTesting();
- t.equal(
- immediateTasks.some(task => task.type === 'PROCESS_FILE_CONTENT'),
- true,
- 'an arrow file still adds each batch when it is not deferred'
- );
+ initApplicationConfig({useArrowProgressiveLoading: false});
+ reducer(CloneDeep(InitialState).visState, VisStateActions.nextFileBatch(batch));
+ const disabledTasks = drainTasksForTesting();
+ t.equal(
+ disabledTasks.some(task => task.type === 'PROCESS_FILE_CONTENT'),
+ false,
+ 'an arrow file waits until parsing finishes when progressive loading is disabled'
+ );
+
+ initApplicationConfig({useArrowProgressiveLoading: true});
+ reducer(CloneDeep(InitialState).visState, VisStateActions.nextFileBatch(batch));
+ const immediateTasks = drainTasksForTesting();
+ t.equal(
+ immediateTasks.some(task => task.type === 'PROCESS_FILE_CONTENT'),
+ true,
+ 'an arrow file still adds each batch when it is not deferred'
+ );
+ } finally {
+ initApplicationConfig({useArrowProgressiveLoading: previousProgressiveLoading});
+ }
t.end();
});
diff --git a/test/node/utils/data-container-test.js b/test/node/utils/data-container-test.js
index 78ccca7f6..8d99b3f7b 100644
--- a/test/node/utils/data-container-test.js
+++ b/test/node/utils/data-container-test.js
@@ -284,6 +284,66 @@ test('ArrowDataContainer -> update does not collapse record batches', t => {
t.end();
});
+test('ArrowDataContainer -> worker GeoArrow cache follows progressive chunks', t => {
+ const batchA = arrow.tableFromJSON([{value: 1}]);
+ const batchB = arrow.tableFromJSON([{value: 2}]);
+ const featureTypes = {point: true, line: false, polygon: false};
+ const cachedA = {
+ binaryGeometries: ['a'],
+ bounds: [0, 0, 0, 0],
+ featureTypes,
+ meanCenters: [[0, 0]]
+ };
+ const cachedB = {
+ binaryGeometries: ['b'],
+ bounds: [1, 1, 1, 1],
+ featureTypes,
+ meanCenters: [[1, 1]]
+ };
+ const dc = new ArrowDataContainer({
+ cols: [batchA.getChildAt(0)],
+ fields: [{name: 'value', fieldIdx: 0}],
+ arrowTable: batchA,
+ geoArrowBinaryData: {0: {0: cachedA}}
+ });
+
+ const combined = batchA.concat(batchB);
+ dc.update(combined, {geoArrowBinaryData: {0: {1: cachedB}}});
+
+ t.equal(dc.getGeoArrowBinaryData(0, 0), cachedA, 'should retain the first parsed chunk');
+ t.equal(dc.getGeoArrowBinaryData(0, 1), cachedB, 'should append the new parsed chunk');
+ t.deepEqual(
+ dc.getGeoArrowBinaryData(0).binaryGeometries,
+ ['a', 'b'],
+ 'should expose all cached chunks in record-batch order'
+ );
+
+ const compacted = compactArrowTable(combined, 1);
+ const compactedCache = {...cachedA, binaryGeometries: ['all'], meanCenters: [[0.5, 0.5]]};
+ dc.update(compacted, {geoArrowBinaryData: {0: {0: compactedCache}}});
+ t.equal(
+ dc.getGeoArrowBinaryData(0, 0),
+ compactedCache,
+ 'compaction should replace cache entries because chunk indexes reset'
+ );
+ t.equal(dc.getGeoArrowBinaryData(0, 1), undefined, 'stale progressive chunks should be removed');
+
+ const largeMeanCenters = Array.from({length: 150000}, (_, index) => [index, index]);
+ const largeCache = {...compactedCache, meanCenters: largeMeanCenters};
+ dc.update(compacted, {geoArrowBinaryData: {0: {0: largeCache}}});
+ let combinedCache;
+ t.doesNotThrow(() => {
+ combinedCache = dc.getGeoArrowBinaryData(0);
+ }, 'large compacted centroid caches should not overflow the call stack');
+ t.equal(
+ combinedCache.meanCenters.length,
+ largeMeanCenters.length,
+ 'large compacted centroid caches should keep every center'
+ );
+
+ t.end();
+});
+
function finishArrowVector(builder) {
const finished = builder.finish();
if (finished instanceof arrow.Vector) {
diff --git a/test/node/utils/layer-utils-test.js b/test/node/utils/layer-utils-test.js
index d39785c1a..7b66a3f5e 100644
--- a/test/node/utils/layer-utils-test.js
+++ b/test/node/utils/layer-utils-test.js
@@ -4,8 +4,8 @@
import test from 'tape';
import cloneDeep from 'es-toolkit/compat/cloneDeep';
import {processCsvData, processGeojson} from '@kepler.gl/processors';
-import {LayerClasses, KeplerGlLayers} from '@kepler.gl/layers';
-import {GEOJSON_FIELDS} from '@kepler.gl/constants';
+import {getGeojsonLayerMetaFromArrow, LayerClasses, KeplerGlLayers} from '@kepler.gl/layers';
+import {GEOARROW_EXTENSIONS, GEOARROW_METADATA_KEY, GEOJSON_FIELDS} from '@kepler.gl/constants';
import {findDefaultLayer, getLayerHoverProp, getLayerOrderFromLayers} from '@kepler.gl/reducers';
import {StateWTripGeojson, StateWFiles} from 'test/helpers/mock-state';
@@ -18,7 +18,39 @@ import {createNewDataEntryMock} from 'test/helpers/table-utils';
import tripGeojson, {timeStampDomain, tripBounds} from 'test/fixtures/trip-geojson';
import {geoJsonWithStyle} from 'test/fixtures/geojson';
import {KeplerTable, findPointFieldPairs} from '@kepler.gl/table';
-import {createDataContainer} from '@kepler.gl/utils';
+import {ArrowDataContainer, createDataContainer} from '@kepler.gl/utils';
+import * as arrow from 'apache-arrow';
+
+test('layerUtils -> getGeojsonLayerMetaFromArrow uses worker-prepared data', t => {
+ const pointType = new arrow.FixedSizeList(2, new arrow.Field('xy', new arrow.Float64(), false));
+ const geoColumn = arrow.vectorFromArray([[-122.4, 37.8]], pointType);
+ const metadata = new Map([[GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT]]);
+ const fields = [{name: 'geometry', type: 'geoarrow', fieldIdx: 0, metadata}];
+ const cachedGeometry = {shape: 'worker-result'};
+ const cached = {
+ binaryGeometries: [cachedGeometry],
+ bounds: [-122.4, 37.8, -122.4, 37.8],
+ featureTypes: {point: true, line: false, polygon: false},
+ meanCenters: [[-122.4, 37.8]]
+ };
+ const dataContainer = new ArrowDataContainer({
+ cols: [geoColumn],
+ fields,
+ geoArrowBinaryData: {0: {0: cached}}
+ });
+
+ const result = getGeojsonLayerMetaFromArrow({
+ dataContainer,
+ geoColumn: dataContainer.getColumn(0),
+ geoField: fields[0],
+ columnIndex: 0
+ });
+
+ t.equal(result.dataToFeature[0], cachedGeometry, 'should reuse the worker binary geometry');
+ t.deepEqual(result.bounds, cached.bounds, 'should reuse worker-computed bounds');
+ t.deepEqual(result.centroids, cached.meanCenters, 'should reuse worker-computed centroids');
+ t.end();
+});
test('layerUtils -> findDefaultLayer.1', t => {
const inputFields = [