Lance
Docs /Integrations /Lance Context /Guide /SQL queries

SQL queries

Lance Context can serve read-only SQL over its registered stores through a REST API. It is off by default: a server started without SQL_ENABLED=true mounts no SQL routes and starts no query runtime.

Queries are planned and executed by DataFusion over committed Lance dataset versions; inputs stream from version-bound Lance scans rather than being loaded into memory first.

Enabling SQL

SQL_ENABLED=true lance-context-server --data-dir s3://bucket/lance-context
Setting Default Meaning
SQL_ENABLED false Serve /api/v1/sql and /api/v1/queries/....
SQL_NODE_ID INSTANCE_ID or HOSTNAME This node's name in query ids.
SQL_CATALOG lance SQL catalog name of the store registries.
SQL_DEFAULT_SCHEMA generic Store kind that unqualified table names refer to.
SQL_TIME_ZONE +00:00 Session time zone of every query.
SQL_THREADS one per CPU Threads of the dedicated query runtime. Query work never runs on the threads that serve the other routes.
SQL_TARGET_PARTITIONS SQL_THREADS Parallelism of query plans.
SQL_BATCH_SIZE 8192 Target rows per batch.
SQL_MEMORY_LIMIT_BYTES 25% of the effective memory limit Memory pool shared by all queries. Operators that can spill do so at the limit; others fail with resources_exhausted.
SQL_QUERY_MEMORY_LIMIT_BYTES 0 (the whole pool) Memory of the pool one query may hold; it spills, or fails with resources_exhausted, at this limit too.
SQL_SPILL_DIR / SQL_SPILL_LIMIT_BYTES OS temp dir / 10 GiB Spill location and budget across all queries; 0 disables spilling.
SQL_INDEX_CACHE_BYTES / SQL_METADATA_CACHE_BYTES 512 MiB / 256 MiB Lance caches shared by all queries.
SQL_MAX_RUNNING_QUERIES CPUs, at most 8 Queries executing at once.
SQL_MAX_QUEUED_QUERIES 64 Admitted queries waiting for a slot; more are rejected with 503 overloaded.
SQL_INTERACTIVE_SLOTS a quarter of the running slots, 1 or 2 Running slots heavy queries leave to interactive ones (see Admission).
SQL_INTERACTIVE_MAX_ESTIMATED_SECONDS 10 Queries estimated to run within this many seconds, in the mode they run in, are interactive; the rest, and queries without an estimate, are heavy.
SQL_MEMORY_ADMISSION true Hold a query until seven eighths of the memory pool can take the state its estimate says cannot spill (see Admission); false admits by slots alone.
SQL_MAX_OPEN_QUERIES 256 Queries holding state (queued, running, or with unread results); more are rejected.
SQL_DEFAULT_TIMEOUT_MS / SQL_MAX_TIMEOUT_MS 5 min / 6 h Deadline of requests without timeout_ms, and the largest allowed.
SQL_RESULT_IDLE_TIMEOUT_MS 5 min A query whose results nobody reads or polls for this long expires.
SQL_DRAIN_TIMEOUT_MS 20 s On SIGTERM or Ctrl+C, how long open queries, and the tasks this node runs for other members' queries, may finish before they are cancelled (see Draining).
SQL_JSON_MAX_ROWS / SQL_JSON_MAX_BYTES 100 000 / 64 MiB Bounds of JSON results.
SQL_MAX_TABLES_PER_QUERY 256 Tables one query may bind.
SQL_RUNTIME_FILTERS true Lance scans apply the filters hash joins and top-k sorts derive while a query runs (see Runtime filters); false turns them off.
SQL_COST_BASED_JOINS true Choose hash join build sides from estimates of what every plan node produces (see Join planning); false leaves DataFusion with the statistics of the Lance scans alone.
SQL_FILTER_SAMPLE_ROWS 4096 Rows a filtered scan of a large table reads from each sampled fragment to measure its filter (see Join planning); 0 keeps the guesses.
SQL_FILTER_SAMPLE_FRAGMENTS 8 Fragments one scan samples, spread over the table; 0 keeps the guesses.
SQL_FILTER_SAMPLE_MIN_TABLE_ROWS 1000000 Tables with fewer live rows keep the guesses.
SQL_FILTER_SAMPLE_TIMEOUT_MS 2000 A sample that takes longer is abandoned, and the scan keeps its guess.

Every setting is also a --sql-... flag.

Memory. The pool bounds what DataFusion accounts for, not everything a query allocates: a hash join copies its build side into one batch after collecting it, so for a moment it holds about twice what it reserved, and Lance scans, caches and the allocator need room besides. That is why the default pool is a quarter of the memory limit. A hash join's build side cannot spill: a query whose build sides together exceed the pool fails with resources_exhausted, while aggregations and sorts spill to SQL_SPILL_DIR.

