Skip to content

feat(layers): resolve Scatterplot columns from Arrow tables - #11089

Open
ibgreen wants to merge 4 commits into
masterfrom
codex/arrow-table-resolution
Open

ibgreen wants to merge 4 commits into
masterfrom
codex/arrow-table-resolution

Conversation

@ibgreen

@ibgreen ibgreen commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

For #11069

Change List

  • Resolve compatible ScatterplotLayer table fields by accessor name
  • Preserve explicit Arrow accessors and GPU columns
  • Keep batch conversion and picking aligned with source rows
  • Unit tests and WebGL/WebGPU layer tests
  • Documentation and Query tabs for Arrow-enabled layers

Depends on #11131. Verified with lint, 155 Node tests, and 59 Chromium tests


Note

Low Risk
Low risk changes localized to Arrow column resolution and incremental GPU chunk uploads, with no impact on standard data paths or security.

Overview
Enables ScatterplotLayer to automatically resolve GPU columns directly from Arrow table fields that match accessor names (such as getPosition or getRadius), without requiring explicit Arrow vector props.

Updates LayerColumns to support incremental Arrow chunk uploads, reusing previously converted GPU buffers for unchanged chunk prefixes across data updates. Also improves Arrow list unpacking in accessor fallbacks and adds documentation with new Query tab examples demonstrating SQL accessors across multiple layer reference pages.

Reviewed by Cursor Bugbot for commit b89f058. Bugbot is set up for automated code reviews on this repo. Configure here.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T15:19:58.364837Z c8f8f55 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR adds opt-in SQL and Arrow-column paths to Deck layers.

Preserve custom fetch behavior for URL queries and satisfy the remaining documentation requirement before merging.

Findings

  1. P1 URL queries skip custom `fetch` ▶
  2. P2 Required comments are missing ▶
  3. P2 Old points upload again ▶

Summary

Adds SQL queries and SQL accessor expressions for Arrow data, plus automatic Scatterplot field matching.

  • ScatterplotLayer can use matching Arrow table fields as columns.
  • Layers can run SQL queries on Arrow tables and supported URLs.
  • Arrow-enabled accessors can build columns from SQL expressions.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Layer data] --> B{query supplied?}
  B -->|Yes| C[Run table query]
  B -->|No| D[Load data normally]
  C --> E[Apply dataTransform]
  D --> E
  E --> F[Evaluate SQL accessors]
  F --> G[Resolve Arrow or GPU columns]
  G --> H[Upload and draw]
  E --> I[Pick source rows]
Loading

Reviews (16) · Last reviewed commit: "Use the shared Arrow streaming documenta..." · Reviewed by Greptile

@coveralls

coveralls commented Nov 11, 2026 •

Copy link
Copy Markdown

Coverage Status

Coverage is 83.406% — codex/arrow-table-resolution into codex/arrow-query-props. No base build found for codex/arrow-query-props.

@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch from c8f8f55 to a2a6279 Compare November 11, 2026 15:42
@ibgreen
ibgreen changed the base branch from master to codex/scatterplot-column-definitions November 11, 2026 15:42
@ibgreen
ibgreen force-pushed the codex/scatterplot-column-definitions branch from fced3ef to 355e62e Compare November 11, 2026 15:56
Base automatically changed from codex/scatterplot-column-definitions to master November 11, 2026 16:09
@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch 2 times, most recently from fc851a2 to 86bf8f5 Compare November 11, 2026 16:19
@ibgreen
ibgreen changed the base branch from master to codex/arrow-table-core November 11, 2026 16:19
@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch 2 times, most recently from 3115070 to a8533f6 Compare November 11, 2026 16:24
Base automatically changed from codex/arrow-table-core to master November 11, 2026 16:39
@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch from a8533f6 to 00bcf20 Compare November 11, 2026 16:52

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have docs demonstrating how to pack colors?

