Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Bug] fix filtering and saving of derived Int64 datasets (#3885)
Igor Dykhtad184ed1697c1
diff --git a/AGENTS.md b/AGENTS.mdindex a30926181..84ce580df 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -71,6 +71,10 @@ Ask first for a public API change, saved-config compatibility, product behavior,## Pull requests+After an authorized push, verify it succeeded and confirm the remote commit SHA, then report completion immediately. Do not wait for or poll GitHub checks (including DCO, GitBook, Netlify previews, redirect/header/page checks, and Node.js CI), or start background CI monitors, by default. Monitor checks only when the user explicitly requests it or the task specifically requires their terminal outcome.++Required local tests, type checks, lint, and review must still be completed before publishing. Report pending checks as pending; never claim they passed.+Keep PR descriptions short:- What changed and whydiff --git a/src/reducers/src/dataset-ops-updaters.spec.ts b/src/reducers/src/dataset-ops-updaters.spec.tsindex f331616f6..6a507ec8b 100644--- a/src/reducers/src/dataset-ops-updaters.spec.ts+++ b/src/reducers/src/dataset-ops-updaters.spec.ts@@ -4,7 +4,10 @@import {ALL_FIELD_TYPES} from '@kepler.gl/constants';import {VisStateActions} from '@kepler.gl/actions';import {KeplerTable} from '@kepler.gl/table';-import {processCsvData} from '@kepler.gl/processors';+import {processArrowTable, processCsvData, processKeplerglJSON} from '@kepler.gl/processors';+import {Int64, Table, vectorFromArray} from 'apache-arrow';+import {ProtoDataset} from '@kepler.gl/types';+import {exportMapToHTML, exportToJsonString, validateInputData} from '@kepler.gl/utils';import SchemaManager, {VisState} from '@kepler.gl/schemas';import {drainTasksForTesting, succeedTaskWithValues} from '@kepler.gl/tasks';import {Response} from 'node-fetch';@@ -101,6 +104,90 @@ describe('dataset ops vis-state', () => {expect(state.datasets[resultId].dataContainer.numRows()).toBe(2);});+ test.each([false, true])(+ 'joined BigInts filter and save after source removal (mixed: %s)',+ mixed => {+ const arrow = new Table({+ key: vectorFromArray(['a', 'b', null]),+ pop: vectorFromArray([10n, 20n, null], new Int64())+ });+ const arrowData = processArrowTable({shape: 'arrow-table', data: arrow});+ if (!arrowData) throw new Error('Invalid Arrow fixture');+ const left = new KeplerTable({info: {id: 'left'}, color: [0, 0, 0]}).updateSchema(+ mixed+ ? {+ fields: arrowData.fields,+ rows: [+ ['a', 10n],+ ['b', 20],+ [null, 0.5]+ ]+ }+ : arrowData+ );+ const right = makeTable('right', [{name: 'key', type: 'string'}], [['a'], ['b']]);+ let state: VisState = {...INITIAL_VIS_STATE, datasets: {left, right}};+ state = reduceVisState(state, VisStateActions.addJoin('left'));+ const op = state.joins[0];+ state = reduceVisState(+ state,+ VisStateActions.setJoinConfig(op.id, {+ rightDataId: 'right',+ leftField: 'key',+ rightField: 'key',+ rightColumns: []+ })+ );+ state = flushCreateTableTasks(reduceVisState(state, VisStateActions.runJoin(op.id)));+ state = reduceVisState(state, VisStateActions.addFilter(op.resultId));+ state = reduceVisState(state, VisStateActions.setFilter(0, 'name', 'pop'));+ expect(state.filters[0].domain).toEqual([10, 20]);+ state = reduceVisState(state, VisStateActions.setFilter(0, 'gpu', false));+ state = reduceVisState(state, VisStateActions.setFilter(0, 'value', [15, 20]));+ expect(state.datasets[op.resultId].filteredIndex).toEqual([1]);++ for (const removeSources of [false, true]) {+ if (removeSources) {+ state = reduceVisState(state, VisStateActions.removeDataset('left'));+ state = reduceVisState(state, VisStateActions.removeDataset('right'));+ expect(Object.keys(state.datasets)).toEqual([op.resultId]);+ }+ const saved = SchemaManager.save({visState: state});+ const json = JSON.parse(exportToJsonString(saved));+ const embedded = JSON.parse(+ exportMapToHTML(saved).match(/const datasets = (.*);/)?.[1] || ''+ );+ expect(embedded).toEqual(json.datasets);+ const parsed: ProtoDataset | undefined = processKeplerglJSON(json)?.datasets?.find(+ dataset => dataset.info.id === op.resultId+ );+ if (!parsed) throw new Error('Missing derived dataset after reload');+ const data = validateInputData(parsed.data);+ if (!data) throw new Error('Invalid derived dataset after reload');+ const reloaded = new KeplerTable({+ info: parsed.info,+ metadata: parsed.metadata,+ color: [0, 0, 0]+ }).updateSchema(data);+ expect(reloaded.getColumnFilterProps('pop')?.domain).toEqual([10, 20]);+ expect(reloaded.dataContainer.flattenData()).toEqual([+ ['a', 10],+ ['b', 20],+ [null, null]+ ]);+ expect(state.datasets[op.resultId].dataContainer.flattenData()).toEqual([+ ['a', 10n],+ ['b', 20n],+ [null, null]+ ]);+ }+ expect([0, 1, 2].map(index => arrow.getChild('pop')?.get(index))).toEqual([10n, 20n, null]);+ expect([0, 1, 2].map(index => left.dataContainer.valueAt(index, 1))).toEqual(+ mixed ? [10n, 20, 0.5] : [10n, 20n, null]+ );+ }+ );+test.each(['minimum', 'maximum'] as const)('runGroupBy selects chronological %s from recognized CSV timestamps',technique => {diff --git a/src/schemas/src/dataset-schema.ts b/src/schemas/src/dataset-schema.tsindex d076cd3e7..54017af31 100644--- a/src/schemas/src/dataset-schema.ts+++ b/src/schemas/src/dataset-schema.ts@@ -150,6 +150,24 @@ const getAllDataForSaving = (dataContainer: DataContainerInterface): any[][] =>});}}+ } else {+ // Row containers expose their live backing rows. Copy only when conversion+ // is needed, leaving other rows and exact stored values intact.+ let savedData = allData;+ for (let rowIndex = 0; rowIndex < allData.length; rowIndex++) {+ const row = allData[rowIndex];+ if (row == null) continue;+ let savedRow = row;+ for (let columnIndex = 0; columnIndex < row.length; columnIndex++) {+ const value = row[columnIndex];+ if (typeof value !== 'bigint') continue;+ if (savedData === allData) savedData = allData.slice();+ if (savedRow === row) savedRow = savedData[rowIndex] = row.slice();+ const number = Number(value);+ savedRow[columnIndex] = Number.isSafeInteger(number) ? number : value.toString();+ }+ }+ return savedData;}return allData;diff --git a/src/table/src/dataset-ops.spec.ts b/src/table/src/dataset-ops.spec.tsindex 123320c1d..c16da2553 100644--- a/src/table/src/dataset-ops.spec.ts+++ b/src/table/src/dataset-ops.spec.ts@@ -5,6 +5,7 @@ import {ALL_FIELD_TYPES} from '@kepler.gl/constants';import {latLngToCell} from '@kepler.gl/common-utils';import {Int64, Table, Uint64, vectorFromArray} from 'apache-arrow';import {Response} from 'node-fetch';+import {ProtoDataset} from '@kepler.gl/types';import KeplerTable from './kepler-table';import {aggregateValues} from './dataset-ops/aggregations';@@ -17,6 +18,7 @@ import {canMutateDatasetSchema,isTabularDatasetForOps,joinDatasets,+ makeResultProtoDataset,spatialJoinDatasets,defaultSuitabilityWeights,isSuitabilityWeightField,@@ -63,6 +65,14 @@ function makeInt64Data(values: (bigint | null)[], type: Int64 | Uint64 = new Int};}+function importDerived(result: ProtoDataset) {+ return new KeplerTable({+ info: result.info,+ metadata: result.metadata,+ color: [0, 0, 0]+ }).updateSchema(result.data);+}+const square = (west: number, south: number, east: number, north: number) => ({type: 'Feature',properties: {},@@ -89,6 +99,37 @@ describe('dataset-ops engine', () => {globalThis.Response = originalResponse;});+ test.each([undefined, true, false])(+ 'makeResultProtoDataset supports normalizeBigInts=%s without changing source values',+ normalizeBigInts => {+ const values = [10n, 20, 0.5, null, 9007199254740993n];+ const source = makeTable({+ id: 'source',+ fields: [{name: 'value', type: ALL_FIELD_TYPES.integer}],+ rows: values.map(value => [value])+ });+ const result = makeResultProtoDataset({+ source,+ type: 'join',+ operationId: 'normalization-option',+ label: 'result',+ fields: [{name: 'value', type: ALL_FIELD_TYPES.integer, analyzerType: 'INT'}],+ rows: values.map(value => [value]),+ ...(normalizeBigInts === undefined ? {} : {normalizeBigInts})+ });+ const enabled = normalizeBigInts === true;+ expect(result.data.rows).toEqual(+ (enabled ? [10n, 20n, null, null, 9007199254740993n] : values).map(value => [value])+ );+ const derived = importDerived(result);+ expect(values.map((_, index) => derived.getValue('value', index))).toEqual(+ enabled ? [10, 20, null, null, 9007199254740992] : values+ );+ expect(source.dataContainer.flattenData()).toEqual(values.map(value => [value]));+ expect(source.getValue('value', 0)).toBe(10n);+ }+ );+test('groupByDataset aggregates numeric and unique string values', () => {const dataset = makeTable({id: 'cities',@@ -409,6 +450,260 @@ describe('dataset-ops engine', () => {expect(result.data.rows[0]).toEqual(['sf']);});+ describe.each([new Int64(), new Uint64()])('derived Arrow %s numeric access', arrowType => {+ test.each(['LEFT', 'INNER', 'FULL'] as const)(+ '%s join preserves raw values on both sides',+ type => {+ const left = new KeplerTable({info: {id: 'left'}, color: [0, 0, 0]}).updateSchema(+ makeInt64Data([10n, 20n, null], arrowType)+ );+ const right = new KeplerTable({+ info: {id: 'right', label: 'right'},+ color: [0, 0, 0]+ }).updateSchema(makeInt64Data([10n, 20n, 30n, null], arrowType));+ const result = joinDatasets(left, right, {leftField: 'pop', rightField: 'pop', type});+ const table = importDerived(result);+ const raw = table.dataContainer.flattenData().map(row => [row[1], row[3]]);+ expect(raw).toEqual([+ [10n, 10n],+ [20n, 20n],+ ...(type !== 'INNER' ? [[null, null]] : []),+ ...(type === 'FULL'+ ? [+ [null, 30n],+ [null, null]+ ]+ : [])+ ]);+ for (const index of [1, 3]) {+ const field = table.fields[index];+ expect(table.getColumnFilterProps(field.name)?.domain).toEqual(+ index === 3 && type === 'FULL' ? [10, 30] : [10, 20]+ );+ expect(field.valueAccessor({index: 0})).toBe(10);+ const accessRow = field.valueAccessor as (row: {index: number} | any[]) => unknown;+ expect(accessRow(table.dataContainer.rowAsArray(0))).toBe(10);+ expect(table.getColumnLayerDomain(field, 'linear')).toEqual(+ index === 3 && type === 'FULL' ? [10, 30] : [10, 20]+ );+ }+ expect(table.dataContainer.flattenData().map(row => [row[1], row[3]])).toEqual(raw);+ expect([0, 1, 2].map(index => left.dataContainer.valueAt(index, 1))).toEqual([+ 10n,+ 20n,+ null+ ]);+ }+ );+ });++ test.each([true, false])('numeric access keeps unsafe join keys exact (Arrow: %s)', useArrow => {+ const values = [9007199254740992n, 9007199254740993n];+ const data = makeInt64Data(values);+ const source = new KeplerTable({info: {id: 'large'}, color: [0, 0, 0]}).updateSchema(+ useArrow ? data : {fields: data.fields, rows: values.map(value => ['west', value])}+ );+ const table = importDerived(+ joinDatasets(source, source, {+ leftField: 'pop',+ rightField: 'pop',+ type: 'INNER'+ })+ );+ expect(table.dataContainer.numRows()).toBe(2);+ expect([0, 1].map(index => table.dataContainer.valueAt(index, 1))).toEqual([+ 9007199254740992n,+ 9007199254740993n+ ]);+ expect([0, 1].map(index => table.fields[1].valueAccessor({index}))).toEqual([+ 9007199254740992, 9007199254740992+ ]);+ expect(+ joinDatasets(table, source, {leftField: 'pop', rightField: 'pop', type: 'INNER'}).data.rows+ ).toHaveLength(2);+ });++ test.each([[], [null, null], [10, 20, null]].map(values => [values]))(+ 'derived numeric columns without BigInts stay unchanged: %j',+ values => {+ const rows = values.map((value, index) => [String(index), value]);+ const source = makeTable({+ id: 'numeric',+ fields: [+ {name: 'id', type: 'string'},+ {name: 'pop', type: 'integer'}+ ],+ rows+ });+ const table = importDerived(+ joinDatasets(source, source, {+ leftField: 'id',+ rightField: 'id',+ type: 'LEFT',+ rightColumns: []+ })+ );+ expect(table.dataContainer.flattenData()).toEqual(rows);+ expect(values.map((_, index) => table.getValue('pop', index))).toEqual(values);+ expect(() => table.getColumnFilterProps('pop')).not.toThrow();+ }+ );++ test.each(['integer', 'real'])(+ 'derived %s BigInt columns normalize incompatible cells to null',+ type => {+ const values = [+ null,+ 10n,+ 20,+ 0.5,+ NaN,+ Infinity,+ -Infinity,+ Number.MAX_SAFE_INTEGER + 1,+ '30',+ true,+ undefined,+ -0,+ -42+ ];+ const expected = [null, 10n, 20n, null, null, null, null, null, null, null, null, 0n, -42n];+ const geometry = square(0, 0, 1, 1);+ const rows = values.map((value, index) => [String(index), value, index + 0.5, geometry]);+ const original = rows.map(row => row.slice());+ const source = makeTable({+ id: 'mixed',+ fields: [+ {name: 'id', type: 'string'},+ {name: 'value', type},+ {name: 'ordinary', type: 'real'},+ {name: 'geometry', type: 'geojson'}+ ],+ rows+ });+ const joined = importDerived(+ joinDatasets(source, source, {+ leftField: 'id',+ rightField: 'id',+ type: 'INNER',+ rightColumns: ['value']+ })+ );+ expect(joined.length).toBe(values.length);+ for (const column of [1, 4]) {+ expect(values.map((_, index) => joined.dataContainer.valueAt(index, column))).toEqual(+ expected+ );+ const field = joined.fields[column];+ expect(joined.getColumnFilterProps(field.name)?.domain).toEqual([-42, 20]);+ expect(joined.getColumnLayerDomain(field, 'linear')).toEqual([-42, 20]);+ expect(expected.map((_, index) => field.valueAccessor({index}))).toEqual(+ expected.map(value => (value === null ? null : Number(value)))+ );+ }+ expect(joined.dataContainer.valueAt(3, 2)).toBe(3.5);+ expect(joined.dataContainer.valueAt(3, 3)).toBe(geometry);+ const grouped = importDerived(+ groupByDataset(source, {+ fieldName: 'id',+ aggregations: {value: 'maximum'}+ })+ );+ expect(grouped.length).toBe(values.length);+ expect(values.map((_, index) => grouped.dataContainer.valueAt(index, 1))).toEqual(expected);+ expect(source.dataContainer.flattenData()).toEqual(original);+ expect(Object.is(source.dataContainer.valueAt(11, 1), -0)).toBe(true);+ }+ );++ test('derived BigInt normalization accepts safe Number boundaries only in numeric fields', () => {+ const values = [+ 10n,+ Number.MIN_SAFE_INTEGER,+ Number.MAX_SAFE_INTEGER,+ Number.MIN_SAFE_INTEGER - 1,+ Number.MAX_SAFE_INTEGER + 1+ ];+ const rows = values.map((value, index) => [String(index), value, value]);+ const source = makeTable({+ id: 'boundaries',+ fields: [+ {name: 'id', type: 'string'},+ {name: 'value', type: 'integer'},+ {name: 'text', type: 'string'}+ ],+ rows+ });+ const result = importDerived(+ joinDatasets(source, source, {+ leftField: 'id',+ rightField: 'id',+ type: 'INNER',+ rightColumns: []+ })+ );+ expect(values.map((_, index) => result.dataContainer.valueAt(index, 1))).toEqual([+ 10n,+ -9007199254740991n,+ 9007199254740991n,+ null,+ null+ ]);+ expect(values.map((_, index) => result.getValue('text', index))).toEqual(values);+ expect(source.dataContainer.flattenData()).toEqual(rows);+ });++ test('derived Group By and suitability retain exact cells with numeric access', () => {+ const source = new KeplerTable({info: {id: 'source'}, color: [0, 0, 0]}).updateSchema(+ makeInt64Data([10n, 20n, null])+ );+ const results = [+ groupByDataset(source, {fieldName: 'pop', aggregations: {region: 'count'}}),+ groupByDataset(source, {fieldName: 'region', aggregations: {pop: 'maximum'}}),+ suitabilityDataset(source, {weights: {pop: 1}})+ ];+ for (const result of results) {+ const table = importDerived(result);+ for (const field of table.fields.filter(+ field => field.type === 'integer' || field.type === 'real'+ )) {+ for (let index = 0; index < table.dataContainer.numRows(); index++) {+ const raw = table.dataContainer.valueAt(index, field.fieldIdx);+ expect(field.valueAccessor({index})).toBe(typeof raw === 'bigint' ? Number(raw) : raw);+ }+ expect(() => table.getColumnFilterProps(field.name)).not.toThrow();+ }+ expect(table.dataContainer.flattenData()).toEqual(result.data.rows);+ }+ expect(source.dataContainer.valueAt(1, 1)).toBe(20n);+ });++ test('spatial join copied integers and extrema retain numeric access', () => {+ const polygons = makeTable({+ id: 'polygons',+ fields: [+ {name: 'geom', type: 'geojson'},+ {name: 'pop', type: 'integer'}+ ],+ rows: [+ [square(0, 0, 1, 1), 10n],+ [square(2, 2, 3, 3), 20n]+ ]+ });+ const result = spatialJoinDatasets(polygons, polygons, {+ leftGeo: {kind: 'geojson', fieldName: 'geom'},+ rightGeo: {kind: 'geojson', fieldName: 'geom'},+ aggregations: {pop: 'maximum'}+ });+ const table = importDerived(result);+ for (const name of ['pop', 'pop_maximum']) {+ expect(table.getColumnFilterProps(name)?.domain).toEqual([10, 20]);+ expect(table.getValue(name, 0)).toBe(10);+ expect(table.dataContainer.valueAt(0, table.getColumnFieldIdx(name))).toBe(10n);+ }+ expect(polygons.dataContainer.valueAt(1, 1)).toBe(20n);+ });+test.each([{format: 'GeoJSON', west: square(-10, -10, 10, 10), east: square(20, -10, 40, 10)},{diff --git a/src/table/src/dataset-ops/column-edit.spec.ts b/src/table/src/dataset-ops/column-edit.spec.tsindex 6e15ed6b5..e62aed1de 100644--- a/src/table/src/dataset-ops/column-edit.spec.ts+++ b/src/table/src/dataset-ops/column-edit.spec.ts@@ -3,7 +3,8 @@import {ALL_FIELD_TYPES} from '@kepler.gl/constants';import {createArrowVector} from '@kepler.gl/utils';-import KeplerTable from '../kepler-table';+import KeplerTable, {getFieldValueAccessor} from '../kepler-table';+import {joinDatasets} from './join';import {buildChangeColumnTypeData,buildDeleteColumnData,@@ -47,6 +48,42 @@ function makeColumnTable(}describe('column edit payloads', () => {+ test('derived BigInt representation survives projection and clears on type conversion', () => {+ const source = makeColumnTable([10n, null, 9007199254740993n], ALL_FIELD_TYPES.integer);+ const proto = joinDatasets(source, source, {+ leftField: 'value',+ rightField: 'value',+ type: 'LEFT',+ rightColumns: []+ });+ const derived = new KeplerTable({color: [0, 0, 0]}).updateSchema(proto.data);+ const renamed = buildRenameColumnData(derived, 'value', 'renamed');+ if (!renamed) throw new Error('Missing renamed dataset');+ const projected = new KeplerTable({color: [0, 0, 0]}).updateSchema(renamed.data);+ expect(projected.dataContainer.flattenData()).toEqual([[10n], [null], [9007199254740993n]]);+ expect([0, 1, 2].map(index => projected.getValue('renamed', index))).toEqual([+ 10,+ null,+ 9007199254740992+ ]);+ const timestampAccessor = getFieldValueAccessor(+ {...projected.fields[0], type: ALL_FIELD_TYPES.timestamp, format: 'YYYY-MM-DD'},+ 0,+ projected.dataContainer+ );+ expect(timestampAccessor(['2020-01-01'])).toBe(Date.UTC(2020, 0, 1));+ const converted = buildChangeColumnTypeData(projected, 'renamed', ALL_FIELD_TYPES.string);+ expect(converted?.error).toBeUndefined();+ if (!converted?.payload) throw new Error('Missing converted dataset');+ const strings = new KeplerTable({color: [0, 0, 0]}).updateSchema(converted.payload.data);+ expect([0, 1, 2].map(index => strings.getValue('renamed', index))).toEqual([+ '10',+ null,+ '9007199254740993'+ ]);+ expect(derived.dataContainer.flattenData()).toEqual([[10n], [null], [9007199254740993n]]);+ });+test('rename keeps values and records the old name', () => {const payload = buildRenameColumnData(makeTable(), 'region', 'area');expect(payload?.renames).toEqual({region: 'area'});diff --git a/src/table/src/dataset-ops/column-edit.ts b/src/table/src/dataset-ops/column-edit.tsindex 287d9e1ef..35734f915 100644--- a/src/table/src/dataset-ops/column-edit.ts+++ b/src/table/src/dataset-ops/column-edit.ts@@ -5,6 +5,7 @@ import {Analyzer, DATA_TYPES as AnalyzerDataTypes} from 'type-analyzer';import {ALL_FIELD_TYPES} from '@kepler.gl/constants';import {Field, ProtoDataset} from '@kepler.gl/types';import {createArrowVector, DataContainerInterface} from '@kepler.gl/utils';+import {clearBigIntColumn} from './normalize-bigint-columns';export type ColumnEditDataset = {fields: Field[];@@ -438,6 +439,9 @@ export function buildChangeColumnTypeData(};});+ // Converted cells no longer have the derived column's BigInt representation.+ clearBigIntColumn(fields[fieldIndex]);+if (typeof dataset.dataContainer.getColumn === 'function') {const cols = dataset.fields.map((_, index) => dataset.dataContainer.getColumn?.(index));if (cols.every(Boolean)) {diff --git a/src/table/src/dataset-ops/group-by.ts b/src/table/src/dataset-ops/group-by.tsindex 5cd423fd6..a474a6b12 100644--- a/src/table/src/dataset-ops/group-by.ts+++ b/src/table/src/dataset-ops/group-by.ts@@ -102,6 +102,7 @@ export function groupByDataset(label: config.label || `group-by-${config.resultId || generateHashId(6)}`,resultId: config.resultId,fields,- rows+ rows,+ normalizeBigInts: true});}diff --git a/src/table/src/dataset-ops/join.ts b/src/table/src/dataset-ops/join.tsindex 3e323036c..86ee03fdc 100644--- a/src/table/src/dataset-ops/join.ts+++ b/src/table/src/dataset-ops/join.ts@@ -106,6 +106,7 @@ export function joinDatasets(label: config.label || `join-dataset-${config.resultId || generateHashId(6)}`,resultId: config.resultId,fields,- rows+ rows,+ normalizeBigInts: true});}diff --git a/src/table/src/dataset-ops/normalize-bigint-columns.ts b/src/table/src/dataset-ops/normalize-bigint-columns.tsnew file mode 100644index 000000000..aa5fef909--- /dev/null+++ b/src/table/src/dataset-ops/normalize-bigint-columns.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {ALL_FIELD_TYPES} from '@kepler.gl/constants';+import {ProtoDatasetField} from '@kepler.gl/types';++// Runtime physical representation, preserved by field copies but omitted from+// saved schemas.+const BIGINT_COLUMN = Symbol('bigintColumn');++/** Whether a derived numeric field stores normalized BigInt values. */+export function columnContainsBigInts(field: object): boolean {+ return (field as {[BIGINT_COLUMN]?: boolean})[BIGINT_COLUMN] === true;+}++/** Clear the representation marker after an explicit column type conversion. */+export function clearBigIntColumn(field: object): void {+ Reflect.deleteProperty(field, BIGINT_COLUMN);+}++/** Normalize newly built derived rows, never their source datasets. */+export function normalizeBigIntColumns(+ fields: ProtoDatasetField[],+ rows: any[][]+): ProtoDatasetField[] {+ return fields.map((field, column) => {+ if (+ (field.type !== ALL_FIELD_TYPES.integer && field.type !== ALL_FIELD_TYPES.real) ||+ !rows.some(row => typeof row[column] === 'bigint')+ ) {+ return field;+ }++ for (const row of rows) {+ const value = row[column];+ // A BigInt column accepts exact safe integers (including -0 as 0n).+ // Fractions, unsafe Numbers and other incompatible values become missing.+ row[column] =+ typeof value === 'bigint'+ ? value+ : typeof value === 'number' && Number.isSafeInteger(value)+ ? BigInt(value)+ : null;+ }+ return {...field, [BIGINT_COLUMN]: true};+ });+}diff --git a/src/table/src/dataset-ops/proto-dataset.ts b/src/table/src/dataset-ops/proto-dataset.tsindex f1e706e9a..8e4974944 100644--- a/src/table/src/dataset-ops/proto-dataset.ts+++ b/src/table/src/dataset-ops/proto-dataset.ts@@ -6,6 +6,7 @@ import {generateHashId} from '@kepler.gl/common-utils';import {ProtoDataset, ProtoDatasetField} from '@kepler.gl/types';import {DatasetOpsTable, DerivedDatasetMetadata} from './types';+import {normalizeBigIntColumns} from './normalize-bigint-columns';export function uniqueColumnName(name: string, used: Set<string>): string {if (!used.has(name)) {@@ -30,7 +31,8 @@ export function makeResultProtoDataset({label,resultId,fields,- rows+ rows,+ normalizeBigInts = false}: {source: DatasetOpsTable;extraSources?: DatasetOpsTable[];@@ -40,6 +42,8 @@ export function makeResultProtoDataset({resultId?: string;fields: ProtoDatasetField[];rows: any[][];+ /** Opt in to normalizing and marking numeric BigInt columns; defaults to false. */+ normalizeBigInts?: boolean;}): ProtoDataset {const id = resultId || generateHashId(6);return {@@ -47,7 +51,7 @@ export function makeResultProtoDataset({id,label},- data: {fields, rows},+ data: {fields: normalizeBigInts ? normalizeBigIntColumns(fields, rows) : fields, rows},metadata: {derivedDataset: {type,diff --git a/src/table/src/dataset-ops/spatial-join.ts b/src/table/src/dataset-ops/spatial-join.tsindex 497aa307c..cc87c6890 100644--- a/src/table/src/dataset-ops/spatial-join.ts+++ b/src/table/src/dataset-ops/spatial-join.ts@@ -341,6 +341,7 @@ export function spatialJoinDatasets(label: config.label || `spatial-join-${config.resultId || generateHashId(6)}`,resultId: config.resultId,fields,- rows+ rows,+ normalizeBigInts: true});}diff --git a/src/table/src/dataset-ops/suitability.ts b/src/table/src/dataset-ops/suitability.tsindex b5033f87c..30a7b0efb 100644--- a/src/table/src/dataset-ops/suitability.ts+++ b/src/table/src/dataset-ops/suitability.ts@@ -172,6 +172,7 @@ export function suitabilityDataset(label: config.label || `suitability-${config.resultId || generateHashId(6)}`,resultId: config.resultId,fields,- rows+ rows,+ normalizeBigInts: true});}diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.tsindex 627fd461c..bb4a9847f 100644--- a/src/table/src/kepler-table.ts+++ b/src/table/src/kepler-table.ts@@ -28,6 +28,7 @@ import {} from '@kepler.gl/types';import {getGpuFilterProps, getDatasetFieldIndexForFilter} from './gpu-filter-utils';+import {columnContainsBigInts} from './dataset-ops/normalize-bigint-columns';import {getSortingFunction,@@ -1051,7 +1052,7 @@ export function getFieldValueAccessor<const format = f.format || '';return (d: {index: number} | any[]) => timeToUnixMilli(readFieldValue(i, dc, d), format);}- if (isInt64ArrowColumn(dc, i)) {+ if (columnContainsBigInts(f) || isInt64ArrowColumn(dc, i)) {return (d: {index: number} | any[]) => {const value = readFieldValue(i, dc, d);return value == null ? value : Number(value);diff --git a/test/node/schemas/dataset-schema-test.js b/test/node/schemas/dataset-schema-test.jsindex 7d095082d..bf8c29ab4 100644--- a/test/node/schemas/dataset-schema-test.js+++ b/test/node/schemas/dataset-schema-test.js@@ -6,7 +6,7 @@ import cloneDeep from 'es-toolkit/compat/cloneDeep';import SchemaManager, {datasetSchema, VERSIONS} from '@kepler.gl/schemas';import {DatasetType, DATASET_FORMATS} from '@kepler.gl/constants';import * as arrow from 'apache-arrow';-import {KeplerTable} from '@kepler.gl/table';+import {KeplerTable, joinDatasets} from '@kepler.gl/table';import {exportToJsonString, exportMapToHTML, validateInputData} from '@kepler.gl/utils';import {processArrowTable, processKeplerglJSON} from '@kepler.gl/processors';@@ -345,6 +345,160 @@ test('#DatasetSchema -> Int64 values survive JSON, HTML and reload without precit.end();});+test('#DatasetSchema -> joined Int64 rows save and reload without changing live rows', t => {+ const values = [+ 0n,+ 10n,+ 20n,+ -9007199254740991n,+ 9007199254740991n,+ -9223372036854775808n,+ 9007199254740992n,+ 9007199254740993n,+ null+ ];+ const source = arrowDataset({+ key: arrow.vectorFromArray(values.map((_, index) => String(index))),+ signed: arrow.vectorFromArray(values, new arrow.Int64()),+ unsigned: arrow.vectorFromArray(+ values.map(value => (value === null ? null : value < 0n ? 18446744073709551615n : value)),+ new arrow.Uint64()+ )+ });+ const proto = joinDatasets(source, source, {+ leftField: 'key',+ rightField: 'key',+ type: 'LEFT',+ rightColumns: []+ });+ const original = proto.data.rows.map(row => [...row]);+ const expected = [+ ['0', 0, 0],+ ['1', 10, 10],+ ['2', 20, 20],+ ['3', -9007199254740991, '18446744073709551615'],+ ['4', 9007199254740991, 9007199254740991],+ ['5', '-9223372036854775808', '18446744073709551615'],+ ['6', '9007199254740992', '9007199254740992'],+ ['7', '9007199254740993', '9007199254740993'],+ ['8', null, null]+ ];+ const dataset = new KeplerTable({+ info: proto.info,+ metadata: proto.metadata,+ color: [0, 0, 0]+ }).updateSchema(proto.data);+ const saved = datasetSchema[VERSIONS.v1].save(dataset);+ t.deepEqual(saved.allData, expected, 'safe numbers and exact unsafe decimal strings');+ t.equal(+ reloadDataset(saved).getValue('signed', 7),+ '9007199254740993',+ 'in-memory saved schema also omits the live BigInt representation'+ );+ t.deepEqual(dataset.dataContainer.flattenData(), original, 'live rows are not mutated');+ t.deepEqual(source.dataContainer.flattenData(), original, 'source Arrow values are not mutated');+ t.doesNotThrow(() => {+ const json = exportToJsonString({+ datasets: [{version: 'v1', data: saved}],+ config: {version: 'v1', config: {}}+ });+ const parsed = processKeplerglJSON(JSON.parse(json)).datasets[0];+ const reloaded = new KeplerTable({+ info: parsed.info,+ metadata: parsed.metadata,+ color: [0, 0, 0]+ }).updateSchema(validateInputData(parsed.data));+ t.deepEqual(reloaded.dataContainer.flattenData(), expected, 'JSON reload retains exact cells');+ t.equal(+ reloaded.fields[1].valueAccessor({index: 7}),+ '9007199254740993',+ 'accepted unsafe-string numeric limitation unchanged'+ );+ t.deepEqual(+ datasetSchema[VERSIONS.v1].save(reloaded).allData,+ expected,+ 'resave retains exact cells'+ );+ const html = exportMapToHTML({+ datasets: [{version: 'v1', data: saved}],+ config: {version: 'v1', config: {}}+ });+ const embedded = JSON.parse(html.match(/const datasets = (.*);/)[1]);+ t.deepEqual(embedded[0].data.allData, expected, 'HTML retains the same exact cells');+ t.deepEqual(+ reloadDataset(embedded[0].data).dataContainer.flattenData(),+ expected,+ 'HTML reload retains exact cells'+ );+ }, 'JSON and HTML exports are valid');+ t.end();+});++test('#DatasetSchema -> string-typed Arrow Int64 joins still export exact values', t => {+ const source = new KeplerTable({info: {id: 'string-arrow'}, color: [0, 0, 0]}).updateSchema({+ fields: [+ {name: 'key', type: 'string'},+ {name: 'value', type: 'string'}+ ],+ rows: [],+ cols: [+ arrow.vectorFromArray(['a', 'b']),+ arrow.vectorFromArray([10n, 9007199254740993n], new arrow.Int64())+ ]+ });+ const proto = joinDatasets(source, source, {+ leftField: 'key',+ rightField: 'key',+ type: 'LEFT',+ rightColumns: []+ });+ const table = new KeplerTable({info: proto.info, color: [0, 0, 0]}).updateSchema(proto.data);+ t.deepEqual(datasetSchema.v1.save(table).allData, [+ ['a', 10],+ ['b', '9007199254740993']+ ]);+ t.equal(table.getValue('value', 1), 9007199254740993n);+ t.end();+});++test('#DatasetSchema -> row numeric controls and empty rows remain unchanged', t => {+ for (const rows of [[], [[null], [null]], [[10], [20], [null]], [[10], null, [], [20]]]) {+ const dataset = new KeplerTable({+ color: [0, 0, 0]+ }).updateSchema({fields: [{name: 'value', type: 'integer', analyzerType: 'INT'}], rows});+ const saved = datasetSchema[VERSIONS.v1].save(dataset);+ t.deepEqual(JSON.parse(exportToJsonString(saved)).allData, rows, 'control saves unchanged');+ t.deepEqual(dataset.dataContainer.flattenData(), rows, 'control source unchanged');+ t.equal(saved.allData, rows, 'no row copy is needed when there are no BigInts');+ }+ t.end();+});++test('#DatasetSchema -> BigInt normalization copies only affected rows and preserves other cells', t => {+ const date = new Date('2020-01-01T00:00:00Z');+ const rows = [null, [10n, date, '9007199254740993'], [20, null, 'unchanged'], null];+ const dataset = new KeplerTable({color: [0, 0, 0]}).updateSchema({+ fields: [+ {name: 'value', type: 'integer'},+ {name: 'date', type: 'date'},+ {name: 'text', type: 'string'}+ ],+ rows+ });+ const saved = datasetSchema[VERSIONS.v1].save(dataset);+ t.notEqual(saved.allData, rows, 'the outer array is copied for a conversion');+ t.deepEqual(+ saved.allData,+ [null, [10, date, '9007199254740993'], rows[2], null],+ 'only BigInt cells change'+ );+ t.notEqual(saved.allData[1], rows[1], 'the affected row is copied');+ t.equal(saved.allData[2], rows[2], 'the unchanged row is reused');+ t.equal(saved.allData[1][1], date, 'row dates are not converted by Arrow temporal handling');+ t.equal(dataset.dataContainer.valueAt(1, 0), 10n, 'live storage remains exact');+ t.end();+});+test('#DatasetSchema -> null Arrow timestamps remain null through save and reload', t => {const dataset = arrowDataset({time: arrow.vectorFromArray([null, 0, 1700000000123], new arrow.TimestampMillisecond())diff --git a/test/node/utils/kepler-table-test.js b/test/node/utils/kepler-table-test.jsindex 8fb7fd0c0..7aa6b5a20 100644--- a/test/node/utils/kepler-table-test.js+++ b/test/node/utils/kepler-table-test.js@@ -6,7 +6,13 @@ import moment from 'moment';import testData, {numericRangesCsv, testFields} from 'test/fixtures/test-csv-data';import {preciseRound, getFilterFunction} from '@kepler.gl/utils';-import {findPointFieldPairs, KeplerTable, createNewDataEntry} from '@kepler.gl/table';+import {+ findPointFieldPairs,+ KeplerTable,+ createNewDataEntry,+ joinDatasets,+ sortDatasetByColumn+} from '@kepler.gl/table';import {processArrowBatches, processCsvData} from '@kepler.gl/processors';import {ALL_FIELD_TYPES, FILTER_TYPES} from '@kepler.gl/constants';import * as arrow from 'apache-arrow';@@ -448,6 +454,51 @@ test('KeplerTable -> Int64 field accessor converts BigInt to number', async t =>t.end();});+test('KeplerTable -> ordinary row access leaves numbers and strings unchanged', t => {+ const rows = [+ [10, 0.5],+ ['9007199254740993', '12'],+ [null, undefined]+ ];+ const table = new KeplerTable({color: [0, 0, 0]}).updateSchema({+ fields: [+ {name: 'integer', type: 'integer'},+ {name: 'real', type: 'real'}+ ],+ rows+ });+ for (const [column, field] of table.fields.entries()) {+ const expected = rows.map(row => row[column]);+ t.deepEqual(+ rows.map((_, index) => field.valueAccessor({index})),+ expected+ );+ t.deepEqual(rows.map(field.valueAccessor), expected, 'materialized rows agree');+ }+ t.deepEqual(table.dataContainer.flattenData(), rows, 'raw storage unchanged');+ t.end();+});++test('KeplerTable -> derived BigInt access preserves exact raw sorting', t => {+ const rows = [[9007199254740993n], [9007199254740992n], [null]];+ const source = new KeplerTable({color: [0, 0, 0]}).updateSchema({+ fields: [{name: 'value', type: 'integer'}],+ rows+ });+ const proto = joinDatasets(source, source, {+ leftField: 'value',+ rightField: 'value',+ type: 'LEFT',+ rightColumns: []+ });+ const table = new KeplerTable({color: [0, 0, 0]}).updateSchema(proto.data);+ t.equal(table.fields[0].valueAccessor({index: 0}), 9007199254740992, 'numeric view can round');+ sortDatasetByColumn(table, 'value', 'ASCENDING');+ t.deepEqual(table.sortOrder, [1, 0, 2], 'sorting distinguishes adjacent unsafe integers');+ t.deepEqual(table.dataContainer.flattenData(), rows, 'sorting leaves exact raw cells intact');+ t.end();+});+test('KeplerTable -> update with arrow cols keeps gpu filter state', async t => {const first = arrow.tableFromArrays({lat: [1, 2],