# Quixote > Experimental C++20 query engine for Apache Arrow data and Parquet files. # Start # Quixote Quixote is an experimental C++20 query engine for Apache Arrow data and local Parquet files. It is built to explore vectorized execution, standalone Parquet I/O, explicit memory budgets, and Arrow C Data/C Stream interoperability from Python and C++. Build a physical query plan in Python or C++, give it Arrow data or Parquet files, then collect the result, stream batches, or write a Parquet file. Both APIs are experimental and Quixote has no SQL parser. ## Start here 1. [Install Quixote]() from PyPI, from source, or as a C++ SDK. 2. Run the [Python]() or [C++]() quickstart. 3. [Read and write Parquet](). 4. Review [benchmarks and current status](). ## Current scope Quixote accepts 19 nullable scalar types (integers, floats, decimals, strings, bytes, dates, and timestamps) plus nested Struct, List, LargeList, and Map columns. See the [type table]() for the full list. - Filter rows, select columns, and compute expressions including linear-time UTF-8 regular expressions. - Compute sum, count, average, minimum, maximum, stddev, variance, and `any_value` across all rows or by group. Feed grouped results into follow-on filters, joins, or sorts. - Join two queries with inner, left, right, full, semi, anti, or cross joins, with optional post-join predicates. - Sort rows by one or more keys (preserving input order on ties) and limit or offset results. - Apply window functions or combine inputs with union, intersection, and difference. - Spill large sorts, grouped aggregates, intersections, and differences to a local directory when memory is constrained. - Inspect operator time, rows, memory, and I/O with [profiling](). The standalone [Parquet reader and writer]() handle flat and nested columns without linking `libarrow` or `libparquet`. Scans can skip row groups and indexed pages, filter dictionary IDs, and apply runtime filters from joins. See [behavior and limits]() for type, ordering, and memory rules. The source repository includes Python physical plans for TPC-H Q01 through Q22 in `benchmarks/tpch/`. Download the [page index]() or the [complete guide with examples](). # Installation Install `quixote-engine` and import it as `quixote`. Use an isolated virtual environment because the unrelated `quixote` web framework uses the same import name. ## Python wheel Prebuilt wheels target regular CPython 3.11 through 3.14 on Linux x86-64 (`manylinux_2_28`) and Apple Silicon (macOS 15 or later). The wheel needs no compiler and has no runtime Python dependencies. Install PyArrow alongside it if you want to pass PyArrow batches and tables in the examples: ``` uv venv .venv --python 3.14 uv pip install --python .venv/bin/python quixote-engine pyarrow uv run --no-project --python .venv/bin/python python -I -c 'import quixote; print(quixote.__version__)' ``` With `pip` in an active virtual environment: ``` pip install --pre quixote-engine pyarrow ``` (`--pre` is needed while releases are alpha pre-releases such as `0.1.0a1`.) ## Python from source From a Git checkout or unpacked source archive, you need `uv` and a C11/C++20 toolchain: ``` uv venv .venv --python 3.14 uv pip install --python .venv/bin/python . pyarrow uv run --no-project --python .venv/bin/python python -I examples/getting_started.py ``` The quickstart prints a total of `36` for three rows. The build fetches CMake, Ninja, and Python build tools into an isolated build environment as needed. ## C++ SDK Building or consuming the C++ SDK requires CMake 3.28 or later and a C++20 toolchain. The SDK installs static libraries and its C++ ABI may change between revisions. To build and install the SDK from source with Parquet support: ``` cmake -S . -B build/sdk -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DQUIXOTE_BUILD_PARQUET=ON -DBUILD_TESTING=OFF cmake --build build/sdk --parallel 4 cmake --install build/sdk --prefix "$PWD/prefix" --component Development ``` Pass the installed prefix to CMake as `CMAKE_PREFIX_PATH` when building `examples/cpp`. The core and Arrow C interchange targets work without `libarrow` or Python. The Parquet target includes its codec and metadata libraries. ## Optional native components | Build option | CMake component | Link target | Use | | --- | --- | --- | --- | | `QUIXOTE_BUILD_PARQUET=ON` | `parquet` | `Quixote::parquet` | Read and write local Parquet files | | `QUIXOTE_BUILD_TBB=ON` | `tbb` | `Quixote::tbb` | Use shared oneTBB in place of the default thread pool | | `QUIXOTE_BUILD_ARROW_ADAPTER=ON` | `arrow_adapter` | `Quixote::arrow` | Use Apache Arrow C++ `RecordBatch` and reader objects | Request installed components with `find_package`, for example `find_package(Quixote CONFIG REQUIRED COMPONENTS parquet)`. TBB and the Arrow adapter require their respective libraries. Python builds with TBB enabled accept `Runtime(cpu_executor="tbb")`. # Queries # Python With Quixote and PyArrow installed, run `examples/getting_started.py` to filter a nullable Arrow column, compute a total and stream the selected values. ``` """Run with an installed Quixote wheel and the optional PyArrow consumer.""" import pyarrow as pa import quixote as qe def run(): data = pa.record_batch({"x": pa.array([1, 2, None, 600, 3], type=pa.int64())}) with qe.Runtime(cpu_threads=2, io_threads=1, memory_limit="4 MiB") as runtime: with qe.Session(runtime, query_memory_limit="1 MiB") as session: query = session.from_arrow(data).filter(qe.col("x") < 512).select( (qe.col("x") + 10).alias("value")) print(query.explain()) result = query.select(qe.col("value").sum().alias("total"), qe.count_rows().alias("rows")).collect() with query.stream() as stream: retained = pa.RecordBatchReader.from_stream(stream).read_all() assert retained.to_pydict() == {"value": [11, 12, 13]} table = pa.table(result) assert table.to_pydict() == {"total": [36], "rows": [3]} return table if __name__ == "__main__": print(run()) ``` The filter keeps 1, 2 and 3. Adding 10 gives 11, 12 and 13, for a total of 36. The example reads the result after the session and runtime close. ## Group and sort To find the two regions with the highest average sale, group by region and sort the averages. The second sort key breaks ties by region name. ``` """Find the two regions with the highest average sale.""" import pyarrow as pa import quixote as qe sales = pa.record_batch({ "region": ["west", "east", "east", "west", "north"], "amount": [12.0, 5.0, 15.0, None, 7.0], }) with qe.Runtime() as runtime, qe.Session(runtime) as session: averages = session.from_arrow(sales).group_by("region").agg( qe.col("amount").avg().alias("mean_sale") ) ranked = averages.sort("mean_sale", "region", descending=[True, False]).limit(2) result = ranked.collect() table = pa.table(result) assert table.to_pydict() == {"region": ["west", "east"], "mean_sale": [12.0, 10.0]} print(table) ``` Use `qe.col("sale").stddev_samp()` or `.var_samp()` for a sample. Use `.stddev_pop()` or `.var_pop()` for the whole population. To keep an arbitrary non-null label per group, include `qe.col("label").any_value()` in `agg()`. You can also filter, select or aggregate again after grouping. Operations run in their written order. Filtering before a limit can give a different result from limiting before the filter. To page through sales by amount, choose a fallback for missing payments, round the amount, then skip the first row in sort order. ``` """Show the second sale by amount, with its calendar day and rounded magnitude.""" from datetime import datetime import pyarrow as pa import quixote as qe sales = pa.record_batch({ "sold": pa.array([datetime(1969, 12, 31, 22), datetime(2025, 1, 4, 15)], pa.timestamp("us")), "paid": pa.array([None, -12.25], pa.float64()), "quoted": [15.75, 18.00], }) with qe.Runtime() as runtime, qe.Session(runtime) as session: amount = qe.coalesce(qe.col("paid"), qe.col("quoted")) query = session.from_arrow(sales).select( qe.col("sold").date_trunc("day").alias("day"), amount.abs().round(1).alias("amount"), ) page = pa.table(query.sort("amount", descending=True).limit(1, offset=1).collect()) assert page.to_pydict() == {"day": [datetime(2025, 1, 4)], "amount": [12.3]} print(page) ``` ## Profile a query See [Profile a query](<../profiling/index.md>) for operator timings, memory use and execution traces. ## Build and run a query - Use `session.from_arrow()` with an Arrow C Array or C Stream producer. A PyArrow RecordBatch can run repeatedly. Import a PyArrow Table again for a separate execution because it supplies a single-use stream. - Pass names or expressions to `select()`. Use `qe.col("amount")` to refer to a column and `.alias("name")` to name an output. Use `datetime.date` and `decimal.Decimal` for date and exact decimal literals. Pass `bytes` to `qe.lit()` for Binary. A naive or UTC `datetime.datetime` creates a microsecond timestamp. Use `qe.float32` in casts and `qe.lit_float32(1.5)` for a single-precision literal. A Python float passed to `qe.lit` uses Float64. A Python integer passed to `qe.lit` uses Int64. Use typed literals such as `qe.lit_int8(-128)` and `qe.lit_uint64(2**64 - 1)`. Cast with descriptors such as `qe.uint16`. Integer membership lists accept the full UInt64 range. Use `qe.Type.date64()`, `qe.Type.large_utf8()`, `qe.Type.large_binary()`, `qe.Type.binary()`, `qe.Type.timestamp("us")` or `qe.Type.timestamp("us", tz="UTC")` to compare schema descriptors. - Use `qe.col("ordered").date_add_days(7)` to add a week and `qe.col("shipped").date_diff_days(qe.col("ordered"))` to count elapsed days. Extract calendar parts with `.month()` and `.day()`. - Use `qe.col("name").trim().lower()` to remove surrounding spaces and lowercase ASCII letters. Chain `.concat(other)` to append another string. Use `.replace(old, new)` to replace literal text and `.split_part("/", -1)` to take the last field of a path. To extract the digits from a label such as `"item-42"`, use `qe.col("label").regexp_extract(r"item-(\d+)", 1)`. See [Behavior and limits](<../semantics/index.md>) for whitespace and length rules. - Use `qe.null_if(qe.col("amount"), 0)` to treat zero as missing. Use `qe.col("amount") % 10` to compute a remainder. - Combine parenthesized comparisons with `&`, `|` and `~`. - Read `query.schema` or call `query.explain()` to inspect a plan before execution. Call `collect()` or `stream()` to read results. Use `sink_parquet(path)` or `write_parquet(path)` to write them to a file. - Read a collected result with `pa.table(result)` or `polars.from_arrow(result)`. To read incrementally, use `with query.stream() as stream:` and pass each batch to `pa.record_batch(batch)`. The context manager closes the stream even if you stop early. Set `memory_limit` on an execution to override the session's query budget. Byte limits accept integers or strings such as `"64 MiB"`. Set `max_contexts=1` to run with one execution context. The wheel includes typed Python signatures. Read `runtime.stats()` after collection to see how much memory the query used. `peak_working_bytes`, `peak_reserved_bytes` and `peak_held_bytes` give the maximum working, reserved and caller-held bytes over the runtime's lifetime. Use a fresh runtime to measure one query. ## Window functions Rank sales within each region and show the cumulative total on every sale. The two sales tied for first place both include the full tie in their total. ``` """Rank sales and keep a running total within each region.""" import pyarrow as pa import quixote as qe sales = pa.record_batch({ "region": ["east", "west", "east", "east"], "amount": [10, 8, 10, 5], }) with qe.Runtime() as runtime, qe.Session(runtime) as session: query = session.from_arrow(sales).window( qe.rank().alias("place"), qe.col("amount").sum().alias("total"), partition_by="region", order_by=qe.SortKey("amount", descending=True), ) result = pa.table(query.sort("region", "place").collect()) assert result["place"].to_pylist() == [1, 1, 3, 1] assert result["total"].to_pylist() == [20, 20, 25, 8] print(result) ``` Use `qe.col("amount").lag(default=0)` to read the preceding sale in the same region. Chain another `window()` to change the partition or ordering. ## Disk spilling Pass `spill_directory` to `Runtime` to let sorts, grouped aggregates and set operations write temporary runs. For example, `Runtime(spill_directory=path, max_spill_bytes="16 GiB")` caps live runs across queries. ## Compare two query results Use `left.intersect(right)` for rows in both queries and `left.except_(right)` for rows found only on the left. To compare counts as well, pass `all=True`. For example, `actual.except_(expected, all=True)` returns the extra copies in `actual`. ## Count distinct values Use `distinct()` to keep one copy of each row. Use `count_distinct()` to count different non-null values in a group. Omit the keys in `group_by().agg(...)` to count across the whole input. ``` """Count suppliers per part, including parts with no known supplier.""" import pyarrow as pa import quixote as qe offers = pa.record_batch({"part": [1, 1, 1, 2], "supplier": ["A", "A", "B", None]}) with qe.Runtime() as runtime, qe.Session(runtime) as session: query = session.from_arrow(offers) assert query.distinct().collect().num_rows == 3 counts = query.group_by("part").agg(qe.col("supplier").count_distinct().alias("suppliers")) result = pa.table(counts.sort("part").collect()) assert result.to_pydict() == {"part": [1, 2], "suppliers": [2, 0]} print(result) ``` ## Nested Arrow columns Use `qe.col("order").struct_field("items")` to select a struct field. List expressions support `list_length()`, `list_element(index)` and `list_contains(value)`. Build a struct with ordered keyword arguments, such as `qe.struct_(id=qe.col("id"), items=qe.col("items"))`. Inspect child descriptors through `type.fields`, `list_type.value_field` and `list_type.value_type`. Construct them with `qe.Type.struct([qe.Field("id", qe.Type.int64)])`, `qe.Type.list_(item)` and `qe.Type.large_list(item)`. Declare a map with `qe.Type.map_(key_type, value_type, keys_sorted=True)`. Inspect `key_field`, `item_field` and `keys_sorted` on the type. Use `qe.col("labels").map_get("region")` to look up a value. Use `map_keys()`, `map_values()` or `list_length()` to get the keys, values or entry count. # C++ Use the installed SDK to query an Arrow array from a C++20 application. Build the supplied example from the source root, replacing `/path/to/sdk` with the SDK prefix: ``` cmake -S examples/cpp -B build/quickstart -G Ninja -DCMAKE_PREFIX_PATH=/path/to/sdk cmake --build build/quickstart ./build/quickstart/quixote_quickstart ``` The program prints `total=36 rows=3`. Its CMake file links `Quixote::interchange`, which also links the core query engine. ``` cmake_minimum_required(VERSION 3.28) project(QuixoteQuickstart LANGUAGES CXX) find_package(Quixote CONFIG REQUIRED) add_executable(quixote_quickstart main.cc) target_link_libraries(quixote_quickstart PRIVATE Quixote::interchange) ``` The program imports a nullable Int64 array, filters it, computes a total and exports the result through Arrow C Data. The input buffers stay in scope while the query uses them. ``` // SPDX-License-Identifier: Apache-2.0 #include #include #include #include struct ExportedBatch { ArrowSchema schema{}; ArrowArray array{}; ~ExportedBatch() { if (array.release) array.release(&array); if (schema.release) schema.release(&schema); } }; int main() { using namespace quixote; const int64_t values[]{1, 2, 0, 600, 3}; const uint8_t valid = 0b11011; const void* buffers[]{&valid, values}; ArrowSchema schema{"l", "x", nullptr, ARROW_FLAG_NULLABLE, 0, nullptr, nullptr, [](ArrowSchema* p) noexcept { p->release = nullptr; }, nullptr}; ArrowArray array{5, 1, 0, 2, 0, buffers, nullptr, nullptr, [](ArrowArray* p) noexcept { p->release = nullptr; }, nullptr}; auto input = ImportArray(&schema, &array); auto runtime = Runtime::Make({2, 1, 4 * 1024 * 1024}); Session session(runtime, 1024 * 1024); auto result = session.FromTable(Table::FromBatches(input.schema(), {input})) .Filter(Col("x").Less(Lit(int64_t{512}))) .Select({Col("x").Add(Lit(int64_t{10})).Alias("value")}) .Select({Col("value").Sum().Alias("total"), CountRows().Alias("rows")}) .Collect(); ExportedBatch output; ExportArray(result.batches().front(), &output.schema, &output.array); session.Close(); runtime->Close(); int64_t total, rows; const auto* totals = output.array.children[0]; const auto* counts = output.array.children[1]; std::memcpy(&total, static_cast(totals->buffers[1]) + totals->offset * 8, sizeof(total)); std::memcpy(&rows, static_cast(counts->buffers[1]) + counts->offset * 8, sizeof(rows)); if (total != 36 || rows != 3) return 1; std::cout << "total=" << total << " rows=" << rows << '\n'; } ``` ## Build a query Start with `Session::FromTable`, `Session::FromSource` or `ScanParquet`. Use `Filter` to keep rows and `Select` to compute columns, or `GroupBy(keys, aggregates)` to reduce rows by key. Use `Lit(int64_t{10})` for an Int64 literal, `LitInt8(-128)` for Int8, `LitUInt64(UINT64_MAX)` for UInt64, `LitFloat32(1.5f)` for `Type::Float32`, `LitUtf8("west")` for text and `LitDecimal("0.05")` for an exact decimal. For opaque bytes, pass a length-aware `std::string_view` to `LitBinary`. Use `LitTimestamp({micros, true})` for UTC and `LitTimestamp({micros, false})` for a naive timestamp. Use `Type::Date64()`, `Type::LargeUtf8()` and `Type::LargeBinary()` for millisecond dates and 64-bit byte offsets. Check timestamp and binary types with `Type::Binary()`, `Type::TimestampUtc()` and `Type::TimestampUs()`. Dates use `std::chrono::sys_days`. Use `Col("shipped").DateDiffDays(Col("ordered"))` for elapsed days or `Col("ordered").DateAddDays(Lit(int64_t{7}))` for a date one week later. `Month()` and `Day()` extract calendar parts. For text, use `Trim()`, `LTrim()`, `RTrim()`, `Lower()`, `Upper()` and `Concat(other)`. `Length()` counts code points and `ByteLength()` counts bytes. Use `query.Limit(rows, offset)` to page through a sorted query. `Coalesce({a, b})` picks the first non-null value. Numeric expressions support `Abs()`, `Floor()`, `Ceil()` and `Round(digits)`. Use `Col("time").DateTrunc("hour")` to group timestamps by hour. Use `NullIf(a, b)` to clear matching values and `a.Modulo(b)` for remainders. Call `Replace(old, replacement)` on text or `SplitPart(delimiter, part)` to extract a field. In `Select` or `GroupBy`, use `StddevSamp()`, `StddevPop()`, `VarSamp()` and `VarPop()` to measure spread. Use `AnyValue()` to keep one non-null value in its original type. See [Behavior and limits](<../semantics/index.md>) for case and whitespace rules. Use `left.Intersect(right)` to keep common rows or `left.Except(right)` to keep rows found only on the left. Both return one copy per distinct row. Pass `true` as the second argument to intersect or subtract duplicate counts. `Query::Join` takes the right query, two lists of key names, a `JoinType`, an optional filter and a suffix for duplicate names. Use `JoinType::Right` to keep unmatched right rows or `JoinType::Full` to keep unmatched rows from both inputs. Key lists must be empty for `JoinType::Cross`. Use `query.Sort({{"key"}, {"total", true}})` to sort by ascending key and then descending total. Call `Collect()` for a table or `Stream()` for a move-only cursor. Both accept `ExecutionOptions` with `memory_limit` and `max_contexts`. Use `auto profile = query.Collect({.profile = true}).profile();` to capture one execution. Print `profile->Summary()` for operator timings and row counts. `ToJson()` returns the counters, `ToOtelJson()` returns OTLP/JSON, and `ToChromeTraceJson()` returns a trace you can open in Perfetto. A profiled stream exposes its profile after EOF or `Close()`. Use `WriteParquetWithProfile` to include writing in the profile. `FilterAggregate` times a fused predicate and partial sum. Trace storage uses the query budget, and `spans_dropped` reports omitted phases. Retained snapshots and their copies count toward caller-held memory. Read `Runtime::stats()` after a query finishes. In the returned `MemoryStats`, `peak_working_bytes` is the most working memory in use at once, `peak_reserved_bytes` is the largest total of active query reservations, and `peak_held_bytes` is the most memory held by callers. Each peak covers the lifetime of the runtime. Use `Expr::RegexpLike` to filter strings, `Expr::RegexpExtract` to select a match or capture, and `Expr::RegexpReplace` to replace it. Pass `true` as the third replacement argument to change every match. See [Behavior and limits](<../semantics/index.md>). ## Exchange Arrow data On success, `ImportArray` and `ImportStream` take ownership of the C structs and clear their release callbacks. On failure the caller retains ownership. Keep imported buffers immutable until release. Pass empty output structs to `ExportArray`, `ExportTable` and `ExportStream`. Each export stays valid after the runtime closes. Call each release callback when finished. Serialize all calls on a C Stream, including release. Check the return status of `get_schema` and `get_next`. At end of stream, `get_next` succeeds with a null array release callback. For a native `ResultStream`, `Next()` blocks until a batch, end of stream or failure. Use `WaitFor(duration)` for a bounded wait and `Close()` to stop early. Call blocking waits and close from application threads. ## Window functions Call `query.Window({"region"}, {{"sales", true}}, {Rank().Alias("place")})` to rank sales within each region, highest first. Use an empty vector for either set of keys. Each expression needs a unique output alias. Add `Col("sales").Lag(1, Lit(int64_t{0})).Alias("previous")` to the same call to read the preceding Int64 sale, with zero for the first sale in each region. ## Disk spilling Set `RuntimeOptions::spill_directory` to a writable directory to let sorts and grouped aggregates write temporary runs. Set `max_spill_bytes` to limit their combined live size across queries. ## Nested Arrow columns `Type::Struct({{"id", Type::Int64}, {"items", Type::List(Type::Utf8)}})` describes a record containing a list. Use `Type::LargeList` for 64-bit offsets. Pass a `Field` to either list constructor to preserve the item name, nullability and metadata. Use `StructField`, `ListLength`, `ListElement` and `ListContains` on expressions. `StructPack({{"id", Col("id")}, {"items", Col("items")}})` constructs a non-null struct in the given order. Build a map with `Type::Map(key_type, item_type)`. The overload taking two fields preserves their names, nullability and metadata. The key field must be required. Pass `true` as the third argument for sorted keys. Use `MapKeys()`, `MapValues()`, `MapGet(key)` or `ListLength()` on a map expression. # Parquet The standard Python build includes the standalone Parquet reader and writer. In C++, link `Quixote::parquet` and include ``. ## Read, query and write Run `examples/parquet_roundtrip.py` to filter two files together, append new rows from memory with `union_all`, and write the combined rows to Parquet. ``` """Create, query and write Parquet with an installed Quixote package.""" from pathlib import Path from tempfile import TemporaryDirectory import pyarrow as pa import quixote as qe def run(): data = pa.record_batch({"id": [1, 2, 3], "value": [10, None, 30]}) with TemporaryDirectory() as directory: parts = [Path(directory) / f"part-{i}.parquet" for i in range(2)] output_path = Path(directory) / "output.parquet" with qe.Runtime(cpu_threads=2, io_threads=2) as runtime: with qe.Session(runtime) as session: for part, rows in zip(parts, [data.slice(0, 2), data.slice(2)], strict=True): session.from_arrow(rows).sink_parquet(part) selected = session.scan_parquet(parts).filter( qe.col("value").is_not_null() ).select("id", "value") arrivals = session.from_arrow(pa.record_batch({"id": [4], "value": [40]})) selected.union_all(arrivals).sink_parquet(output_path) result = session.scan_parquet(output_path).collect() table = pa.table(result) assert table.to_pydict() == {"id": [1, 3, 4], "value": [10, 30, 40]} return table if __name__ == "__main__": print(run()) ``` `session.scan_parquet(path, columns=["x", "y"])` reads the footer and exposes those fields in that order. Include fields used by filters as well as outputs. Omit `columns` to select every field. Use `columns=[]` to count rows without reading value columns. Pass a nonempty iterable of paths to scan several files in the order given. Each path can be a string or a path object such as `pathlib.Path`. Quixote reads each footer when you build the query and schedules row groups across files when you run it. Selected fields must have the same names and types. If any file allows nulls in a field, the result allows nulls there. Keep the files unchanged while their queries exist. `query.sink_parquet(path)` writes row groups without collecting the whole result. The defaults are Zstd compression, 131072 rows per group and 8192 rows per page. Use `compression="snappy"`, `"lz4"`, `"gzip"` or `"uncompressed"` to change the codec. Set `row_group_rows` and `page_rows` to positive sizes with at least as many rows per group as per page. The writer closes the temporary file before publishing it. To replace an existing destination, pass `overwrite=True`. In C++, pass a path or a `std::vector` of paths to `ScanParquet`. Write with `WriteParquet(query, path, write_options, execution_options)`. ## Supported files Struct, List, LargeList and Map can contain any supported scalar or nested type. A null struct, a struct with all-null fields, an empty list and a list with one null element each retain their meaning. Select a top-level column by name to read its children together. A filter on a sibling scalar column can skip whole row groups before reading those children. The writer uses standard Parquet LIST and MAP annotations. The reader also accepts older two-level lists and bare repeated fields. Embedded Arrow schema metadata preserves LargeList, LargeUtf8, LargeBinary and the sorted map key flag. Readers that ignore this metadata use their own offset widths. Each selected nested column is assembled one row group at a time against the query memory limit. Reduce the row group size when writing very large values. | Feature | Reader | Writer | | --- | --- | --- | | Boolean, all signed and unsigned integer widths, Float32, Float64, Utf8, Date32 | Required or optional fields | Preserves field nullability | | Binary, LargeBinary | Unannotated BYTE\_ARRAY | BYTE\_ARRAY | | LargeUtf8 | BYTE\_ARRAY with STRING or UTF8 annotation | BYTE\_ARRAY with STRING annotation | | Date64 | Parquet DATE reads as Date32 | INT32 with DATE annotation. Values must be midnight and fit Date32. | | Timestamp | INT64 with TIMESTAMP(MICROS) or legacy TIMESTAMP\_MICROS | TIMESTAMP(MICROS), preserving the UTC flag | | Decimal128 | Annotated INT32, INT64 or fixed-length bytes (1 to 16) | Chooses physical storage by precision | | Boolean encoding | PLAIN and RLE | PLAIN | | PLAIN and dictionary | Reads both for the other supported types, including dictionary fallback | PLAIN for all supported types. Dictionary for Int8, Int16, Int32, all unsigned integers, Float32, Float64, strings, bytes, Date64 and Timestamp when smaller | | BYTE\_STREAM\_SPLIT | FLOAT, DOUBLE, INT32, INT64 and fixed-length decimal bytes | For Float32 and Float64 pages without dictionary encoding, uses BYTE\_STREAM\_SPLIT when it compresses smaller than PLAIN | | DELTA\_BINARY\_PACKED | INT32 and INT64 storage, including dates and integer-backed decimals | Can choose delta for integer storage | | DELTA\_BYTE\_ARRAY and DELTA\_LENGTH\_BYTE\_ARRAY | Both offset widths for strings and bytes | Can choose either | | Data pages | V1 and V2 | V2 | | Compression | Uncompressed, Zstd, Snappy, LZ4\_RAW, Gzip | Same | Parquet stores dates in whole days. Writing a non-midnight Date64 raises an error. To discard the time explicitly, cast the column to Date32 before writing. The `"lz4"` option uses raw LZ4 blocks. The reader rejects legacy Hadoop-framed LZ4. The writer requires at least one output field. Encryption and external column files are unsupported. ## When a scan can skip data - Row-group null counts and usable min/max bounds can rule out entire groups before the scan reads their pages. For example, a date range can exclude a group whose latest date is too early. Quixote writes these statistics for narrow and unsigned integers, Binary, LargeBinary, LargeUtf8, Date64, Timestamp, Float32 and Float64. Unsigned pruning uses type-ordered bounds. Floating-point bounds exclude NaNs. The scan keeps groups that may contain a NaN matching the filter. - Quixote writes a page offset index for each column and a column index with per-page bounds and null counts. It omits the column index when a bound exceeds 256 bytes or the column chunk contains a NaN. A selective filter can use these indexes to skip pages in the filter and projected columns, even when their page boundaries differ. Unfiltered scans skip the indexes. - On dictionary-encoded Utf8 pages, the scan can test dictionary entries for equality, membership or a string pattern and filter rows by dictionary ID. It can still evaluate the predicate when a later page uses plain encoding. - Inner and semi joins on Int32, Int64 or Date32 keys can pass a runtime filter from the right input to the left scan. The scan can skip groups outside the key range and discard rows before reading other columns. A surviving row may still require reading and decompressing a whole page. A large page or dictionary can exceed the query's memory budget. ## Run TPC-H Q6 From the source tree, run the shipped query on the small lineitem fixture: ``` uv run --no-sync python examples/tpch/q6.py tests/fixtures/tpch_q6.parquet ``` The fixture returns one Decimal128 revenue value, `19.0000`. Pass your own lineitem file in place of the fixture to run the query on its date, quantity, price and discount columns. ``` """Compute TPC-H Q6 revenue from a lineitem Parquet file.""" import argparse import datetime as dt from decimal import Decimal import pyarrow as pa import quixote as qe def q6(session, path): scan = session.scan_parquet(path, columns=[ "l_shipdate", "l_quantity", "l_extendedprice", "l_discount", ]) shipdate = qe.col("l_shipdate") discount = qe.col("l_discount") selected = ( scan.filter(shipdate >= dt.date(1994, 1, 1)) .filter(shipdate < dt.date(1995, 1, 1)) .filter(discount >= Decimal("0.05")) .filter(discount <= Decimal("0.07")) .filter(qe.col("l_quantity") < Decimal("24")) ) revenue = (qe.col("l_extendedprice") * discount).sum().alias("revenue") return selected.select(revenue) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("lineitem") parser.add_argument("--cpu-executor", choices=("thread_pool", "tbb"), default="thread_pool") args = parser.parse_args() with qe.Runtime(cpu_threads=4, io_threads=2, cpu_executor=args.cpu_executor) as runtime: with qe.Session(runtime) as session: print(pa.table(q6(session, args.lineitem).collect())) ``` # Profile a query Use `profile = query.collect(profile=True).profile`, then print `profile.summary()` to see each operator's input and output rows, worker time, I/O and spilling. Operator wall times add time across workers and may exceed elapsed query time. An operator’s memory peak records query working bytes while that operator allocates. `profile.to_dict()` returns the counters and phase spans. Save `profile.to_chrome_trace_json()` to open the timeline in Perfetto, or send `profile.to_otel_json()` to an OTLP/HTTP trace endpoint as `application/json`. For streamed results, read `stream.profile` after EOF or `close()`. `query.sink_parquet(path, profile=True)` returns the writer and query profile. A scan records reads during execution. Footer reads used to construct the query occur before profiling starts. `FilterAggregate` measures a fused predicate and partial sum. Its output row count is the number of rows that passed the predicate. Trace storage grows within the query memory budget. The timeline retains up to 65,536 phase spans and may retain fewer under memory pressure. `spans_dropped` counts the rest. Operator counters continue throughout. A retained profile counts toward the runtime’s caller-held memory until you release it. ## Save and compare profiles Run a TPC-H query from the source checkout against a generated dataset. ``` uv run --no-sync python benchmarks/tpch/profile.py --scale 10 --query Q09 \ --data-dir build/tpch-data/sf10 --out build/q09-before ``` Use `--query Q09,Q21` or `--query all` to write one subdirectory per query. Each TPC-H result must match its DuckDB golden. For your own query, pass `--script query.py` and define a function named `query(session)` that returns a Quixote query. Set `--threads`, `--io-threads`, `--memory-limit-gib` and `--spill-dir` to reproduce the runtime settings. Read `summary.txt` for the top five operators by share of query CPU. The bundle includes counters in `profile.json`, OTLP in `otel.json`, a Perfetto timeline in `trace.json` and run settings in `metadata.json`. Use `--cpu-profile` with the `profile` CMake preset to collect native CPU samples. Capture a second run in another directory to compare the counters. ``` uv run --no-sync python benchmarks/tpch/profile.py \ --compare build/q09-before build/q09-after --format markdown ``` The table shows head minus base. It matches physical operators by ID, name, detail and parent. Added and removed operators appear on separate rows. Omit `--format markdown` for plain text. # Reference # Benchmarks and status Quixote uses TPC-H Q01 through Q22 over local Parquet files as a correctness and performance test suite on Linux x86-64 (AVX2) and Apple Silicon (NEON). Results are checked against DuckDB 2.0.1 on the exact same Parquet files. These numbers are engineering reference points, not an apples-to-apples SQL engine comparison: - **No SQL parser**: Quixote runs hand-written physical query plans in `benchmarks/tpch/`, while DuckDB parses, plans, and optimizes SQL. - **Build flags**: Quixote is built with explicit `-O2 -g0 -DNDEBUG`, vendored static Zstd 1.5.7, and no Arrow C++ runtime dependency. - **Measurement setup**: 8 CPU threads for both engines (`2` I/O threads at SF 1.0 and SF 10; `8` I/O threads at SF 100), median of 5 runs (SF 1.0 / 10) or 3 runs (SF 100) after warmup on idle machines, with nominal Apple Silicon thermals and zero disk spill under the configured query limits (`2 GiB` / `4 GiB` / `8 GiB`). ## Scale summary (commit `8c70ca9`) All 22 queries matched DuckDB 2.0.1 outputs at every scale on both platforms. | Scale | Platform | Threads | Quixote total | DuckDB 2.0.1 ref | Ratio | Max peak working memory | | --- | --- | --- | ---: | ---: | ---: | ---: | | SF 1.0 | Linux x86-64 (AVX2) | 8 CPU / 2 I/O | 577.9 ms | 953.7 ms | 0.61x | 57.5 MiB | | SF 1.0 | Apple Silicon M4 (NEON) | 8 CPU / 2 I/O | 402.0 ms | 611.2 ms | 0.66x | 55.4 MiB | | SF 10 | Linux x86-64 (AVX2) | 8 CPU / 2 I/O | 4,629.7 ms | 7,744.6 ms | 0.60x | 177.7 MiB | | SF 10 | Apple Silicon M4 (NEON) | 8 CPU / 2 I/O | 3,972.7 ms | 6,018.0 ms | 0.66x | 169.9 MiB | | SF 100 | Linux x86-64 (AVX2) | 8 CPU / 8 I/O | 46,191.4 ms | 77,795.6 ms | 0.59x | 1,294.3 MiB | | SF 100 | Apple Silicon M4 (NEON) | 8 CPU / 8 I/O | 42,697.2 ms | 63,561.2 ms | 0.67x | 1,293.8 MiB | SF 100 spans roughly 23 GiB of local Parquet files (600 million `lineitem` rows). ## Per-query SF 100 breakdown (commit `8c70ca9`) Median elapsed milliseconds and peak working memory (`MiB`) per query at SF 100 (`8` CPU threads, `8` I/O threads, `16 GiB` runtime limit, `8 GiB` query limit): | Query | Linux Quixote (ms) | Linux DuckDB (ms) | Linux Peak (MiB) | M4 Quixote (ms) | M4 DuckDB (ms) | M4 Peak (MiB) | | --- | ---: | ---: | ---: | ---: | ---: | ---: | | Q01 | 2,205.4 | 3,293.0 | 20.0 | 2,592.1 | 2,830.0 | 19.5 | | Q02 | 456.0 | 735.7 | 110.6 | 375.7 | 553.8 | 108.8 | | Q03 | 2,469.8 | 4,076.7 | 786.1 | 2,143.2 | 2,971.0 | 784.5 | | Q04 | 1,464.2 | 2,410.7 | 421.1 | 1,370.4 | 1,945.0 | 472.9 | | Q05 | 2,833.8 | 4,333.4 | 254.0 | 2,581.4 | 3,535.7 | 253.6 | | Q06 | 1,074.8 | 1,810.2 | 11.0 | 1,009.3 | 1,434.5 | 11.0 | | Q07 | 2,994.7 | 4,009.0 | 349.9 | 2,454.5 | 3,272.4 | 349.5 | | Q08 | 3,514.2 | 5,367.2 | 208.1 | 3,429.3 | 4,258.2 | 208.0 | | Q09 | 5,291.0 | 7,319.9 | 1,294.3 | 4,505.0 | 6,365.1 | 1,293.8 | | Q10 | 2,560.8 | 4,332.6 | 1,071.8 | 2,091.5 | 3,253.1 | 1,041.8 | | Q11 | 384.0 | 636.7 | 410.5 | 304.3 | 543.7 | 396.5 | | Q12 | 1,422.0 | 2,268.2 | 99.8 | 1,581.3 | 1,757.0 | 97.9 | | Q13 | 2,586.1 | 5,117.1 | 326.5 | 2,588.6 | 4,844.0 | 326.2 | | Q14 | 1,985.5 | 2,854.8 | 642.3 | 2,046.2 | 2,486.3 | 642.2 | | Q15 | 2,125.3 | 2,715.6 | 701.3 | 1,956.5 | 2,270.6 | 696.8 | | Q16 | 409.1 | 720.1 | 332.9 | 344.1 | 562.8 | 331.1 | | Q17 | 1,903.8 | 4,435.3 | 135.3 | 1,951.4 | 3,494.2 | 131.7 | | Q18 | 1,509.9 | 6,027.7 | 26.0 | 1,272.3 | 4,337.3 | 26.0 | | Q19 | 1,992.2 | 3,066.4 | 37.0 | 2,176.6 | 2,701.9 | 36.9 | | Q20 | 2,184.1 | 3,315.9 | 202.2 | 2,187.6 | 2,801.2 | 191.0 | | Q21 | 4,252.9 | 7,960.9 | 1,073.0 | 3,307.7 | 6,604.4 | 1,084.6 | | Q22 | 571.8 | 988.5 | 261.6 | 428.3 | 739.0 | 256.1 | ## Current status | Area | Status | Notes | | --- | --- | --- | | Arrow scalar types | Implemented | 19 nullable types via Arrow C Data / C Stream | | Nested Arrow types | Implemented | Struct, List, LargeList, Map (including nested Parquet I/O) | | Physical operators | Implemented | Filter, project, joins (all 7 types), groupby, aggregates, sort, top-K, window, set ops, UTF-8 regex | | Standalone Parquet | Implemented | V1/V2 reader, V2 writer, Zstd/Snappy/LZ4\_RAW/Gzip, row-group and page-index pruning | | Spilling & budgets | Implemented | Query-wide working/reserved/held accounting; disk spill for sort, Grace joins, grouping, set ops | | Profiling | Implemented | Operator counters, JSON, OTLP/HTTP JSON, Perfetto traces (`QueryProfile`) | | SIMD dispatch | Implemented | Runtime AVX2 (x86-64) and NEON (arm64) kernels verified against scalar implementations | | Test suites | Passing | 45 native CTest suites, 1,974 Python tests (Linux), 16 relocated C++ SDK consumer checks | | SQL parser | Out of scope | Physical plan API only | | API & ABI stability | Experimental | Alpha (`0.1.0a1`); Python and C++ APIs may change | ## Reproduce locally From a source checkout with the `interop` dependency group installed: ``` uv run --no-sync python benchmarks/tpch/generate.py --scale 1.0 --out build/tpch-data/sf1.0 uv run --no-sync python benchmarks/tpch/eval.py \ --data-dir build/tpch-data/sf1.0 \ --mode benchmark --runs 5 --threads 8 --io-threads 2 \ --memory-limit "4 GiB" --query-memory-limit "2 GiB" ``` Replace `--scale 1.0` with `10` or `100` (adjusting `--memory-limit`, `--query-memory-limit`, and `--io-threads 8` for SF 100) to run the larger datasets. # Behavior and limits ## Values and reductions On empty input, a scalar aggregate returns one row and a grouped aggregate returns no groups. Sum, average, minimum and maximum ignore nulls and return null when there are no non-null values. `count()` counts non-null values, including false. `count_rows()` counts every selected row. Both counts return zero on empty input. Variance and standard deviation ignore nulls and return nullable Float64. Sample functions (`variance()` or `var_samp()`, `stddev()` or `stddev_samp()`) need at least two values. Population functions (`var_pop()`, `stddev_pop()`) return null for no values and zero for one value, including NaN or infinity. With two or more values, any NaN or infinity gives NaN. The result is also NaN if the Float64 calculation overflows. `any_value()` returns one non-null input with its original type, or null if there is none. The chosen value can vary with execution order. | Type | Operations and limits | | --- | --- | | Int8, Int16, Int32, Int64 | Addition, subtraction, multiplication and negation wrap at the result width. Scalar and grouped sums return Int64. | | UInt8, UInt16, UInt32, UInt64 | Addition, subtraction and multiplication wrap at the result width. Scalar and grouped sums return UInt64, modulo 2⁶⁴. Unsigned negation requires a cast. | | Float32, Float64 | Arithmetic, comparisons and reductions. NaNs compare equal to each other and sort after numbers in ascending order. | | Utf8, LargeUtf8 | Bytewise comparisons, sorting, grouping, string operations and regular expressions. | | Binary, LargeBinary | Raw bytes, including NUL. Compares in unsigned byte order. Use `byte_length()` to count bytes. | | Timestamp | Signed microseconds since 1970-01-01, timezone-naive or UTC. Comparisons and join keys require matching timezone types. | | Boolean | Equality, null tests and three-valued logic. | | Date32, Date64 | Signed days or milliseconds since 1970-01-01. Date64 comparisons use the stored milliseconds. Both support calendar parts and day arithmetic. | | Decimal128 | Precision 1 to 38 and scale 0 to precision. Supports exact addition, subtraction and multiplication. | | Struct | Ordered named fields. Extracting a field from a null struct returns null regardless of the child's stored value. | | Map | Ordered key-value pairs with required keys. Values can be nullable. | | List, LargeList | Ordered elements of one type, including nested values. List uses signed 32-bit offsets and LargeList uses signed 64-bit offsets. | A null list and an empty list are distinct. List length counts null elements. Element indices start at zero. Negative indices count from the end. An absent element returns null. Membership ignores null elements, returns false for an empty list, and returns null for a null list or a null needle in a nonempty list. Equality compares fields or elements in order. Two null children compare equal. A null value at the outermost level gives a null comparison result. Map keys and values keep entry order. Map length counts entries, including those with null values. A null map gives null for length, keys and values. An empty map has length zero and yields two empty lists. Map lookup returns null for a missing key, a null key or a null map. Arrow maps can contain duplicate keys. Quixote returns the first matching entry. DuckDB 2.0.1 rejects duplicate keys and null keys when constructing a map. Nested types support up to 32 levels, including the entries struct in a map. Sort, join and group by a scalar key to carry nested data through a query. LargeUtf8 and LargeBinary use signed 64-bit byte offsets. Cast between offset widths within either type. A cast to Utf8 or Binary fails if the output array would exceed 2,147,483,647 bytes. Integer arithmetic uses the wider operand type when signedness matches. For mixed signedness it uses the smallest signed type that can hold both ranges. Combining UInt64 with a signed integer requires an explicit cast for arithmetic, conditional branches and coalesce. Integer comparisons are exact across all widths. Integer division returns Float64. Integer window sums return Decimal128(38, 0). Integer remainder (`%` or `modulo`) truncates the quotient toward zero. A zero integer divisor raises an error. A zero floating-point divisor gives NaN. Integer casts check the destination range. Cast to Utf8 for base-ten text. Two Float32 operands produce Float32 for addition, subtraction, multiplication and division. Combining Float32 with another numeric type uses Float64. All other divisions, floating-point sums and averages return Float64. Decimal sum uses precision 38 and keeps the input scale. Decimal arithmetic raises an error if the exact result of an addition, subtraction or multiplication overflows. Use `cast(type)` to convert between numeric types. Reducing a decimal's scale truncates toward zero. Arithmetic and comparisons with a null return null. Filters keep only true, non-null values. `false & null` is false and `true | null` is true. Other combinations with null return null. Boolean operations evaluate both arguments, so an error in either argument can fail the query. `if_else(condition, yes, no)` selects `yes` for true and `no` for false or null. Decimal branches use a common scale and can include integer literals. A selected value that needs more than 38 digits at that scale raises an overflow error. `null_if(a, b)` returns null when the operands compare equal, including two NaNs. Otherwise it returns `a`, including when `b` is null. Its operands follow the type rules for conditional branches. `coalesce(a, b, ...)` returns the first non-null value per row. Supply at least two arguments. Mixing Float32 with another numeric type promotes both to Float64. Integer arguments follow arithmetic promotion, and integers mixed with floating-point arguments use Float64. Other types must match, including decimal precision and scale or timestamp timezone. The result is nullable only when every argument is nullable. `abs()` accepts integers, floating-point values and Decimal128. The minimum signed integer raises an overflow error. `floor()` and `ceil()` accept the same types and leave integers unchanged. `round(digits=0)` accepts floating-point values and Decimal128 and rounds ties away from zero. Negative digits round to the left of the decimal point. Both floating-point types round the stored binary value. For example, the Float64 value written as `2.675` is just below the halfway point and rounds to `2.67` at two places. Decimal results retain their precision. Floor and ceil use scale zero. Round clamps the output scale to the range between zero and the input scale. A result outside the decimal precision raises an overflow error. These operations preserve nulls. Casting a timestamp to Int64 gives its signed microsecond count. Casting that count to a naive or UTC timestamp preserves the value. Casting Date64 to Date32 floors to the start of the day. For example, `-1` millisecond becomes 1969-12-31. Casting to Timestamp preserves the milliseconds as microseconds. Casting back floors to the preceding millisecond. Both casts check the destination range. For a Date32, Date64 or Timestamp column `d`, `d.year()` returns the Gregorian year as Int64. `d.month()` (1–12) and `d.day()` (1–31) return Int32. Timestamp columns also support `hour()`, `minute()` and `second()`, all returning Int32. Use `date_trunc("year")`, `"month"` or `"day"` on either type. Timestamps also accept `"hour"`, `"minute"` and `"second"`. Truncation returns the start of that period in the input type and timezone. An unrepresentable start raises an overflow error. For date columns, `d.date_add_days(n)` accepts signed Int32 or Int64 days and preserves the input type and any time within the day. A result outside the signed 32-bit day range raises an overflow error. `end.date_diff_days(start)` returns the signed number of days from start to end as Int64. These date operations propagate nulls. For integer, string, binary, date and timestamp columns, `is_in(values)` returns null for null inputs. A missing value returns null if the list contains null, and false otherwise. String expressions support `starts_with`, `ends_with`, and `contains`. `like(pattern)` matches the whole string. Use `%` for any sequence and `_` for one Unicode code point. `substr(start_1based, length)` counts code points starting at one. These operations preserve nulls and match case exactly. `replace(old, new)` replaces non-overlapping matches from left to right. An empty search string leaves the input unchanged. `split_part(delimiter, part)` counts fields from one, or from the end for negative positions. Zero and out-of-range positions return an empty string. An empty delimiter splits on Unicode code points. Both functions preserve nulls. `regexp_like(pattern)` searches anywhere in a string. `regexp_extract(pattern, group=0)` returns the first match. Group 0 selects the whole match and groups 1 through 9 select captures. A missing match or capture returns `""`. Indices outside 0 through 9 raise an error. Both methods propagate nulls. `regexp_replace(pattern, replacement)` changes the first match. Pass `replace_all=True` to change every non-overlapping match. In a Python raw replacement string, `\0` inserts the whole match, `\1` through `\9` insert captures, and `\\` inserts a backslash. A reference must name a group in the pattern. `$1` is literal text. An empty pattern inserts at character boundaries. Global replacement skips an empty match at the end of the previous match. Extraction and replacement preserve Utf8 or LargeUtf8. Patterns support `.`, `^`, `$`, bracket classes, ASCII `\d`, `\w`, `\s` and their uppercase complements, groups, alternation and greedy or lazy repetition. `.` matches one Unicode code point except newline. Use `(?s)` to include newlines, `(?m)` for line anchors, and `(?i)` for Unicode simple case folding. Scope flags with `(?i:...)`. The binder rejects lookarounds, pattern backreferences, repeat counts above 1,000 and patterns exceeding its size or nesting limits. `s.length()` counts Unicode code points, including combining marks. `s.byte_length()` counts UTF-8 bytes. Both return Int64. `lower()` and `upper()` change ASCII letters only. For example, uppercasing `"café"` gives `"CAFé"`. `trim()`, `ltrim()` and `rtrim()` remove Unicode space separators (category Zs) from both ends, the start or the end, respectively. Tabs and line breaks are preserved. `s.concat(t)` joins two strings and returns null if either input is null. All unary string operations return null for a null input. Group keys may be integers, floating-point numbers, strings, bytes, Boolean, Timestamp or dates. Null keys form their own groups. Use `group_by(*keys).agg()` or C++ `GroupBy(keys, {})` for one row per distinct tuple. Use `distinct()` or C++ `Distinct()` to compare all columns, including decimals. Rows with nulls in the same positions compare equal when their other values match. In a group, `count_distinct()` (C++ `CountDistinct()`) ignores nulls and returns a non-nullable Int64. A group with only nulls returns zero. Group order is unspecified. Filter/project/limit preserve source order, subject to any earlier unordered grouping. Direct column aliases retain field metadata; computed expressions clear it. Schema metadata survives. Duplicate output names and mixed scalar/reduction projections are errors. `sort("key", "other", descending=[False, True])` orders rows by named columns. Equal keys keep incoming order. Nulls come last by default in either direction; use `nulls_first=True` to put them first. With a positive limit immediately after the sort, Quixote scans all rows but keeps only the best candidates and the batches they reference. With an offset, Quixote uses this bounded sort when the offset plus the requested rows is at most 2048. Larger offset pages use the full sort. Set a spill directory to sort inputs larger than the working budget. ## Window functions A window appends a value to each input row. All supported types can partition and order rows. Null partition keys group together. Equal order keys form a peer group, including equal nulls and NaNs. Within a tie, navigation and row numbering follow input order. Add a unique order key when that order matters. Use a final sort to choose the order of the result. `row_number()`, `rank()` and `dense_rank()` start at one in each partition. Peers share a rank. After a tie, rank skips the occupied positions and dense rank advances by one. With no order keys, all rows in a partition are peers. `lag()` and `lead()` look back or ahead by a nonnegative row count. Zero selects the current row. The default applies only outside the partition. An in-range null stays null. With order keys, sum, count, average and extrema include every row through the last peer of the current row. Without order keys they cover the entire partition. Integer window sums use Decimal128(38, 0). Windows consume their input before emitting batches of up to 4,096 rows. The sort, retained input and window state must fit the query budget. ## Appending queries Use `left.union_all(right)`, C++ `left.UnionAll(right)`, or `qe.union_all(queries)` for a nonempty iterable. Rows arrive in input order, including duplicates. All inputs must belong to the same session. Fields match by position and must have identical types, including decimal precision, scale, and timestamp timezone. The first input supplies field names and metadata. A field is nullable if any input allows nulls there. Independent inputs stream in sequence. When branches read the same one-shot source, they share one cursor on the source. The query budget must cover the batches that later branches still need to read. ## Intersecting and subtracting queries `left.intersect(right)` returns each row that occurs in both inputs once. `left.except_(right)` returns each row that occurs only in the left input once. Pass `all=True` to count copies. For a row that appears five times on the left and twice on the right, intersection returns two copies and subtraction returns three. Both operations use the same session and positional schema rules as `union_all`. They keep the left field names, field metadata and schema metadata. A field is nullable if either input allows nulls. Equality compares every column. Nulls match nulls, NaNs match NaNs, and signed zeros match. Text and binary values compare byte for byte. With zero columns, all rows compare equal. Quixote counts both inputs before emitting results. Set a spill directory for counts larger than the working memory limit. Stream large results and use `sort()` when row order matters. ## Joining queries Both inputs must come from the same session. Use `left.join(right, on="id")` for shared key names, or pass `left_on` and `right_on` for different names. For composite keys, list the columns in matching order. All supported query types can serve as join keys. Corresponding types must agree. A null in any key prevents a match. For Float32 and Float64 keys, positive and negative zero match, and NaNs match each other. The default inner join returns every matching pair. A left join also returns each unmatched left row. Use `how="right"` for matching pairs and each unmatched right row, or `how="full"` to keep unmatched rows from both inputs. All four joins retain both sets of columns. On an unmatched row, every column from the missing side is null, including its join keys. Right fields that share a left name get `suffix` (default `"_right"`). The resulting names must be unique. A cross join takes no keys and considers every pair. The join build state must fit in the query budget. Use `how="semi"` to keep left rows with a match or `how="anti"` to keep those without one. The optional `filter` expression sees fields from both inputs, including suffixed names. Only pairs where it evaluates to true count as matches. Semi and anti joins return the original left columns. ## Execution and lifetimes Queries are immutable. In-memory array inputs and unchanged local Parquet scans are repeatable; an imported Arrow stream has one admitted execution. Failed admission does not consume that stream. After execution starts, failure or cancellation does not make it reusable. `limit(rows, offset=0)` skips the first `offset` rows and returns up to `rows` in input order. An offset at or beyond the end returns an empty result. `limit(0)` validates the plan/schema without pulling input. Other limits stop upstream work after the required rows, then drain already accepted work. Errors from accepted work still propagate. Foreign stream callbacks and blocking file I/O cannot be forcibly interrupted and can delay cancellation/close. Results, exported Arrow objects and delivered batches remain valid after closing their stream, session or runtime. Keep borrowed input storage immutable until released. A `Result` has repeatable batch cursors/exports; a `Stream` is one single-consumer cursor, so choose iteration or an Arrow consumer for that cursor. The first execution failure is preserved; unpublished output is discarded and accepted work drains. Already delivered batches remain valid. `Session.cancel()` affects active queries in that session; closing the session rejects new work. Closing a runtime drains its sessions and executors. Close is idempotent. ## Memory budgets Each query has a working memory budget. It covers execution state, temporary buffers and results that have not been handed to the caller. - `collect()` keeps the whole result inside this budget until completion. - `stream()` hands over one batch at a time. Once delivered, a batch belongs to the caller. Keeping earlier batches does not block the next pull. - A slice keeps its entire backing allocation alive; two views of the same allocation count it once. The runtime's `memory_limit` controls which queries can start. Most queries reserve their full working budget. A scalar aggregate over a Parquet scan can reserve less. A request fails immediately if its budget exceeds the runtime limit, or if results you still hold leave too little space. Release those results and retry. If active queries are the blocker, it may wait. Smaller fitting queries can pass a larger waiting query. An admitted stream keeps progressing even if the results you hold grow beyond the runtime limit. Process memory can exceed the runtime limit. Imported Arrow data, some metadata, adapter/codec allocations and allocator overhead are outside the working budget. A large page, dictionary or group table can exhaust the budget even when streaming. `runtime.stats()` / C++ `MemoryStats` expose `active_reserved_bytes`, `working_live_bytes`, `held_bytes`, `imported_logical_bytes` and `metadata_logical_bytes`. Logical imported/metadata totals are not RSS or unique physical bytes. The lifetime peaks for working, reserved and held memory are `peak_working_bytes`, `peak_reserved_bytes` and `peak_held_bytes`. These maxima can occur at different times. ## Errors Python budget errors use `ResourceLimitError(MemoryError)`; actual allocation failure can also raise `MemoryError`. Cancellation uses `CancelledError` and Ctrl-C uses `KeyboardInterrupt`. Other binding/type/I/O/unsupported failures map to ordinary Python exceptions. C++ uses exported `EngineError` with an `ErrorCode`. Arrow C callbacks never propagate C++ exceptions: check status/error text and release all exported objects. ## Common problems | Problem | Next step | | --- | --- | | Import has no `Runtime` or `Session` | Check `quixote.__file__` in the interpreter you run. Use an isolated environment with `quixote-engine`; the unrelated `quixote` distribution shares the import name. | | A query exceeds its budget | Use streaming for a large output, or increase the query budget and runtime limit together. Streaming still needs enough working memory for pages and group tables. | | A second query cannot start while you hold results | Release unneeded results and retry. Raising the runtime limit allows more admission space. | | An imported stream cannot run a second time | Import the producer again. A PyArrow RecordBatch input is repeatable; an imported Table uses its one-shot stream interface. | | A Parquet field is unsupported | Pass `columns=[...]` with the top-level fields you need. Every leaf in a selected field must have a supported type. | | Output already exists | Choose another path or explicitly pass `overwrite=True`. Failed writes preserve the existing destination. | ## Disk spilling Sorts, grouped aggregates, intersections and differences can use temporary files when the runtime has a spill directory. An empty directory setting disables spilling. A zero spill byte limit allows unlimited disk use. The working memory limit still applies to input, each merge, and collected output. Stream results to consume an output larger than the query budget. Runtime statistics report live disk use (`spilled_bytes`), its lifetime peak (`peak_spilled_bytes`), and all bytes written including intermediate merges (`total_spilled_bytes`). Closing or cancelling the query releases its files.