@ibgreen ibgreen changed the title feat(layers): resolve Scatterplot columns from Arrow tables feat(layers): support Arrow tables and column queries in ScatterplotLayer Nov 11, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

const table = new Table(arrowBatches);
lastResult = table;
this._setAsyncPropValue(propName, table, loadCount);
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arrow streams skip dataTransform

Medium Severity

Arrow RecordBatch chunks take an early path that never runs dataTransform. Layer docs say this callback applies to async iterables, and column-query docs say the query runs after dataTransform, so streamed Arrow tables and columnsQuery both miss that transform.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6039692. Configure here.

}
const table = new Table(arrowBatches);
lastResult = table;
this._setAsyncPropValue(propName, table, loadCount);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale stream writes after import

Medium Severity

The superseded-stream guard runs before await import('apache-arrow'), and nothing re-checks pendingLoadCount afterward. _setAsyncPropValue only requires loadCount >= resolvedLoadCount, so an older Arrow stream can still publish a table after a newer data source has already started.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6039692. Configure here.

const {Table, RecordBatch} = await import('apache-arrow');
if (!(chunk instanceof RecordBatch)) {
this._onError(propName, new Error('Expected an Arrow RecordBatch in the query stream.'));
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RecordBatch identity check is brittle

Medium Severity

Chunks are first recognized with a duck-type, then rejected unless they pass instanceof RecordBatch from a dynamically imported apache-arrow. Valid batches from another Arrow copy fail that check, abort the stream, and raise a misleading "Expected an Arrow RecordBatch" error.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6039692. Configure here.

Comment thread modules/core/src/lib/layer-manager.ts Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread modules/core/src/arrow/columns-query.ts Outdated
}
const select =
parsed.select?.map(normalizeSelection) ?? data.schema.fields.map(field => field.name);
return {select, where: parsed.where, limit: parsed.limit};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SELECT drops ORDER BY and OFFSET

Medium Severity

String columnQueries keep only select, where, and limit from the parsed SQL. ORDER BY, OFFSET, and GROUP BY are neither applied nor rejected. A query such as SELECT ... ORDER BY size DESC LIMIT 10 therefore returns the first 10 source rows in original order instead of the intended ranking.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ac7d331. Configure here.

@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch from ac7d331 to 638485e Compare November 15, 2026 15:46
Comment thread modules/core/src/types/layer-props.ts Outdated
/** Projects source Arrow fields and SQL expressions for layer column resolution. */
export type ColumnExpressionQuery = Readonly<Record<string, string | Expression>>;

