GPU SQL
Overview​
@luma.gl/graph/gpu-sql provides a bounded SQL frontend for
GPUDataFrame. GPUSQLContext registers
existing GPU dataframes by name and lowers supported statements into the same immutable GPU
dataframe planner. Planning does not upload, submit, allocate query output, or read GPU buffers.
The optional loaders.gl integration lives in the
GPU data analysis example.
Its planGPUDataFrameQuery() helper consumes the loaders.gl plan directly. Copy the adapter into
your application and install @loaders.gl/core and @loaders.gl/sql when needed.
The @luma.gl/graph/gpu-sql module exports the native frontend without a loaders.gl dependency.
When to use it​
Use GPU SQL when an application already has GPU dataframe inputs and a constrained SQL surface is more convenient than manually composing expressions, filters, aggregations, ordering, and joins. Use GPU Dataframe directly when an application needs behavior outside the supported grammar.
Use the loaders.gl adapter when a query originates in a loader, catalog, or application component
that already emits TableQueryOptions and SQLPredicate values:
import {parseSQLPredicate} from '@loaders.gl/sql';
import {GPUCommandGraph} from '@luma.gl/graph/gpu-graph';
import {planGPUDataFrameQuery} from './loaders-sql-query';
const predicate = parseSQLPredicate('fare >= :minimum AND category IN (0, 1)', {
preserveParameters: true
});
const query = planGPUDataFrameQuery(frame, {
predicate,
columns: ['fare', 'category'],
parameters: {minimum: 8}
});
const compiledGraph = query.compile(new GPUCommandGraph(device));
const commandEncoder = device.createCommandEncoder();
compiledGraph.encode(commandEncoder, {minimum: 10});
device.submit(commandEncoder.finish());
The compiled result stays GPU-resident as table, validity, dictionaries, rowIndices, and
selectedCounts. Rendering or another command graph can consume those resources directly. Arrow
readback remains an explicit adapter operation rather than the query's required result type.
Execution boundary​
The execution boundary is explicit: Arrow input → GPU dataframe execution → GPU consumers.
Use makeGPUAnalyticsTableFromArrowTable() to upload input, construct a GPUDataFrame, compile
the query into a caller-owned GPUCommandGraph, then encode and submit the graph. Downstream
rendering and compute can use the compiled GPU resources directly. Call
makeArrowTableFromGPUAnalyticsTable() only when the application explicitly needs CPU readback.
Use a SQL result in the same graph​
Check query.graphContribution during CPU planning before allocating an enclosing graph.
Resident projections, grouping, ordering, pagination, aggregation, bounded joins, and
UNION ALL can contribute results. Use the capability to choose the execution path.
| Capability | Caller action |
|---|---|
supported: true | Add the query with graph.add(query, {id}) and get the borrowed result before compiling. |
supported: false, executeWith: 'compile' | Use query.compile(graph) to execute the query on its own. |
supported: false, executeWith: 'execute' | Iterate plan.execute() for a spill plan that reaches host memory or storage. |
An unsupported capability includes the stage that requires the standalone path. The example below uses the result type for a projection because the SQL is known in advance.
const query = context.query(
'SELECT fare * 2 AS adjusted FROM trips WHERE fare >= :minimum',
{parameters: {minimum: 8}}
);
using graph = new GPUCommandGraph<GPUDataFrameQueryParameters>(device);
graph.add(query, {id: 'adjusted-fares'});
const result = graph.getContribution<GPUDataFrameQueryContribution>('adjusted-fares');
const adjusted = result.getColumn('adjusted');
// The application's consumer uses the same graph views as a DataFrame query.
addFareConsumer(graph, adjusted.values, result.selectionMask, adjusted.validity);
using compiledGraph = graph.compile();
compiledGraph.encode(commandEncoder, {parameters: {minimum: 10}});
device.submit(commandEncoder.finish());
The column retains source row order and batch boundaries. Use the selection mask for filtered rows and the validity sidecar for nulls. The enclosing graph keeps the contribution’s GPU resources alive. See DataFrame query contributions.
For dynamic resident SQL, use getContribution<GPUSQLQueryContribution>(id). Every result
exposes getColumn(), and supportsQueryChaining indicates whether another DataFrame row query
can consume it in the same graph. An ordered result exposes the row IDs and active counts
through ordering. Use those views to consume rows in query order after paging.
Use GPUDataFrameGroupedAggregationContribution for a known grouped query. In an observed
grouping or a query with HAVING, selection describes the active group rows.
For a unique-right join, read GPUDataFrameJoinContribution from the graph. Projected right
values and their validity are aligned to the physical left rows. rightRowIndices and
rightValidity describe compacted matches, while contractViolation and overflows carry
GPU diagnostics. A duplicate right key invalidates the match publication.
Supported grammar​
SQRT, LN, LOG10, ASIN, and ACOS accept Float32 inputs. Square root requires a nonnegative
value, logarithms require a positive value, and inverse sine and cosine accept the interval [-1, 1].
Invalid domains and non-finite inputs produce null in GPU SQL. SIN, COS, TAN,
ATAN, and EXP also accept Float32 inputs and return null for non-finite inputs. EXP
returns null when its result would overflow Float32. Trigonometric functions use radians.
RADIANS and DEGREES convert Float32 angles. Both return null for non-finite inputs,
and DEGREES also returns null if the converted magnitude would overflow.
ATAN2(y, x) takes two Float32 values and returns the quadrant-aware angle in radians.
A null or non-finite argument, or the origin where both arguments are zero, yields null.
MOD(dividend, divisor) takes matching Float32, Int32, or Uint32 inputs. The remainder keeps
the dividend's sign. Null arguments, non-finite inputs, and zero divisors yield null. Float32
remainder is computed without materializing a floating-point quotient.
POWER(base, exponent) accepts Float32 arguments, with integral exponents required for
negative bases. GPU Float32 overflow and invalid domains yield null. Results use GPU
floating-point precision and very small results may round to zero.
TRY(expression[, fallback]) can recover checked row errors from scalar arithmetic, POWER, zero divisors in MOD, and domain-checked
unary math such as SQRT and LN. Genuine nulls remain null. An omitted fallback yields null.
The fallback must use the same scalar format. Boolean TRY expressions are supported in predicates.
As in Arrow SQL, COALESCE and null tests do not catch checked math errors inside TRY.
GPU execution evaluates both expressions and
chooses the fallback only for tracked errors. Scalar / checks Float32, Int32, and Uint32
division by zero, Int32 overflow, and Float32 overflow from finite inputs. Integer quotients
truncate toward zero. A checked division error produces null unless TRY supplies a fallback.
Scalar +, -, and * also check Int32 and Uint32 range errors and Float32 overflow from
finite inputs. Casts use their own conversion rules.
CAST supports scalar Float32, Int32, and Uint32 results. Float-to-integer casts truncate toward zero
and preserve nulls. A non-finite or out-of-range conversion produces a null on the GPU.
Use TRY(CAST(value AS INTEGER), fallback) to recover from conversion errors with the same
fallback semantics as math.gl Arrow SQL.
COALESCE returns the first valid value from 2–64 scalar numeric arguments. NULLIF
returns null when its two valid numeric arguments compare equal. Columns in either
function use matching scalar formats.
ABS, FLOOR, CEILING, ROUND, and TRUNC accept one numeric argument and preserve nulls.
SIGN preserves the input format and returns -1, 0, or 1 for finite scalar numeric inputs.
ROUND rounds halfway values away from zero. ABS supports Float32 and Uint32. The rounding
functions also accept Int32 and return integer inputs unchanged. Calls on untyped literals or
parameters use Float32, so a comparison with an integer column requires matching formats.
Searched CASE WHEN … THEN … ELSE … END can produce numeric columns. Conditions that are null skip
the branch. Numeric column branches must have the same scalar format. An omitted ELSE yields null.
-
SELECT *, named columns, numeric expressions, and explicitASaliases. Projection-only queries can pass through packed GPU columns and retain their source buffers. -
One registered
FROMtable with optional aliases. -
WHEREcomparisons,AND,OR,NOT, parentheses,IS NULL, andIS NOT NULL. -
INandNOT INcompare a source column against up to 64 literals or named parameters. A null candidate makes a nonmatching result unknown, whichWHEREexcludes. -
Named
:parametervalues with planning defaults and encoding-time updates. -
One or more numeric
ORDER BYexpressions, each with its own direction and null ordering, and an optional boundedLIMIT. Keys are evaluated in priority order. Rows that tie on every key retain their input order. Sort keys can use source fields outside the projection and are excluded from the output schema.A one-based position refers to the SELECT output, including computed aliases and expanded
*. -
OFFSETskips selected rows before applyingLIMIT. A single-table, nonaggregate query withoutORDER BYpages filtered rows in source batch order using a GPU prefix scan. It exposes the page through the usual per-batch selection mask, row indices, and selected counts. -
COUNT(*),COUNT(column),SUM,MIN,MAX, andAVG, with optionalGROUP BY.COUNT(column)counts valid values after filtering, whileCOUNT(*)counts all selected rows. Without GROUP BY, HAVING filters the single aggregate row. It accepts SELECT aliases and aggregate calls, including calls omitted from SELECT. ORDER BY can refer to an output name, position, or aggregate call. LIMIT and OFFSET apply after HAVING. Read the filtered or paged row usingrowIndicesandselectedCounts. Numeric aggregate inputs such asSUM(fare * 2) AS totalrequire an explicit output alias. SELECT can also compute expressions over reductions and group keys. For example,MAX(fare) - MIN(fare) AS spreadevaluates after the reductions. Computed aggregate outputs require an alias, which HAVING and ORDER BY can reference.Refer to a selected key by source name, a matching expression, a one-based SELECT position, or an unqualified alias that does not shadow a source column. GROUP BY without aggregates returns one row per observed key or key tuple, including nulls. It supports HAVING, ORDER BY, LIMIT, and OFFSET. For example, use
SELECT fare FROM trips GROUP BY fare ORDER BY fare LIMIT 20to page through unique fares. GROUP BY keys may be omitted from SELECT. Queries with hidden keys return only groups observed after WHERE. A projected computed key such asFLOOR(fare) AS bucketrequires an explicit SELECT alias. Computed keys use observed grouping. HAVING filters grouped results before ordering and pagination. Without ORDER BY, LIMIT and OFFSET page the groups in GPU emission order. It can reference SELECT output names, grouping keys (including exact computed grouping expressions), and aggregate calls. Grouping keys and aggregate calls can be omitted from SELECT. For unordered HAVING results, passrowIndicesandselectedCountsto Arrow readback. SetmaxReductionScratchBytesin the query options to cap temporary partial buffers per grouped SUM or AVG. AVG counts both the sum and count buffers. The GPU reuses scratch across key ranges.maxMeanScratchBytescan also constrain the size of an individual AVG partial buffer. Grouped queries accept ORDER BY on SELECT positions or numeric expressions over SELECT output names, grouping keys, and aggregate calls. Grouping expressions and aggregate calls can be omitted from SELECT. Apply LIMIT and OFFSET to the sorted groups. PassglobalRowIndicesandglobalSelectedCountto Arrow readback for ordered groups. Grouped results preserve SELECT column order and retain key dictionaries under their output names. A projected single dictionary key returns the full category domain. Single numeric keys and multi-key queries return only groups observed after WHERE. Observed grouping supports uint32, sint32, float32, and dictionary-encoded keys, including nulls. Float keys group both signed zeros together and treat all NaNs as a single value. For observed results, pass the compiled query’srowIndicesandselectedCountsto Arrow readback to read the observed rows from the capacity-backed result.Default aggregate aliases use the bound field name, such as
sum_fareforSUM(trips.fare). -
One
INNER,LEFT,SEMI, orANTI JOINover a single equality key. Keys can use UInt32, Int32, or Float32. Mixed Int32 and UInt32 keys match only values in their shared numeric range. Both sides use Float32 for a floating-point join. Float32 joins treat both signs of zero as equal and skip NaN keys. Null keys never match. Int32 supports the full signed range, including -1. Aggregates can consume the selected left rows of a unique-right join directly on the GPU. The join and aggregate execute in one graph. An invalid right key index contributes no rows. The SELECT list controls result order and may omit either join key.INNER JOINandLEFT JOINcan project direct right-side packed 32-bit numeric columns, including two- to four-component vectors and dictionary codes with adapter metadata. For example,SELECT t.identifier, a.score AS account_score FROM trips AS t LEFT JOIN accounts AS a ON t.identifier = a.identifier. The GPU gathers right payloads into the original left batch layout. For multiple left batches, the join can stage contiguous right payload chunks in GPU scratch, then gather each staged range once per left batch and projected column. Each staged range spans consecutive right chunks that fit in one storage binding. The GPU copies chunks with copy-source usage directly and can stage storage-only chunks with compute passes when the staging and gather steps together use fewer compute passes than direct gathering. The join gathers directly from any remaining source chunks. SetmaxJoinProjectionScratchBytesto cap the combined staged payload and validity bytes across projected right columns. The planner considers columns in SELECT order and can stage a partial range when the whole column exceeds the remaining budget. A budget of zero disables staging. The cap applies to projection staging only. Multiple aliases for the same right source column share its gather work, GPU values, validity mask, and staging allocation. The result retains each alias in SELECT order. An unmatched left row yields null for every right field. SELECT expressions can combine left and right numeric inputs and use named parameters. Expressions run after matching, so COALESCE can replace a null from an unmatched right row. WHERE predicates that read right columns run after INNER or LEFT JOIN matching and before aggregation, ordering, or pagination. On a LEFT JOIN,WHERE r.score IS NULLcan retain unmatched rows, whileWHERE r.score > 0excludes them. Predicates that read only left columns can still filter before matching. Global and grouped aggregates over INNER and LEFT JOIN can consume direct right columns or scalar expressions over both inputs, including in HAVING and aggregate sort expressions. GROUP BY accepts direct and computed right keys and emits observed groups for those keys. Unmatched rows have null right inputs, so COUNT of a direct right column excludes them. A computed input can explicitly substitute a value with COALESCE. Joined row results support ORDER BY on numeric left and right expressions, output aliases, and SELECT positions. With ORDER BY, useglobalRowIndicesandglobalSelectedCountfor ordered Arrow readback. Without ORDER BY, LIMIT and OFFSET page matching left rows in source order. Per-batch join row IDs and validity remain aligned with the final page. Qualify the ON operands when the join sides cannot be determined from their field names.
Compound queries​
UNION ALL combines row-returning SELECT branches, including projections, filters,
and unique-right joins. Fields align by SELECT position and take their names from the
first branch. Corresponding GPU formats and dictionary codebooks must match. If
any branch is nullable, the combined column is nullable.
SELECT id, score FROM current_rows WHERE score > :minimum
UNION ALL
SELECT archive_id, archived_score FROM archived_rows
ORDER BY score DESC, 1 ASC
LIMIT 100 OFFSET 20
Duplicates are preserved. The trailing ORDER BY, LIMIT, and OFFSET apply to the combined result. Without ORDER BY, branches retain their input order. ORDER BY accepts output names and one-based positions and preserves branch and row order across ties.
The CompiledGPUDataFrameUnionAll result keeps the branch batches on the GPU. Read
globalRowIndices and globalSelectedCount for ordered results, or use
rowIndices and selectedCounts in source order. Aggregate and grouped UNION ALL
branches are outside the current GPU route.
Use graph.add(query, {id}) to let another GPU pass consume a compound query in the
same submission. Retrieve a GPUDataFrameUnionAllContribution from getContribution(id).
Its columns remain in branch and batch order. Read rowIndices and selectedCounts
to consume the selected rows in that order, or use ordering when the query has
ORDER BY. The graph retains the branch inputs and owns the combined selection.
SQL keywords and registered table names are case-insensitive. Column names must match the
dataframe schema exactly, even when unquoted. Double-quote reserved names such as "limit"
and "order". A quoted identifier such as "fare.total" names a single field. In
trips."fare.total", trips qualifies the field. The period inside the quotes remains part of its name.
Unsupported statements, unknown columns, unregistered tables, unsupported strings, ambiguous expressions and pagination on unsupported query routes fail during CPU-only planning. Applications still own command submission, synchronization, result readback, and cleanup.
The loaders.gl adapter currently supports predicate pushdown and output projection. It accepts
finite numeric, Boolean, and null predicate values, including reusable named parameters. Portable
source-order limit, streaming, in-flight cancellation, string/binary/date values, and relational
extensions are reported or rejected as unsupported instead of silently falling back to CPU work.
Use Arrow text as SQL keys​
Encode UTF-8 keys at the Arrow boundary before uploading the tables. A group shares one lexical codebook, so the GPU can compare codes directly and Arrow readback can recover the original labels.
import {encodeArrowGPUTextKeys, makeGPUAnalyticsTableFromArrowTable} from '@luma.gl/graph/arrow';
import {GPUDataFrame} from '@luma.gl/graph/gpu-dataframe';
import {GPUSQLContext} from '@luma.gl/graph/gpu-sql';
const encoded = encodeArrowGPUTextKeys({trips, airports}, [[
{table: 'trips', column: 'airport'},
{table: 'airports', column: 'code'}
]]);
const frames = Object.fromEntries(
Object.entries(encoded).map(([name, table]) => [
name,
new GPUDataFrame({...makeGPUAnalyticsTableFromArrowTable(device, table), ownership: 'owned'})
])
);
const context = new GPUSQLContext(frames);
const plan = context.query(\`
SELECT t.airport, COUNT(*) AS flights
FROM trips AS t
INNER JOIN airports AS a ON t.airport = a.code
WHERE t.airport IN ('CDG', 'SFO')
GROUP BY t.airport
ORDER BY t.airport
\`);
Group together corresponding join keys or corresponding text outputs of a UNION ALL.
Use singleton groups for unrelated keys. The encoder accepts plain Utf8 and Utf8
dictionaries, including different source codebooks. It preserves input table ownership,
row order, nulls, and source batches. Text comparisons and ordering use the same UTF-8
byte order as math.gl Arrow SQL. Grouped SQL over encoded text emits observed groups.
A text filter can compare a normalized key to a text literal, including an absent label,
or use literal IN and NOT IN lists. Comparisons between encoded text fields use a
shared codebook.
Unique-right joins can also match Float32 keys with Int32 or Uint32. A float matches only when its value is integral and in the other key's range. Equality preserves integer precision, including around the Float32 exact-integer boundary.
Expand Arrow lists and maps in SQL​
Use compileArrowGPUSQLUnnest from @luma.gl/graph/arrow when the source contains a
List, FixedSizeList, or Map. The adapter uploads supported scalar fields
and expands the collections on the GPU. The same SQL planner then applies the SELECT,
WHERE, aggregation, HAVING, ordering, and pagination to the published rows.
import {compileArrowGPUSQLUnnest} from '@luma.gl/graph/arrow';
import {GPUCommandGraph} from '@luma.gl/graph/gpu-graph';
const query = compileArrowGPUSQLUnnest(
new GPUCommandGraph(device),
\`
SELECT t.id AS trip, u.speed, u.position
FROM trips AS t
LEFT JOIN UNNEST(t.speeds) WITH ORDINALITY AS u(speed, position) ON TRUE
WHERE u.speed IS NULL OR u.speed >= :minimum
ORDER BY trip, position
\`,
{trips: arrowTable},
{capacity: 100_000, parameters: {minimum: 10}}
);
try {
const encoder = device.createCommandEncoder();
query.encode(encoder);
device.submit(encoder.finish());
const result = await query.readArrow();
} finally {
query.destroy();
}
A list exposes one item, and a map exposes its key and value. WITH ORDINALITY adds
a one-based position. CROSS JOIN drops null and empty collections. LEFT JOIN ... ON TRUE
keeps their parent row and supplies null child and ordinality values. Expansion visits Arrow
batches and rows in source order, and children in collection order.
Set capacity to bound expanded rows before any downstream clause. The GPU-resident
query.expansionCounts contains two uint32 words for the required row count and an
overflow flag. On overflow the query processes the published prefix, so a filter, aggregate,
or sort can produce a partial result even when its output is shorter than the capacity.
Choose a sufficient capacity or check the flag before using results that must cover all rows.
Each lateral expansion supports Int8, Int16, Int32, Uint8, Uint16, Uint32,
Float16, Float32, Utf8, and UTF-8 dictionaries in parent and child fields. Narrow
numeric values widen exactly to 32 bits. Text uses a lexical dictionary shared
across expansion batches and is returned as Arrow dictionary text. SELECT *
exposes the supported parent scalars and the lateral outputs.
Place an ordinary equality join after CROSS or LEFT UNNEST to look up an expanded
value before filtering, aggregation, sorting, or pagination. With no join
option, the follow-up uses the unique-right index. Set join: {capacity: 100_000}
to use a bounded general join with repeated right keys and composite ON clauses.
Inspect query.pairCounts for truncation independently of query.expansionCounts.
An individual UTF-8 equality key shares one lexical codebook across the expansion
and lookup. Composite text keys require compatible codebooks. Wildcard output
qualifies repeated names with their relation aliases.
Two sibling UNNEST clauses can expand separate columns of the same parent. Set
secondaryCapacity and join.capacity to bound the second expansion and the
combined output. The plan correlates the expanded rows by original parent index
on the GPU, producing the child combinations for each parent. Each LEFT clause
retains an empty or null collection as one null row. Check secondaryExpansionCounts
for truncation in the second collection. Qualify fields with their original
parent or lateral aliases.
Inspecting a plan​
Call context.query(sql).explain() to inspect the bound execution route, projected and working columns, key count, join type, and pagination before compiling. The frozen description is generated during CPU planning and allocates no GPU buffers.
Related modules​
Benchmark right-side projection​
Run the opt-in WebGPU benchmark with fixed row counts and varying right batch counts:
yarn test-browser-benchmarks modules/graph/test/gpu-sql/gpu-join-projection-benchmark.spec.ts
The benchmark checks result parity and records projection compute passes, copy passes, and staging bytes. It separately reports graph compilation, command encoding, and the wall time from encoding to GPU completion. Separate GPU timestamp runs measure the graph's compute passes when the device exposes timestamp queries. Native copies contribute to wall time. Arrow readback runs outside the timed samples.
Execute joins and sorts beyond GPU residency​
The Arrow adapters joinArrowTablesWithGPU and sortArrowTableWithGPU treat Arrow as
host storage. They upload packed keys for one tile or run at a time. Payload columns stay in
the input Arrow table. Use makeArrowGPUOPFSSpill with an Origin Private File System
directory to store row identities in files. A custom spill store can use the same paged
interface on any host.
import {makeArrowGPUOPFSSpill, sortArrowTableWithGPU} from '@luma.gl/graph/arrow';
const root = await navigator.storage.getDirectory();
const directory = await root.getDirectoryHandle('query-spill', {create: true});
const spill = makeArrowGPUOPFSSpill(directory);
for await (const page of sortArrowTableWithGPU(device, source, {
keys: [{column: 'revenue', direction: 'descending'}],
runRows: 65_536,
outputRows: 4_096,
spill
})) {
consume(page);
}
The sort spills one permutation per GPU run. A stable host merge reads a page from each run and applies global offset and limit. Packed numeric keys and lexically encoded text keys are supported. The join hashes up to four equality keys into host partitions. Each partition is split into tiles whose full pair count fits the output reservation, including when every key matches every row in the tile. Join chunks contain original signed 32-bit Arrow row IDs. A right ID of -1 marks rows without a right payload in LEFT, SEMI, or ANTI results. Pair order follows partition and tile order.
runRows, tileRows, and pairCapacity bound GPU allocation dimensions. The input Arrow
tables and initial join hash buckets are held on the host. Sort merge memory includes one
configurable page per run. Both operators release spill runs when iteration stops. The
onSample callback reports tracked live buffer bytes before readback. On an isolated
device, the maximum sample measures persistent and transient GPU buffers for the active
tile or run. Readback staging and driver allocations are outside that measurement.
The opt-in benchmark fixes row counts and tile limits while varying source batch counts. It reports tracked buffer bytes and median end-to-end throughput after warm-up.
yarn test-browser-benchmarks modules/graph/test/arrow/arrow-gpu-external-benchmark.spec.ts
Query repeated and composite GPU join keys​
To compose a repeated-key or composite SQL join with other GPU commands, add a
GPUSQLGeneralJoinQuery to the enclosing graph. Pair publication, payload gathering, and
the terminal SQL operations share one compilation.
import {GPUSQLGeneralJoinQuery} from '@luma.gl/graph/gpu-sql';
const query = new GPUSQLGeneralJoinQuery(sql, {orders, shipments}, {capacity: 16_384});
graph.add(query, {id: 'order-shipments'});
const joined = graph.getContribution('order-shipments', query);
const weight = joined.result.getColumn('weight');
// A downstream command can consume weight.values, weight.validity, and joined.rowCounts.overflow.
rowCounts uses the same named GPU views as DataFrame joins and UNNEST.
It describes pairs before filtering, grouping, ordering, or pagination. Terminal SQL operations
apply to the published prefix, even when rowCounts.overflow reports truncation.
Use compileGPUSQLGeneralJoin for resident inputs with repeated right keys or composite
ON conditions. It accepts one INNER, LEFT, SEMI, or ANTI join with up to four
column equalities connected by AND. Qualify columns when both sources use the same name.
import {compileGPUSQLGeneralJoin} from '@luma.gl/graph/gpu-sql';
import {GPUCommandGraph} from '@luma.gl/graph/gpu-graph';
const compiled = compileGPUSQLGeneralJoin(
new GPUCommandGraph(device),
\`
SELECT l.region, SUM(r.amount) AS total, COUNT(*) AS matches
FROM orders AS l
LEFT JOIN payments AS r ON l.orderId = r.orderId AND l.region = r.region
GROUP BY l.region
ORDER BY total DESC
\`,
{orders, payments},
{capacity: 100_000}
);
const encoder = device.createCommandEncoder();
compiled.encode(encoder);
device.submit(encoder.finish());
const result = compiled.result;
The pair stage preserves left and right source order within the bounded publication.
Payload gathers include only referenced packed scalar or vector columns and preserve their
validity and dictionary labels. WHERE, grouped and global aggregates, HAVING, sorting,
and pagination run on the published rows. SEMI and ANTI expose left payloads. A plain
SELECT * uses left payload columns.
The capacity is applied before downstream SQL. compiled.pairCounts contains the required
pair count, published pair count, and overflow flag as three GPU uint32 values. A truncated
join can produce a partial aggregate or sorted result. Use capacity zero to obtain pair
counts without publishing rows. Read the ordinary SQL selection sidecars on compiled.result
when materializing Arrow, and call compiled.destroy() after use.
For large Arrow inputs, joinArrowTablesWithGPU uses host hash partitions and bounds GPU
pair tiles independently. Resident joins automatically build stable sorted hash indexes for larger right inputs
across one or more storage bindings. Probes check exact tuple equality in each segment's
matching hash interval, and ties retain right-source order across segments. Use
maxIndexRows to cap rows per segment or select strategy: 'tiled' to scan raw tiles.
When the upper bound on pair count exceeds uint32, pairCounts also contains the high
word at index 3. The required count is the low word at index 0 plus the high word
multiplied by 2³². The published count and overflow flag remain at indices 1 and 2.
The ordinary GPUSQLContext.query unique-right
path continues to use its existing indexed implementation.
Run SQL with spill-backed joins and ordering​
Use makeArrowGPUSQLSpillContext for a host-resident Arrow catalog that exceeds the
desired GPU working set. Its query() method uses the shared SQL parser and join binder.
It runs WHERE and SELECT expressions on the GPU in bounded batches, uses partitioned GPU
matching for equality joins, and uses external GPU sort runs for global ORDER BY.
import {makeArrowGPUSQLSpillContext, makeArrowGPUOPFSSpill} from '@luma.gl/graph/arrow';
const root = await navigator.storage.getDirectory();
const spill = makeArrowGPUOPFSSpill(await root.getDirectoryHandle('sql-spill', {create: true}));
const context = makeArrowGPUSQLSpillContext(device, {orders, payments}, {
batchRows: 16_384,
join: {partitions: 32, tileRows: 128, pairCapacity: 16_384, spill},
order: {runRows: 16_384, outputRows: 4096, spill}
});
const plan = context.query(`
SELECT o.id AS order_id, p.amount AS amount
FROM orders o LEFT JOIN payments p ON o.id = p.order_id
WHERE o.region >= :region
ORDER BY amount DESC NULLS LAST, order_id
LIMIT 100
`, {parameters: {region: 1}});
for await (const batch of plan.execute({signal})) {
consume(batch);
}
A spill-backed plan reports graphContribution.supported: false and
executeWith: 'execute'. The reported stage is external-join for partitioned joins,
external-sort for external ordering, or gpu-select when batching and transferring host rows
is the only boundary. Use plan.explain() for the complete stage sequence, and iterate
plan.execute() to consume the Arrow batches.
A spill-backed query supports one row-returning SELECT, optionally with an INNER, LEFT, SEMI, or ANTI join using up to four equality keys. Filtering precedes global ordering and pagination. Without ORDER BY, joined rows follow partition and tile order. ORDER BY supports projection aliases, ordinals, and source expressions. Use a unique final sort key when pagination needs to be independent of the chosen partition layout.
The execution path retains the Arrow input tables on the host. Ordered queries also retain the filtered and projected Arrow batches on the host while spilling sort permutations. Pair and run limits bound GPU work. GROUP BY, aggregate SELECT, UNION ALL, and lateral expansion remain available through their existing execution paths. Cancelling or closing the result iterator releases active spill runs and GPU resources.