Join planning

DataFusion builds each hash join's table from one input and streams the other through it, choosing the smaller input as the build side, and collects a small build side into one partition instead of repartitioning both sides, when it knows how large the inputs are. Lance scans know their rows exactly (fragment metadata, less deleted rows), but joins and aggregations above them report nothing without column statistics, which Lance does not keep. With SQL_COST_BASED_JOINS (the default), every plan node reports an estimate instead, from these documented heuristics:

  • a filter keeps a fraction of its input per condition: = 1/10, a range 1/3 (bounds on both sides of one column 1/4), LIKE 1/4, IN with n values n/10 (at most 1/2), IS NULL 1/20, anything else 1/2, combined as probabilities for AND, OR and NOT;
  • an equi-join is taken to join a foreign key to a key: the input whose largest table has fewer rows holds the key, and the join keeps the rows of the other input whose key survived the key side's filters; semi and anti joins keep that fraction of their input or its complement, outer joins at least their preserved inputs, and other joins a tenth of the Cartesian product;
  • an aggregation produces one row without GROUP BY, and otherwise the product of each key's guessed distinct values (2 for a boolean, 2,500 for a date, 1,000 for a string, every row for numbers), at most its input.

A guessed filter can be far off: at scale factor 100, l_returnflag = 'R' keeps a quarter of lineitem (guessed a tenth) and a three-month date range 4 % of orders (guessed a quarter), enough to build TPC-H Q10's join on 148 million rows instead of 5.7 million. So before planning a filtered scan of a table with at least SQL_FILTER_SAMPLE_MIN_TABLE_ROWS live rows, the node reads the first SQL_FILTER_SAMPLE_ROWS rows of SQL_FILTER_SAMPLE_FRAGMENTS fragments spread over the table (only the filter's columns, concurrently) and counts the rows the filter keeps; the scan is estimated at that fraction, and EXPLAIN shows the count as filter_sample=<kept>/<read>. The sampled rows are not random, so a sampled estimate's plausible range still spans a factor of two either way (a guess's spans four). A sample that fails or takes longer than SQL_FILTER_SAMPLE_TIMEOUT_MS leaves the guess in place.

Each estimate records how uncertain it is. The estimates only decide how a query is planned, never its result. At TPC-H scale factor 100, they let Q7, Q18 and Q21 run within the default memory pool on one node, where DataFusion alone built hash tables over hundreds of millions of lineitem rows and failed with resources_exhausted.

Runtime filters

Once a hash join has built its table, it knows which keys its other input can match: their bounds, and the keys themselves (a list when there are at most 150, otherwise a lookup in the table). With SQL_RUNTIME_FILTERS (the default) the join hands that filter to the Lance scans below its other input, which apply it before the rows go further: comparisons with constants and lists of keys join the scan's own Lance filter, so Lance decodes the scan's other columns only for the rows that pass. The rest (lookups in the join's table) is evaluated on each batch the scan returns, one filter at a time on the rows the ones before it kept, and only while it pays. A scan judges a filter on each 65,536 rows it evaluates: if the rows it removed would not have cost more on their way to the join, and in it, than the CPU time evaluating it took, the scan suspends it for its next 65,536 rows, twice as many each further time in a row (up to 64 times as many), then tries it again. What a filter costs varies along a scan, and its first batches can cost several times its later ones while every partition starts at once. The planner estimates what a row costs between the scan and the join from the operators in between: routing it to a partition (2.5 nanoseconds and 0.5 a byte), another join's lookup (25) or table (60), an aggregation (30). The join's own lookup counts as half of what the filter costs a row, which also routes the row and checks its partition's bounds. So a filter whose rows only pass a repartition on their way to the join pays only for wide rows of which it removes nearly all, while one that keeps rows out of another join's table, or out of an aggregation, pays for far less. A partitioned join's filter is evaluated by partition, each row against its own partition's table only. A join whose table is empty lets its scans return nothing. A top-k sort (ORDER BY ... LIMIT) hands down the bound a row must beat to enter its top rows, which it tightens as rows arrive: scans evaluate it as it stands on each batch. Runtime filters only remove rows the operator that built them would discard, so results do not change. DataFusion's filters from min/max aggregations stay off: in DataFusion 54 they can drop rows that change the result (a partition that has aggregated no value yet resets the min bound they keep rows against). Nor do joins whose result depends on rows with NULL keys filter their scans, since a join's filter rejects every such row: joins that match NULL to NULL (EXCEPT, INTERSECT, IS NOT DISTINCT FROM) and the anti joins of NOT IN, which return nothing when the list holds a NULL. EXPLAIN shows a scan's filters as runtime_filters=[...] and, in the same order, what a row costs on its way to each filter's join as runtime_filter_carry_ns=[...] (their current value under EXPLAIN ANALYZE, with runtime_filtered_rows, the rows removed after Lance returned them, runtime_filter_time, the CPU time spent removing them, runtime_filters_suspended, the times scan partitions suspended a filter, and runtime_filter_skipped_rows, the scan's rows while one was, summed over the filters). Distributed queries do not use them yet: the tasks their workers run are encoded without them.

Query pools

Several servers that read the same storage (the same --data-dir, so the same stores and registries) can form a query pool. Every member lists the same members, itself included, and runs the same build:

SQL_ENABLED=true \
SQL_NODE_ID=node-a \
SQL_POOL='node-a=http://10.0.0.1:3000,http://10.0.0.1:7070;node-b=http://10.0.0.2:3000,http://10.0.0.2:7070' \
SQL_POOL_SECRET=... \
lance-context-server --data-dir s3://bucket/lance-context

Each member keeps serving the API on its HTTP port and also serves a worker endpoint (gRPC) that runs distributed tasks for every member's queries. Queries are submitted to any member; that member owns the query, plans it, coordinates its tasks across the ready members, and holds its results.

Setting Default Meaning
SQL_POOL unset ;-separated members, each <node_id>=<http_url>,<worker_url>. Unset: queries run on the receiving node only.
SQL_WORKER_LISTEN 0.0.0.0:<port of this node's worker URL> Address of this node's worker endpoint.
SQL_POOL_SECRET unset Secret every worker call between members carries (16 or more printable ASCII characters); calls without it are refused.
SQL_WORKER_MAX_TASKS 256 Distributed tasks this node runs at once for all members' queries. More are rejected (the query fails with resources_exhausted), never queued.
SQL_STAGE_MAX_TASKS 0 Tasks one stage of a query may use; 0 means one per ready member.
SQL_SCAN_BYTES_PER_TASK 256 MiB Estimated stored bytes per distributed scan task; a scan never uses more tasks than it has fragments.
SQL_EXCHANGE_COMPRESSION lz4 Compression of exchanged data: lz4, zstd or none.
SQL_SINGLE_MAX_ESTIMATED_SECONDS 600 auto runs a query on its owner alone when its estimated time on one reference node is below this.
SQL_STREAMING_MAX_ESTIMATED_SECONDS 3600 At or above this, a query is a staged-execution (scales) candidate; below it (and at or above the single threshold), a streaming candidate.
SQL_AUTO_SCALES false Whether auto runs scales candidates in scales mode (three-way routing). Otherwise they stream, and the routing reason says so.
SQL_ROUTING_UNCERTAINTY expected Which end of an estimate's plausible range auto compares with the thresholds, the memory pool and the deadline: expected, low or high.
SQL_COST_PROFILE unset A JSON file describing the reference node: cores, throughputs (scan_bytes_per_second, operator_rows_per_second, spill_bytes_per_second, network_bytes_per_second, storage_bytes_per_second, output_bytes_per_second), stage overheads (streaming_stage_seconds, scales_stage_seconds) and operator weights. Fields it leaves out keep their defaults. lance-context-tpch calibrate fits one to measured runs (see Calibrating routing).
SQL_REFERENCE_SCAN_BYTES_PER_SECOND / SQL_REFERENCE_ROWS_PER_SECOND 1 GiB/s / 100 M rows/s Throughputs of the reference node: stored bytes scanned, and rows probing a hash join (the unit of operator work). They override SQL_COST_PROFILE.
SQL_SCALES_STORAGE unset Intermediate storage of staged (scales) execution: an object store URI (s3://bucket/prefix, ...) or a directory every member reads and writes, the same on every member and used by no other pool, opened with the member's storage credentials from its environment. Unset: scales is unavailable on this node.
SQL_SCALES_COMPRESSION lz4 Compression of intermediate outputs: lz4, zstd or none.
SQL_SCALES_TASK_ATTEMPTS 3 Attempts a staged task gets before its query fails (1: no retries).
SQL_SCALES_MAX_RUNNING_TASKS 0 Tasks of one staged query running at once; 0 means one per ready member.
SQL_SCALES_RETENTION_SECONDS 86400 Intermediate outputs a staged query left behind (its owner stopped before removing them, and its node did not start again) are removed once this old; must exceed SQL_MAX_TIMEOUT_MS.
SQL_SCALES_FAULTS unset Fault drills and tests only, in servers built with the sql-fault-injection cargo feature (never in production builds): faults staged execution injects on this node, seed=<n>[,attempts=<n>][,delay_ms=<n>],<point>=<rate>,... with the points slow (the attempt waits delay_ms), before_task, while_writing, after_write, before_read, lose (a committed output is deleted) and duplicate (a second attempt races the first). Choices follow the seed, so members with the same setting make the same ones; only a task's first attempts (default 1) attempts fail.

A task can read anything the member's storage settings can open, so the worker endpoint must only be reachable from the pool's network (for example, a Kubernetes NetworkPolicy that admits only pool members to the worker port). Set SQL_POOL_SECRET as well; without it the endpoint accepts tasks from every client that can reach it, and the server logs a warning at startup.

Members probe each other's worker endpoints every few seconds. A member that does not answer, answers with another build, or refuses this node's secret is not ready, and new queries place no tasks on it until it answers again. A member that answers it is draining (see Draining) gets no new tasks either, and finishes those it has. GET /api/v1/sql/pool reports this node's state (ready, draining or stopped), each member's state (unknown, ready, incompatible, draining or unreachable) and this node's worker activity (running, admitted and rejected tasks, refused calls).

Routing. auto estimates how long a query would take on one reference node, described by the defaults below or by SQL_COST_PROFILE: 16 cores, 1 GiB/s of stored bytes scanned and decoded, 100 M hash-join probe rows per second, 512 MiB/s of spill, 1 GiB/s of network per node, 512 MiB/s of intermediate storage per node, 128 MiB/s of results encoded for the client, and 0.05 s (streaming) or 0.5 s (staged) per distributed stage. The estimate walks the final physical plan with the row estimates of join planning and adds:

  • scan: stored bytes of the scanned columns;
  • compute: rows through every operator, weighted per operator (filters 0.1, computed projections 0.05, hash builds 1.5, probes 1, join output 0.3, grouped aggregation 1, aggregation without grouping 0.2, sorts 0.1 per row and doubling, top-k 0.2, windows 1, hash repartitioning 0.2), on as many cores as the operator has partitions;
  • serial work on one core: single-partition operators, a hash table collected into one partition, merging sorted partitions;
  • spill: aggregation and sort state beyond the node's memory pool, written and read back once;
  • output: the result's bytes.

The parts are added, not overlapped, so the estimate leans long when scans and compute overlap. Queueing is not included. Every row estimate has a plausible range, and the estimate is reported with its range: every row estimate at the low, or the high, end of its own range. The query's memory is estimated too: hash join build sides (twice their size while they are concatenated) and window buffers cannot spill; aggregation and sort state can.

Below SQL_SINGLE_MAX_ESTIMATED_SECONDS the query is a single candidate, below SQL_STREAMING_MAX_ESTIMATED_SECONDS a streaming candidate, and otherwise a scales candidate, which runs in scales mode only with SQL_AUTO_SCALES on. SQL_ROUTING_UNCERTAINTY picks the end of the range compared with the thresholds; when the range spans a threshold the reason says so. Each mode the node can run is then weighed for the query, with the work and state divided among the ready members for distributed modes (other members are assumed to have this node's memory pool and spill space), exchanges over the network (streaming) or through intermediate storage (staged), and the per-stage overheads:

  • A mode is infeasible when it needs more state that cannot spill per member than seven eighths of the memory pool (the budget admission gives such state, see Admission), more spill than the spill space left (or any spill with spilling disabled), or, for distributed modes, fewer than two ready members. An infeasible candidate gives way to the next feasible mode (single to streaming, then scales; streaming to scales, then single; scales to streaming, then single), and scales only with SQL_AUTO_SCALES on.
  • When the selected mode is estimated to take longer than the time left before the deadline and another feasible mode is not, the query runs in the fastest such mode. The deadline itself never changes.

The query runs on its owner alone without a pool, when fewer than two members are ready, and for metadata statements. A query whose scans do not all know their stored size and rows is not estimated: auto uses the fallback mode, single. An explicitly requested mode is never replaced; when the estimates expect it to run out of memory or spill space, or to pass its deadline, the decision carries warnings instead. streaming always distributes (on a node with a pool). The response's execution reports the decision: its reason, the estimate with its range, breakdown and memory, every candidate with its estimate and feasibility, warnings and, for distributed modes, the stages and their task counts.

Staged execution. scales plans a query exactly as streaming does (the same stages, tasks and scan assignments) but runs the stages one after another instead of all at once: every task of a stage writes its output to the intermediate storage, the owner commits the stage once all its tasks succeeded, and the stages above read the committed outputs. The owner runs at most SQL_SCALES_MAX_RUNNING_TASKS tasks of a query at once, each a distributed task on a ready member. A task that fails for a reason another attempt may avoid (the intermediate storage failed, the member had no task slot or memory, the member stopped or could not be reached) runs again, on another member when there is one, up to SQL_SCALES_TASK_ATTEMPTS attempts; other failures, such as an invalid computation, fail the query at once, and retries never extend its deadline. Outputs of attempts that were not committed are never read, and a read of a committed output that fails for a passing reason (a storage timeout, say) is tried again where it stopped.

When a committed output is lost or damaged (intermediate_missing: it was deleted, or no longer decodes), the owner recomputes it from its lineage: it finds the producer tasks whose committed outputs are gone, runs them again (and the tasks below them whose outputs are gone too), commits the producer stage's next generation, and runs the failed consumer tasks again. Consumer tasks that already read a recomputed task's old output keep their results only when the producer stage is reproducible, that is, running its tasks again writes the same rows to the same partitions: no volatile functions (random(), ...), limits, windows or order-dependent aggregates in it or below it (floating-point sums count as order-dependent). Otherwise they run again too, so no consumer combines two runs of one task. The owner's last stage verifies what it reads before it starts and can start again only before it returned rows; an output lost after that fails the query with intermediate_missing. Recomputations count against SQL_SCALES_TASK_ATTEMPTS like retries, and never extend the deadline.

When the query ends, however it ends, its intermediate outputs are removed (and once more a few seconds later, for attempts that were still running). A query does not outlive its owner's process: when an owner stops before removing them, its node removes them as soon as it starts again, and every member removes what is still left once it is older than SQL_SCALES_RETENTION_SECONDS. Since a node that starts removes what every earlier process with its node ID left, give each pool its own intermediate storage. Stages run to completion before the next starts, so a staged query is slower than a streaming one, in exchange for surviving the loss of a member, a failed task or lost intermediate outputs. auto selects scales only with SQL_AUTO_SCALES on.

EXPLAIN. EXPLAIN reads no data and runs on the node that receives it, but it is routed as the statement it explains would be (with the request's execution mode), and its execution and estimate are that statement's. Its output ends with a routing row (mode, reason, the estimate with its range, breakdown, state and basis, the candidates, warnings and, for distributed modes, the stages and their tasks) and, when the statement would be distributed, a distributed_plan row showing each stage, its tasks and the fragments each task scans (for scales, under a ScalesExec line with the intermediate storage). EXPLAIN ANALYZE runs the statement in the chosen mode; when it streams, its plan includes the metrics of every stage, when it is staged, its ScalesExec line reports the attempts, retries, recomputations and every stage's tasks, rows and bytes written, followed by the owner's stage reading the committed outputs with its metrics; its output ends with the routing row.

Failures. A streaming query whose member fails or becomes unreachable fails with an explicit error; it is not retried or re-run elsewhere (a staged query retries the failed task as described above). Status, results and cancel requests sent to a member that does not own the query are forwarded once to the owner, which answers (the response carries x-lance-query-owner); when the owner cannot be reached they fail with owner_unreachable, and when it restarted, with owner_lost.

Tables

Each store registry is a SQL schema, and each registered store is a table:

lance.<kind>.<store name>      kind: rollout | generic | datagen

Unqualified names use the default schema, so SELECT * FROM events reads lance.generic.events. Identifiers follow DataFusion rules: unquoted names are lower-cased, so quote names with upper-case letters or punctuation, as in lance.rollout."Exp-1".

The registries stay authoritative: every query resolves its tables through them, and column types, fragments and versions come from each store's Lance dataset. A query reads exactly one committed dataset version per table, chosen when it is planned (or pinned by the request), even when it references a table several times. Rows that are still in a store's write-ahead log (appended but not yet merged into its dataset) are not visible to SQL.

Statements

One read-only statement per request:

  • SELECT, WITH, VALUES and set operations, with joins, aggregates, windows, subqueries, ORDER BY, LIMIT and OFFSET;
  • SHOW TABLES, SHOW COLUMNS FROM t, DESCRIBE t and information_schema views;
  • EXPLAIN and EXPLAIN ANALYZE.

Writes, DDL, transactions and session statements are rejected with statement_not_allowed. Clauses that DataFusion would parse but ignore, such as TABLESAMPLE, FOR UPDATE or GROUP BY ... WITH ROLLUP, are rejected with unsupported_sql rather than silently changing the result.

Functions are DataFusion's, except that array_agg and string_agg with ORDER BY always sort their own rows. DataFusion runs one of two aggregates whose orders are the reverse of each other in reverse, to share one sort, and its version 54 returns such an array_agg or string_agg out of order.

API

Endpoint Behavior
POST /api/v1/sql Parse, bind, plan and submit. Returns 202 Accepted with the query's id, schema, bound versions, execution mode and URLs. Planning errors are returned directly and create no query.
GET /api/v1/queries/{id} Status, error and statistics.
GET /api/v1/queries/{id}/results The results, once: JSON by default, NDJSON with ?format=ndjson.
DELETE /api/v1/queries/{id} Cancel: stop execution and discard undelivered results.
GET /api/v1/sql/ready Readiness: 200 while the node takes queries, 503 once it drains or has stopped (see Draining).
GET /api/v1/sql/pool This node's state and the state of every query pool member (see Query pools).

Submitting

curl -s http://localhost:3000/api/v1/sql -H 'content-type: application/json' -d '{
  "sql": "SELECT category, COUNT(*) AS n FROM lance.generic.events WHERE value >= $1 GROUP BY category",
  "parameters": [{"type": "Float64", "value": 10.0}],
  "format": "json",
  "execution": "auto",
  "timeout_ms": 30000
}'
Field Meaning
sql The statement.
parameters Typed values for $1, $2, ... (an array) or $name (an object), each {"type": ..., "value": ...}. Types are SQL names (BIGINT, DOUBLE, VARCHAR, DATE, TIMESTAMP, DECIMAL(p, s), BOOLEAN, BYTEA) or the Arrow type names results report. Values convert exactly or fail: 64-bit integers may be strings, decimals and temporal values are strings, binary values are base64, null is a typed NULL.
format json (default) or ndjson: the results format when the results request does not choose.
execution auto (default), single, streaming or scales. single runs on the receiving node; streaming runs across the ready members of the node's query pool; scales runs across them in stages committed to intermediate storage, retrying failed tasks (staged execution); auto chooses one of them (routing). A mode the node cannot run (streaming without a pool, scales without intermediate storage, either for metadata statements) fails with unsupported_mode; it is never replaced by another mode.
timeout_ms End-to-end deadline from submission, across planning, queueing, execution and result delivery.
default_catalog, default_schema Override the defaults for unqualified names.
versions Pin dataset versions: [{"schema": "generic", "table": "events", "version": 12}] (schema and catalog default to the request's defaults). A pin that matches no table the query reads is an error.

The response describes the query:

{
  "query_id": "node-a.e3a45f833702.6c3ceb7ada0d4a76b94ca62c74d3d618",
  "state": "queued",
  "results": "pending",
  "statement": "query",
  "execution": {"requested": "auto", "mode": "single",
                "reason": "auto: no query pool is configured, so the query runs locally",
                "estimate": {"single_node_seconds": 0.0012, "low_seconds": 0.0009,
                             "high_seconds": 0.0019,
                             "breakdown": {"scan": 5.5e-6, "compute": 0.0011, "serial": 0.0001,
                                           "spill": 0.0, "exchange": 0.0, "stages": 0.0,
                                           "output": 2.1e-6},
                             "memory": {"required_bytes": 0.0, "peak_bytes": 3584.0,
                                        "spill_bytes": 0.0},
                             "output_rows": 40.0, "exchange_bytes": 9000.0, "exchanges": 1,
                             "scan_bytes": 5938, "scan_rows": 500, "heavy_operators": 2,
                             "basis": "..."},
                "candidates": [{"mode": "single", "workers": 1, "seconds": 0.0012,
                                "low_seconds": 0.0009, "high_seconds": 0.0019,
                                "required_bytes": 0.0, "spill_bytes": 0.0}]},
  "schema": {"fields": [{"name": "category", "type": "Utf8", "nullable": true, "encoding": "string"},
                        {"name": "n", "type": "Int64", "nullable": false, "encoding": "int-string"}]},
  "bindings": [{"catalog": "lance", "schema": "generic", "table": "events", "version": 3, "pinned": false}],
  "estimate": {"scans": 1, "fragments": 1, "rows": 500, "bytes": 5938},
  "status_url": "/api/v1/queries/node-a.e3a45f833702.6c3ceb7ada0d4a76b94ca62c74d3d618",
  "results_url": "/api/v1/queries/node-a.e3a45f833702.6c3ceb7ada0d4a76b94ca62c74d3d618/results"
}

A query distributed across a pool (streaming or staged) also reports its plan's stages, for example "distribution": {"distributed": true, "ready_workers": 2, "stages": [{"stage": 1, "tasks": 2}, {"stage": 2, "tasks": 2}]}.

state is queued, running, succeeded, failed, cancelled or expired; results is pending, reading, streaming, delivered or discarded. stats reports planning, queueing, time to first batch and execution time in milliseconds, the rows produced and delivered, and where the query ran:

Field Meaning
execution_tasks Distributed tasks the query ran, on any pool member (for a staged query, every attempt). 0 for a query that ran on its owner alone.
remote_execution_tasks Those tasks that ran on members other than the owner.
task_retries Staged task attempts that failed and ran again; 0 for other modes.
recomputed_tasks Staged tasks that ran again because committed intermediate outputs were lost: the tasks that wrote them, and consumer tasks whose inputs changed; 0 for other modes.
shuffle_bytes Bytes the query's stages read from each other over the network (a task's output read in process by the owner is not counted), or for a staged query, wrote to the intermediate storage. 0 for a query that ran on its owner alone; absent while a streaming query runs, and when some task's metrics never arrived.
stages For a completed distributed query (for a staged query that did not complete, the stages it committed), per stage: stage, tasks, the rows its tasks produced (output_rows, and min_task_rows/max_task_rows over its tasks, which show skew) and its shuffle_bytes.

A streaming stage of one task runs on the owner. A larger stage places its tasks round-robin over the ready members, starting one member further for each stage. Staged tasks are placed round-robin over the ready members, the owner included, and a retried task avoids the members it failed on.

Results

Results are delivered once. A second results request gets 409 results_consumed; the query is never re-executed. Rows are arrays in schema order.

JSON (default) returns the complete result in one document:

{"query_id": "...", "state": "succeeded", "schema": {...}, "stats": {...},
 "row_count": 2, "rows": [["c0", "96"], ["c1", "96"]]}

A result over SQL_JSON_MAX_ROWS or SQL_JSON_MAX_BYTES fails with 422 result_too_large instead of being truncated. Nothing is lost: the same results can then be read as NDJSON.

NDJSON (?format=ndjson, application/x-ndjson) streams one JSON object per line:

{"type":"schema","query_id":"...","schema":{"fields":[...]}}
{"type":"rows","rows":[["e0000","9007199254740993",true], ...]}
{"type":"complete","query_id":"...","row_count":500,"stats":{...}}

The last line is complete on success or {"type":"error","error":{"code":...,"message":...},"row_count":...} on failure. Only a complete record means the result is complete: an HTTP 200 response that ends without one (for example because the connection broke) is not a successful result. Rows arrive in the order of the query's final plan, so ORDER BY order is preserved.

Value encodings

Values are encoded so that clients recover them exactly, including clients whose numbers are doubles. Each schema field reports its encoding:

encoding Arrow types JSON value
null Null null
boolean Boolean true / false
number 8–32-bit integers, floats number; "NaN", "Infinity", "-Infinity" as strings
int-string Int64, UInt64, Duration decimal integer string (durations count the type's unit)
decimal-string decimals exact decimal string, e.g. "12.30"
string strings string
base64 binary standard base64
date Date32, Date64 "2024-02-29"
time Time32, Time64 "12:34:56.789"
timestamp Timestamp RFC 3339; with the zone's offset (Z for UTC) when the type has a time zone, without an offset when it has none
interval intervals {"months":..,"days":..,"nanoseconds":".."} (the type's components)
array lists array
object structs object
map maps array of [key, value] pairs
display other types Arrow's display text

SQL NULL is always null. Nested fields list their element or member fields under children.

Errors

Errors are {"error": {"code": "...", "message": "..."}}:

Code HTTP Meaning
invalid_request 400 Malformed body, parameters, options or version pins.
invalid_sql 400 Syntax error, unknown table/column/function, type error.
unsupported_sql 400 Valid SQL this engine does not support.
statement_not_allowed 400 Not exactly one read-only statement.
too_many_tables 400 The query binds more than SQL_MAX_TABLES_PER_QUERY tables.
unsupported_mode 400 The requested execution mode is not available.
query_not_found 404 Unknown query id, or its record has expired.
results_consumed, results_busy 409 The results were already read, or another request is reading them.
cancelled 409 The query was cancelled.
source_unavailable 409 A bound dataset version or file cannot be read. The query never falls back to another version.
query_expired 410 The results were not fetched in time.
owner_lost 410 The process that owned the query restarted; its state is gone.
result_too_large 422 The result exceeds the JSON bounds; read it as NDJSON.
owner_unreachable 502 The query's owner node cannot be reached.
catalog_unavailable 503 A store registry cannot be read.
resources_exhausted 503 The query exceeded the memory or spill budget, or a pool member had no task slot left, or no pool member was ready.
overloaded, shutting_down 503 Admission limits reached, or the node is stopping; retry later (Retry-After).
intermediate_missing, intermediate_unavailable 503 Staged (scales) execution lost an intermediate output it could not produce again, or its intermediate storage failed after the task retries ran out.
deadline_exceeded 504 The query's deadline passed.
execution_failed, internal 500 Execution failed.

Query lifecycle

A query id names the node and process that own the query (<node>.<instance>.<token>). Status, results and cancellation must reach that process; pool members forward them to it. A request for a query owned by a process that has since restarted fails with owner_lost rather than re-running anything. No other process takes over a lost owner's queries; SQL query owner recovery records what that would take and when it would pay.

A query ends when its results have been delivered, or when it fails, is cancelled, passes its deadline, or its results go unread for SQL_RESULT_IDLE_TIMEOUT_MS. Execution pauses while its result buffer is full, so an unread query holds no more than a few batches. Cancelling, a client that disconnects from an NDJSON stream, and node shutdown all stop the query's scans and release its resources. Finished queries keep their final status for an hour (up to 10 000 queries) so clients can still read it.

Draining

On SIGTERM (or Ctrl+C) a node drains before it stops:

  • It takes no new queries. POST /api/v1/sql answers 503 shutting_down, and GET /api/v1/sql/ready answers 503 with "state": "draining", so a load balancer that probes it stops sending requests. While the node takes queries, that endpoint answers 200 with "state": "ready".
  • The queries it has keep running, and HTTP keeps serving: clients read their status and results directly or through other members.
  • Its worker endpoint answers the other members' probes that it is draining. They place no new tasks on it, and it finishes the tasks it has for their queries.
  • Once no query is open, no task runs and the intermediate outputs of the staged queries that ended are removed (a few seconds after the last one ended), or after SQL_DRAIN_TIMEOUT_MS, it stops: queries still open are cancelled with shutting_down. What their intermediate outputs leave behind, the node removes when it starts again. Tasks still running for other members' queries end with the process, and those queries fail with an explicit error, or, in scales mode, retry the task on another member.

A query whose results nobody reads stays open until the drain's deadline, so an idle node stops at once and a busy one within SQL_DRAIN_TIMEOUT_MS. Give the process manager a longer grace period than the drain, for example a Kubernetes terminationGracePeriodSeconds above it (the default 30 s fits the default 20 s drain). Merges stop at the signal as before, and storage requests HTTP accepts meanwhile complete.

Admission

A query that a node accepts (within SQL_MAX_QUEUED_QUERIES) is queued until it may run on its owner, and queued_ms in its stats says for how long. Two classes share the SQL_MAX_RUNNING_QUERIES slots: queries the routing estimate expects to run within SQL_INTERACTIVE_MAX_ESTIMATED_SECONDS in the mode they run in are interactive; the others, and queries without an estimate, are heavy. Each class runs in arrival order, but heavy queries leave SQL_INTERACTIVE_SLOTS slots to interactive ones, so a burst of heavy queries cannot keep short ones waiting, and while a heavy query waits for a slot, interactive queries leave it the last one.

With SQL_MEMORY_ADMISSION (the default), a query also waits until seven eighths of the memory pool can hold the state its estimate says cannot spill (hash join build sides, window buffers), next to what the running queries' estimates hold; queries that hold no such state, such as scans, filters and aggregations, which spill, never wait for memory. The last eighth of the pool stays for the operators that spill, which need memory to spill too (an aggregation sorts its state before writing it out), and for estimates that fall short. The first heavy query waiting for memory holds its place: interactive queries are admitted next to it only within what it leaves. A query estimated to need more than those seven eighths runs when nothing else does. Estimates can be wrong, so the pool itself still enforces its limit, and SQL_QUERY_MEMORY_LIMIT_BYTES caps what one query holds.

A query's metadata reports how it was admitted, execution.admission: its class and the memory_bytes it holds in the budget while it runs; EXPLAIN shows the same in its routing row. Its stats.peak_memory_bytes is the most memory its operators held at once in the owner's pool (for a distributed query, its part on the owner). A query leaves the queue when it is cancelled or its deadline passes.

Metrics

The server's /metrics endpoint exports the SQL engine's series. Labels are bounded (mode, state, error code, placement, outcome); per-query detail such as stages and their rows is in each query's stats, not in labels.

Series Type Meaning
sql_queries_total{mode, state} counter Queries that finished executing on this node, their owner. mode is single, streaming or scales; state is succeeded, failed, cancelled or expired.
sql_query_duration_seconds{mode} histogram Submission-to-completion time of queries that succeeded (10 ms to 1 h buckets).
sql_rejected_total{code} counter Submissions that created no query, by error code (invalid_sql, overloaded, ...).
sql_running_queries gauge Queries executing on this node now.
sql_queued_queries{class} gauge Queries waiting to run on this node, their owner: interactive or heavy.
sql_admitted_memory_bytes gauge Estimated state that cannot spill the running queries hold in this node's admission budget.
sql_execution_tasks_total{placement} counter Distributed tasks of the queries this node owns: owner (run here) or remote.
sql_shuffle_bytes_total counter Bytes the stages of the queries this node owns read from each other over the network, or in staged (scales) execution wrote to the intermediate storage.
sql_task_retries_total counter Staged task attempts of the queries this node owns that failed and ran again.
sql_task_recomputes_total counter Staged tasks of the queries this node owns that ran again because committed intermediate outputs were lost.
sql_worker_tasks_total{outcome} counter Tasks this node's worker was asked to run for any member's queries: admitted or rejected at SQL_WORKER_MAX_TASKS.
sql_worker_running_tasks gauge Tasks this node's worker runs now.
sql_worker_refused_calls_total counter Worker calls refused for lacking the pool secret.
sql_pool_ready_members gauge Pool members, this node included, ready to run tasks at the last probe.

Process memory (process_resident_memory_bytes) and CPU are exported as well, for watching a node's footprint while it runs queries.