export type ColumnsQuery = {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Required comments are missing

The new public ColumnsQuery type has no TSDoc comment. The repository guide requires TSDoc on types, functions, constants, and fields, including internal declarations. Add the missing comments here and to the other new declarations, including ArrowTableResult and FunctionCall; the same pattern appears elsewhere. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

/** Uses the same selected inputs as column preparation to choose the model. */
private hasColumns(): boolean {
return Object.keys(this.resolveColumns(SCATTERPLOT_COLUMN_DEFINITIONS, true)).length > 0;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pending queries leave column mode

Medium Severity

hasColumns() decides Scatterplot column mode from getColumnData(). While columnQueries is in flight, that helper returns an empty array, so the layer treats itself as an accessor layer. An already prepared column model is torn down and rebuilt after the projection finishes, which flashes empty data and recreates GPU resources on query changes and snapshot streams.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 638485e. Configure here.

@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch 2 times, most recently from dd0cd23 to 08c8f84 Compare November 15, 2026 15:59
export class ScatterplotLayerColumns extends LayerColumns {
constructor(device: Device) {
super(device, SCATTERPLOT_COLUMN_DEFINITIONS, 'Scatterplot', true);
super(device, SCATTERPLOT_COLUMN_DEFINITIONS, 'Scatterplot', true, true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Old points upload again

ScatterplotLayerColumns leaves the sixth constructor argument, appendArrowChunks, at its default false. Each appended batch therefore makes LayerColumns.update convert and upload every accumulated Arrow chunk again instead of reusing old buffers. The wasted work grows as the stream gets longer.

Pass true as the sixth argument to enable the new reuse path.

Suggested change
super(device, SCATTERPLOT_COLUMN_DEFINITIONS, 'Scatterplot', true, true);
super(device, SCATTERPLOT_COLUMN_DEFINITIONS, 'Scatterplot', true, true, true);

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

There are 7 total unresolved issues (including 5 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 08c8f84. Configure here.

Comment thread modules/core/src/lib/layer.ts Outdated
request.resultSource = previousProjection.source;
}
state.columnQueries = request;
this.setChangeFlags({dataChanged: 'columnQueries input changed'});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pending queries drop visible column data

High Severity

Non-appendable columnQueries replace the in-use projection with empty data as soon as a new run starts. getColumnData then returns no fields, so Scatterplot treats the layer as accessor-mode and tears down its GPU columns. Streamed batches with where or limit, and any query change, clear the layer until the next projection finishes.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 08c8f84. Configure here.

this._setAsyncPropValue(propName, table, loadCount);
this._onProgress(propName, table);
continue;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arrow streams skip dataTransform

Medium Severity

Streamed Arrow record batches are applied without dataTransform. The new batch path writes the accumulated table and continues, so columnQueries, accessors, and onDataProgress see raw chunks. Promise-loaded tables still run the transform, which does not match the documented order that queries run after dataTransform.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 08c8f84. Configure here.

@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch from 08c8f84 to b0d0638 Compare November 15, 2026 16:15
@ibgreen ibgreen changed the title feat(layers): support Arrow tables and column queries in ScatterplotLayer feat(layers): resolve Scatterplot columns from Arrow tables Nov 15, 2026
@ibgreen
ibgreen changed the base branch from master to codex/arrow-query-props November 15, 2026 16:15
@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch from b0d0638 to 54e0449 Compare November 15, 2026 16:19
@ibgreen
ibgreen force-pushed the codex/arrow-query-props branch from 139eafd to 6f94ecc Compare November 15, 2026 16:42
@ibgreen
ibgreen force-pushed the codex/arrow-table-resolution branch from 54e0449 to b89f058 Compare November 15, 2026 16:43
Base automatically changed from codex/arrow-query-props to master November 15, 2026 17:17
Comment on lines +177 to +181
if (request?.query) {
const {query} = request;
return import('../arrow/data-query').then(({queryLayerData}) =>
queryLayerData(url, query, request.loaders, request.options, request.parser)
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 URL queries skip custom fetch

Adding query to URL-backed data calls queryLayerData before reaching layer.props.fetch. Only loadOptions and loaders are forwarded. If the custom fetch adds required credentials, the layer can no longer load its data.

Keep custom fetch working, for example by querying the Arrow table it returns while reserving query pushdown for the default loading path.

@athomct athomct left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at b89f058.

Summary

This PR lets ScatterplotLayer take its GPU columns from an Arrow table in data. resolveColumns now looks up a table field by the accessor name (getPosition, getRadius, getFillColor, getLineColor, getLineWidth). The layer uses the same selection to choose column mode, the model and requireRows. The accessor fallback now unpacks Arrow list values with get(index). LayerColumns also gets a path that reuses uploads of unchanged record batches. The docs get a "Query" tab on 15 layer pages and a short section on table fields.

The main feature works. The PR's tests pass on WebGL and WebGPU, and the main changes are guarded. I ran the PR's node tests (41 pass), the full scatterplot-arrow-columns.spec.ts file in headless Chromium (35 pass, WebGPU included), and the nearby Arrow tests (35 node tests, and 30 browser tests for Arc, Column, Icon, Line and PointCloud; all pass). I also ran mutation checks. Three of the four main changes are guarded: matching by accessor name, the list unpack and the table-aware hasColumns. If the requireRows change is reverted, all tests still pass.

I added a probe file (at the end) to check the RFC items. These work as the RFC asks: a table with three record batches (count, bounds, radius readback, and picking row 5), a synchronous dataTransform that produces the table, an error when a selected field has a null, a schema change that falls back to the accessor, overlapping conversions where the newest table wins, and a table built by a second runtime copy of apache-arrow. That last one is good news for the two-copy case in the RFC thread. The findings below are where the code and the RFC differ, plus two lifecycle problems.

Findings

  1. modules/core/src/lib/resolve-columns.ts:45 — question (should-fix if the RFC stands) — table fields match accessor names, but the RFC says column names.
    Evidence: RFC #11069 says "Match exact public column names, such as positions, fillColors, and radii", and its example says "compatible table.radii wins over getRadius". This PR matches table.getRadius instead. A probe with new Table({positions, radii}) stays in accessor mode on WebGL and WebGPU (layer.state.columns is undefined). Columns like these come from DuckDB or GeoArrow with natural names, so users must alias every field (AS "getPosition"). A related effect: a field named getRadius silently wins over an explicit getRadius: () => 7. The RFC allows the table to win over an accessor, but here the field has the same name as a prop the app set. The PR is the template for the other layers, so this choice will spread.
    Suggested change: decide this before the other layers copy it. Either match the RFC names (positions, radii, ...), which also match the existing GPUVector props, or update the RFC text and its example to say "accessor names". In both cases, state in the guide that the table field wins over a function or constant accessor.

  2. modules/core/src/lib/layer.ts:809-818 — should-fix — after a failed or pending table replacement, picking returns rows that are not drawn.
    Evidence: the layer keeps the previous columns when a replacement fails, as the RFC asks. But getPickingInfo reads this.getColumnData(), which is already the new table. Probe: table A (2 rows, a0, a1) renders, then table B (3 rows) fails because getRadius has a null. After the error, prepared.source is A and getNumInstances() is 2, but picking index 0 returns b0. It fails the same way on WebGL and WebGPU. The same mismatch is present for a short time while a new table converts, because props.data changes before the new columns are committed.
    Suggested change: in column mode, resolve the picked object from the rows that were converted, for example this.state.columns.prepared.rows.at(index). Add the probe case as a test.

  3. modules/layers/src/scatterplot-layer/scatterplot-layer-columns.ts:76 and modules/core/src/lib/layer-columns.ts:101, 283, 428 — should-fix — the chunk reuse path is unreachable.
    Evidence: ScatterplotLayerColumns passes five arguments, so appendArrowChunks stays false. No other subclass sets it. So uploadArrowChunks and ArrowConverter.convertChunk never run, and no test covers them. Greptile reported this already; this adds evidence. A probe that appends a batch to a two-batch table gets a new buffer for batch 0. When I set the flag to true, that probe passes, but the existing test "Scatterplot avoids stale picking layout after a failed conversion" fails on both backends. It mocks ArrowConverter.prototype.convert, and the chunk path calls convertChunk, so the failure is a test coupling and not a real defect. It shows that enabling the flag needs more work than one argument.
    Suggested change: move the chunk reuse to its own PR with a test, or turn it on here and update the failure test to also cover convertChunk. The RFC defers async iterator accumulation, so a separate PR also matches the RFC scope.

  4. modules/core/src/lib/layer-columns.ts:128-142 — should-fix (may belong in a follow-up) — a new inline fallback accessor makes an unrelated prop change convert all columns again.
    Evidence: needsUpdate compares function accessors by identity. Deck ignores a new function on its own, but the next update that does run updateState sees the new identity. Probe with a table that has getPosition and getRadius: row => 2: radiusScale: 2 alone makes 0 calls to LayerColumns.update. {getRadius: row => 2, radiusScale: 3} makes 1 call, which converts the table positions again. In React, every render makes a new inline function, so every uniform change converts the whole table again. The accessor path uses updateTriggers for this. The code is not new in this PR, but this PR makes it the normal path for a table with one inline accessor. The RFC verification asks that "uniform-only updates do not re-upload geometry".
    Suggested change: for function accessors, use updateTriggers as the attribute manager does. Compare identity only for Arrow vectors and GPUVectors. At a minimum, do not convert table-sourced columns again when only a fallback accessor changed.

  5. Branch — should-fix — the branch conflicts with master.
    Evidence: the branch still carries the pre-squash commit of #11131 (6f94ecc1). git merge-tree against master 00707ff6 reports conflicts in 10 or more files, including layer-columns.ts, layer.ts, accessor-queries.ts and data-query.ts. master's layer.ts differs from the base by about 160 lines. The approval and the CI results are for code that will change in the rebase.
    Suggested change: rebase onto master, so that the diff shows only the Scatterplot changes, and run the checks again.

  6. test/modules/layers/scatterplot-arrow-columns.spec.ts:859-935 — should-fix — the tests miss several RFC verification items.
    Evidence: the new test uses one record batch only. The RFC asks for "direct/promised/transformed tables, explicit overrides, schema changes, chunks, and picking on WebGL/WebGPU". The current code passes my probes for chunks, synchronous dataTransform, schema change, nulls and a second Arrow copy. But no test in the PR protects them. The requireRows change at scatterplot-layer.ts:389-391 survives its mutation.
    Suggested change: add the multi-batch, dataTransform, null-error and schema-change cases from the probe. They are short, and they pass now. For requireRows, add an empty table case or drop the change.

  7. RFC thread — question — the open questions from the RFC discussion are not answered for the template layer.
    Evidence: in the RFC thread, akre54 asked whether extension attributes (for example filterValues) can be column props, and whether an opt-in null policy is possible for nullable LEFT JOIN columns. This PR keeps both limits. A table that matches a field and has any extension throws "Scatterplot Arrow columns do not support extensions". A null in a selected field raises an error (the probe confirms this, and it agrees with the RFC). ArrowConverter already has a nullPolicy option, with 'reject' as the default.
    Suggested change: no code change is needed in this PR. A short reply on the RFC that says whether nullPolicy and extension columns are planned would help the authors of the other layer PRs.

  8. docs/developer-guide/using-with-arrow.md:171-176 — nit — the new section does not say what is ignored.
    Suggested change: say that a field of an incompatible type is ignored and the accessor is used. Say that a selected field with nulls raises an error, and that extensions are not supported in column mode. Each layer page can then link here.

Verdict

Comment. The feature works on both backends, and the async, chunk and two-copy cases behave as the RFC asks. Before this PR becomes the template, please settle finding 1 (the naming choice). Please also fix finding 2 (picking against the drawn rows) and rebase. Findings 3, 4 and 6 can land here or in a follow-up, but please do not merge finding 3's code without a reachable test.

Probe test

The second-copy case imports apache-arrow-copy, which is a renamed copy of the installed apache-arrow package. Create it before you run that case, or skip it.

// Review probe for Arrow table column resolution in ScatterplotLayer.
import {afterAll, beforeAll, expect, test, vi} from 'vitest';
import {GPUDataEvaluator} from '@luma.gl/graph/gpu-simple-graph';
import {ScatterplotLayer} from '@deck.gl/layers';
import {device, testLayerAsync} from '@deck.gl/test-utils/vitest';
import {getWebGPUTestDevice} from '@luma.gl/core/test-utils';
import {Field, FixedSizeList, Float32, Table, Utf8, vectorFromArray} from 'apache-arrow';
import {ScatterplotLayerColumns} from '../../../modules/layers/src/scatterplot-layer/scatterplot-layer-columns';

const bufferPoolSize = GPUDataEvaluator.bufferPoolSize;
beforeAll(() => {
  GPUDataEvaluator.bufferPoolSize = 0;
});
afterAll(() => {
  GPUDataEvaluator.bufferPoolSize = bufferPoolSize;
});

function xy(rows: number[][]) {
  return vectorFromArray(rows, new FixedSizeList(2, new Field('values', new Float32(), false)));
}

async function readFloats(chunk: any, count: number): Promise<number[]> {
  const bytes = await chunk.buffer.readAsync();
  return Array.from(new Float32Array(bytes.buffer, bytes.byteOffset + chunk.byteOffset, count));
}

/** Three record batches with two rows each, as a chunked query result arrives. */
function chunkedTable(): Table {
  const tables = [0, 1, 2].map(
    batch =>
      new Table({
        getPosition: xy([
          [batch, 0],
          [batch, 1]
        ]),
        getRadius: vectorFromArray([batch * 10 + 1, batch * 10 + 2], new Float32()),
        name: vectorFromArray([`r${batch * 2}`, `r${batch * 2 + 1}`], new Utf8())
      })
  );
  return tables[0].concat(tables[1], tables[2]);
}

for (const backend of ['webgl', 'webgpu'] as const) {
  test(`probe: RFC public column names select columns on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const data = new Table({
      positions: xy([
        [0, 0],
        [1, 1]
      ]),
      radii: vectorFromArray([2, 3], new Float32())
    });
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: false,
      testCases: [
        {
          props: {data},
          onAfterUpdate: ({layer}) => {
            if (!layer.isLoaded) return;
            // RFC #11069: "Match exact public column names, such as positions, fillColors, and radii."
            expect(layer.state.columns, 'table.positions/radii should enter column mode').toBeDefined();
          }
        }
      ],
      onError: error => {
        throw error;
      }
    });
  });

  test(`probe: chunked table draws, counts and picks across batches on ${backend}`, async ({
    skip
  }) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const data = chunkedTable();
    expect(data.batches.length).toBe(3);
    let checked = 0;
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: true,
      testCases: [
        {
          props: {data, getFillColor: (row: any) => [Number(row.name.slice(1)) * 40, 0, 0, 255]},
          onAfterUpdate: async ({layer}) => {
            if (!layer.isLoaded) return;
            const prepared = (layer.state.columns as any).prepared;
            expect(layer.getNumInstances()).toBe(6);
            expect(prepared.chunkLengths).toEqual([2, 2, 2]);
            expect(layer.getBounds()).toEqual([
              [0, 0, 0],
              [2, 1, 0]
            ]);
            const radius = prepared.columns.instanceRadius;
            expect(radius.data.length).toBe(3);
            expect(await readFloats(radius.data[2], 2)).toEqual([21, 22]);
            const info = layer.getPickingInfo({
              info: {index: 5, color: null, layer, picked: true, x: 0, y: 0, pixelRatio: 1},
              mode: 'query',
              sourceLayer: null
            } as any);
            expect(info.object.name).toBe('r5');
            checked++;
          }
        }
      ],
      onError: error => {
        throw error;
      }
    });
    expect(checked).toBeGreaterThan(0);
  });

  test(`probe: synchronous dataTransform output is resolved on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const raw = new Table({
      pos: xy([
        [5, 6],
        [7, 8]
      ])
    });
    let checked = 0;
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: false,
      testCases: [
        {
          props: {
            data: raw,
            dataTransform: (table: any) => new Table({getPosition: table.getChild('pos')})
          },
          onAfterUpdate: ({layer}) => {
            if (!layer.isLoaded) return;
            expect(layer.state.columns).toBeDefined();
            expect(layer.getBounds()).toEqual([
              [5, 6, 0],
              [7, 8, 0]
            ]);
            checked++;
          }
        }
      ],
      onError: error => {
        throw error;
      }
    });
    expect(checked).toBeGreaterThan(0);
  });

  test(`probe: a null in a selected table field raises an error on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const data = new Table({
      getPosition: xy([
        [0, 0],
        [1, 1]
      ]),
      getRadius: vectorFromArray([1, null], new Float32())
    });
    const onError = vi.fn();
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: false,
      testCases: [{props: {data}}],
      onError
    });
    expect(onError).toHaveBeenCalled();
    expect(String(onError.mock.calls[0][0]?.message ?? onError.mock.calls[0][0])).toMatch(/null/i);
  });

  test(`probe: a schema change falls back to the accessor on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const p = xy([
      [0, 0],
      [1, 1]
    ]);
    const withRadius = new Table({getPosition: p, getRadius: vectorFromArray([2, 3], new Float32())});
    const withoutRadius = new Table({getPosition: p});
    const radii: number[][] = [];
    const record = async ({layer}) => {
      if (!layer.isLoaded) return;
      const radius = (layer.state.columns as any).prepared.columns.instanceRadius;
      radii.push(await readFloats(radius.data[0], 2));
    };
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: false,
      testCases: [
        {props: {data: withRadius, getRadius: () => 7}, onAfterUpdate: record},
        {updateProps: {data: withoutRadius}, onAfterUpdate: record}
      ],
      onError: error => {
        throw error;
      }
    });
    expect(radii[0]).toEqual([2, 3]);
    expect(radii[radii.length - 1]).toEqual([7, 7]);
  });

  test(`probe: appended record batches reuse earlier chunk uploads on ${backend}`, async ({
    skip
  }) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const full = chunkedTable();
    const first = new Table(full.batches.slice(0, 2));
    const columns = new ScatterplotLayerColumns(testDevice);
    const failed = vi.fn();
    const base = {getFillColor: [0, 0, 0, 255], getLineColor: [0, 0, 0, 255], getLineWidth: 1};
    try {
      await columns.update({...base, data: first}, () => {}, failed);
      const before = (columns as any).prepared.columns.instanceRadius.data[0].buffer;
      await columns.update({...base, data: full}, () => {}, failed);
      expect(failed).not.toHaveBeenCalled();
      const after = (columns as any).prepared.columns.instanceRadius.data[0].buffer;
      expect(columns.length).toBe(6);
      expect(after, 'first batch radius buffer should be reused').toBe(before);
    } finally {
      columns.destroy();
    }
  });
}

for (const backend of ['webgl', 'webgpu'] as const) {
  test(`probe: a table from a second Arrow copy resolves on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    // @ts-ignore second runtime copy of apache-arrow, not deduplicated
    const other = await import('apache-arrow-copy');
    expect(other.Table).not.toBe(Table);
    const data = new other.Table({
      getPosition: other.vectorFromArray(
        [
          [1, 2],
          [3, 4]
        ],
        new other.FixedSizeList(2, new other.Field('values', new other.Float64(), false))
      ),
      getRadius: other.vectorFromArray([5, 6], new other.Float32()),
      getFillColor: other.vectorFromArray(
        [
          [255, 0, 0, 255],
          [0, 255, 0, 255]
        ],
        new other.FixedSizeList(4, new other.Field('values', new other.Uint8(), false))
      )
    });
    expect(data.schema.fields[2].type.children[0].type instanceof (await import("apache-arrow")).Uint8).toBe(false);
    let checked = 0;
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: true,
      testCases: [
        {
          props: {data},
          onAfterUpdate: async ({layer}) => {
            if (!layer.isLoaded) return;
            const columns = (layer.state.columns as any).prepared.columns;
            expect(await readFloats(columns.instanceRadius.data[0], 2)).toEqual([5, 6]);
            const colorBytes = await columns.instanceFillColors.data[0].buffer.readAsync();
            expect(Array.from(colorBytes.slice(0, 8))).toEqual([255, 0, 0, 255, 0, 255, 0, 255]);
            expect(layer.getBounds()).toEqual([
              [1, 2, 0],
              [3, 4, 0]
            ]);
            checked++;
          }
        }
      ],
      onError: error => {
        throw error;
      }
    });
    expect(checked).toBeGreaterThan(0);
  });
}

for (const backend of ['webgl', 'webgpu'] as const) {
  test(`probe: picking after a failed table replacement on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const good = new Table({
      getPosition: xy([
        [0, 0],
        [1, 1]
      ]),
      name: vectorFromArray(['a0', 'a1'], new Utf8())
    });
    const bad = new Table({
      getPosition: xy([
        [5, 5],
        [6, 6],
        [7, 7]
      ]),
      getRadius: vectorFromArray([1, null, 3], new Float32()),
      name: vectorFromArray(['b0', 'b1', 'b2'], new Utf8())
    });
    const errors: Error[] = [];
    const seen: Array<{source: unknown; instances: number; picked: string}> = [];
    const record = ({layer}) => {
      if (!layer.isLoaded) return;
      const info = layer.getPickingInfo({
        info: {index: 0, color: null, layer, picked: true, x: 0, y: 0, pixelRatio: 1},
        mode: 'query',
        sourceLayer: null
      } as any);
      seen.push({
        source: (layer.state.columns as any).prepared.source,
        instances: layer.getNumInstances(),
        picked: info.object?.name
      });
    };
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device: testDevice,
      draw: true,
      testCases: [
        {props: {data: good}, onAfterUpdate: record},
        {updateProps: {data: bad}, onAfterUpdate: record}
      ],
      onError: error => {
        errors.push(error);
      }
    });
    expect(errors.length).toBe(1);
    const last = seen[seen.length - 1];
    // The previous columns stay on the GPU, as the RFC asks.
    expect(last.source).toBe(good);
    expect(last.instances).toBe(2);
    // Picking must describe the drawn row, so it should still return the previous table's row.
    expect(last.picked).toBe('a0');
  });

  test(`probe: overlapping conversions keep only the newest table on ${backend}`, async ({skip}) => {
    const testDevice = backend === 'webgpu' ? await getWebGPUTestDevice('core') : device;
    if (!testDevice) return skip();
    const a = chunkedTable();
    const b = new Table({getPosition: xy([[9, 9]]), getRadius: vectorFromArray([4], new Float32())});
    const columns = new ScatterplotLayerColumns(testDevice);
    const failed = vi.fn();
    const changed = vi.fn();
    const base = {getFillColor: [0, 0, 0, 255], getLineColor: [0, 0, 0, 255], getLineWidth: 1};
    try {
      const older = columns.update({...base, data: a}, changed, failed);
      const newer = columns.update({...base, data: b}, changed, failed);
      await Promise.all([older, newer]);
      expect(failed).not.toHaveBeenCalled();
      expect((columns as any).prepared.source).toBe(b);
      expect(columns.length).toBe(1);
      expect(changed).toHaveBeenCalledTimes(1);
    } finally {
      columns.destroy();
    }
  });
}

test('probe: column update count for inline accessor and uniform-only changes', async () => {
  const data = new Table({
    getPosition: xy([
      [0, 0],
      [1, 1]
    ])
  });
  const spy = vi.spyOn(ScatterplotLayerColumns.prototype, 'update');
  const counts: Record<string, number> = {};
  const mark = (label: string) => ({
    onBeforeUpdate: () => spy.mockClear(),
    onAfterUpdate: ({layer}) => {
      if (layer.isLoaded) counts[label] = spy.mock.calls.length;
    }
  });
  try {
    await testLayerAsync({
      Layer: ScatterplotLayer,
      device,
      draw: false,
      testCases: [
        {props: {data, getRadius: (row: any) => 2}},
        {updateProps: {radiusScale: 2}, ...mark('radiusScaleOnly')},
        {
          updateProps: {getRadius: (row: any) => 2, radiusScale: 3},
          ...mark('radiusScaleWithNewInlineAccessor')
        }
      ],
      onError: error => {
        throw error;
      }
    });
  } finally {
    spy.mockRestore();
  }
  expect(counts).toEqual({radiusScaleOnly: 0, radiusScaleWithNewInlineAccessor: 0});
});

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants