diff --git a/CHANGELOG.md b/CHANGELOG.md index ae624d6..4c7e845 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -615,6 +615,40 @@ versions (0.x) may contain breaking changes; they are always listed under a deferred and do not exist. An io_uring comment named a test file that does not exist; it names the test that does. +- **NULL elements inside a vector column survive a GPU filter or join** + (#105). The device transfer format carries one validity bit per row, so a + NULL element inside a valid `FixedSizeList` row came back from a + CUDA or Metal filter, or a CUDA join, as a valid `0.0`, where the CPU path + kept it NULL. Such a column now stays on the host, as a `Utf8` column + does, and is gathered at the rows the device selected; the rest of the + batch still runs on the device. `columns::extract` refuses one as + `Unsupported`, so a vector distance over it, whose kernel has to read the + column, runs on the CPU reference, counted in `fallback_batches`, with the + same distances. NULL elements under a NULL row, which a builder's + `append_null` leaves, do not count. New: + `columns::row_with_null_element`. + +- **A `Float64` filter planned for a GPU returns the rows `--target cpu` + returns, over NaN and `-0.0` too** (#28). A `--target cuda` or + `--target metal` filter, or a cluster's GPU placement, could select other + rows than `--target cpu` for two kinds of value. A NaN: the CUDA kernel + compared with plain IEEE `>` and `=`, where a NaN matches nothing, but + DataFusion orders floats by IEEE totalOrder, so `v > 4.0` selects a NaN + (a NaN sorts above `+inf`; one with its sign bit set, x86's default NaN, + below `-inf`). And `-0.0`: DataFusion 55 reads it as `+0.0` in a + comparison (`-0.0 = 0.0` is true; under 0.2.0's DataFusion 54 it was + false on every target), but the CPU reference did not — and the + reference is what runs every `Float64` predicate on Metal, any + GPU-planned query on a machine without that GPU, and every per-batch + fallback — so there `v = 0.0` skipped the `-0.0` rows and `v < 0.0` + returned them. Both now compare as DataFusion 55 does; only rows holding + a NaN or a `-0.0` come back differently. New: `oxide gen-data + --special-floats`, which puts NaN, ±0.0 and ±inf into `v` on every 16th + row to compare targets on (the default table is unchanged), and behind it + `DemoOptions`, `write_demo_table_with`, `demo_batches_with`, + `demo_chunks_with`, `SPECIAL_FLOATS` and `SPECIAL_FLOAT_EVERY` in + `oxidelake-storage`. + ### Security - **thrift is out of the dependency graph** (#4, #54). parquet 59 decodes diff --git a/README.md b/README.md index d68755f..7ee445f 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,7 @@ error, never a silent fallback. | `--seed` | `gen-data` | `42` | PRNG seed. The same seed always writes the same bytes. | | `--row-group-rows` | `gen-data` | `65536` | Rows per Parquet row group. | | `--compression` | `gen-data` | `zstd` | `none`, `lz4` or `zstd`. | +| `--special-floats` | `gen-data` | off | Puts IEEE special values into `v` on every 16th row — NaN, -0.0, +0.0, +inf, -inf and a negative NaN, in turn — to compare backends where float comparison is subtle. Every other value, and the default table, stay the same. | ### `oxide-scheduler` diff --git a/STATUS.md b/STATUS.md index 3ae972f..08be698 100644 --- a/STATUS.md +++ b/STATUS.md @@ -30,11 +30,11 @@ Filled in as phases complete. Every component goes under exactly one column — | `CudaBackend` (dynamic loading, NVRTC pipeline, transfers, upload/download) | driver probe + typed error on GPU-less box; **(T4)** `cargo test -p oxidelake-device --features cuda -- --include-ignored` — transfers, pinned memory round trip, NVRTC compile + launch all executed | | | | `CudaPinnedProvider` / `PinnedBuf` | **(T4)** pinned allocation and H2D/D2H through it (`transfers_and_pinned_memory_round_trip_on_device`) | | | | `MetalBackend`, `MetalSharedBuffer`, Metal kernel dispatch (filter+project, vector distance) | **(macOS)** conformance suite on the real device: `cargo test -p oxidelake-compute --features metal -- --ignored` — `HardwareDetector` selects Metal, MSL compiles via `newLibraryWithSource`, Int64 filter + vector distance dispatch on the GPU and equal stock DataFusion, **and the test asserts device execution through the operator's transfer counters (`bytes_h2d`/`bytes_d2h` > 0), so equal results cannot be mistaken for a silent CPU fallback**; join/aggregate are declared unsupported up front and take the CPU path without uploading; `oxidelake-device`/`oxidelake-memory`/`oxidelake-runtime` metal suites green. Correction (2026-09-02): until the operator layer learned to keep `Utf8` columns on the host, the suite's fixtures (which all carry a `Utf8` column) made every operator fall back to the CPU on Metal, so the earlier version of this row over-claimed — real Metal dispatch had only been exercised by the Int64-only queries in `oxidelake-runtime/tests/embedded.rs` | | | -| CUDA kernel sources (`crates/oxidelake-device/kernels/cuda/*.cu`) + launch orchestration (`cuda/ops.rs`) | embedded-source and scan-helper unit tests; **(T4)** every kernel NVRTC-compiled and launched (the hash join and `aggregation.cu` as they were in 0.2.0: see the next two rows): conformance suite `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored` equal to stock DataFusion (3 seeds × 5 sizes × filter/join/aggregate/vector L2+cosine) **with the transfer-counter witness (`bytes_h2d`/`bytes_d2h` > 0)**; the aggregation kernel's group-table publication bug (below) fixed and re-verified | | | +| CUDA kernel sources (`crates/oxidelake-device/kernels/cuda/*.cu`) + launch orchestration (`cuda/ops.rs`) | embedded-source and scan-helper unit tests; **(T4)** every kernel NVRTC-compiled and launched (the hash join and `aggregation.cu` as they were in 0.2.0: see the next two rows): conformance suite `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored` equal to stock DataFusion (3 seeds × 5 sizes × filter/join/aggregate/vector L2+cosine) **with the transfer-counter witness (`bytes_h2d`/`bytes_d2h` > 0)**; the aggregation kernel's group-table publication bug (below) fixed and re-verified | | `filter_project.cu`'s `Float64` comparison as changed for #28 (DataFusion's order: NaN above `+inf`, `-0.0` = `+0.0`): not NVRTC-compiled or run anywhere yet — `gpu_backend_filters_special_floats_like_datafusion_when_available` (`--ignored`) is for the next T4 run | | `hash_join.cu` as rewritten for 0.3.0 (`oxide_hj_count`, `oxide_hj_expand` over a distinct-key index the host builds) and its launch orchestration (#45, #95, #108) | the host index (`join_slots`: placement, a replica of the device probe loop, the slot reads per probe row for #108's four build shapes) unit-tested in `oxidelake-device`; the operator's device path (prepare once, probe, gather in pieces, finish on the CPU from the same match) through a fake backend in `oxidelake-compute`. The kernel source itself only under **g++ with a shim of the CUDA builtins, thread by thread, against a nested-loop join** (2026-11-17, ASan + UBSan, a harness outside the repository; both kernels only read shared state, so a sequential run computes what the device does) — **not NVRTC, not a GPU** | `cuda/ops.rs` join section: `make check-cuda lint-cuda` | NVRTC compile + launch on the T4: `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored` (conformance join, including the chunked one) and `--test join_timing -- --ignored --nocapture` (timings; the file also runs unchanged on 08a9147 for the before) | | `aggregation.cu` as changed for 0.3.0 (`oxide_agg_number_groups`, accumulators and read-back of one entry per group) and its launch orchestration (#45, the aggregate half) | the host half (`finish_groups`: groups numbered in any order come back sorted by key, `NULL` group last) unit-tested under `--features cuda`; a device result merged per batch through a fake backend in `oxidelake-compute` (#29). The kernel source itself only under **g++ with a shim of the CUDA builtins, thread by thread, against a host reference** (2026-11-18, ASan + UBSan, a harness outside the repository: no rows, only `NULL` keys, one key, a group per row, extreme keys, 100 keys in 65 536 rows; a sequential run cannot exercise the slot-claim race, whose protocol did not change), and compiled to PTX for sm_75 by clang 21 against stubbed SDK atomics — **not NVRTC, not a GPU** | `cuda/ops.rs` aggregate section: `make check-cuda lint-cuda`, `cargo clippy -p oxidelake-device --features cuda --all-targets` | NVRTC compile + launch on the T4: `cargo test -p oxidelake-device --features cuda -- --ignored` (`aggregate_numbers_groups_like_the_reference` and the three older aggregate tests), `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda --test conformance -- --ignored` (the aggregate checks, now also in 7-row batches) and `--test aggregate_timing -- --ignored --nocapture` (timings of a 10M-row `GROUP BY` with 100 keys; the file also runs unchanged on 08a9147 for the before) | | Metal kernel sources (`crates/oxidelake-device/kernels/metal/*.metal`) | **(macOS)** MSL runtime compile + dispatch, exercised by the conformance suite above | | | -| `Gpu*Exec` operators (filter+project, hash join, aggregate, vector distance) on `CpuBackend` | conformance suite vs stock DataFusion; EXPLAIN tags; per-batch CPU fallback path; **(macOS)** same suite executed on `MetalBackend`; **(T4)** same suite executed on `CudaBackend` | | | +| `Gpu*Exec` operators (filter+project, hash join, aggregate, vector distance) on `CpuBackend` | conformance suite vs stock DataFusion; EXPLAIN tags; per-batch CPU fallback path; the device transfer format without a device (`TransferSim`, a CUDA-claiming backend whose uploads and downloads go through `columns`): vector columns with NULL elements through filter, join and vector distance, with the transfer counters as witness of which path ran (#105); `Float64` filters over NaN (both signs), ±0.0, ±inf and subnormals, against stock DataFusion and against its order written out by hand (#28); **(macOS)** same suite executed on `MetalBackend`; **(T4)** same suite executed on `CudaBackend` | | the same #105 checks on a device (`gpu_backend_keeps_null_vector_elements_when_available`, `--ignored`): not run on Metal or the T4 yet; nor the #28 special-float filters (`gpu_backend_filters_special_floats_like_datafusion_when_available`, `--ignored`) | | `GpuOperator` fallback + telemetry, `local_backend()` selection | unit + conformance tests (CPU); **(T4)** CUDA streams and transfer accounting through the conformance witness; a 1M-row `oxide sql … --target cuda` with `RUST_LOG=oxidelake_compute=debug` logged **no** per-batch CPU fallback (since 0.2.0 the same claim is a counter, `fallback_batches`, in the Inspector panel and in every `OperatorSnapshot`, rather than something only a raised log level can see — #32) | | | | Parquet writer options + `write_parquet` (row groups, dictionaries, Bloom filters on keys, page statistics) | unit test inspects row-group/Bloom metadata; a refused, failed or abandoned write leaves the file it would replace untouched (`parquet_io`/`datagen` unit tests, `oxide gen-data --row-group-rows 0` in `tests/cli.rs`, #119) | | | | DataFusion pruning settings + `scan_pruning_metrics` proof (statistics, Bloom filter, page index) | `tests/pruning.rs` on a 200k-row / 100-row-group dataset | | | @@ -78,6 +78,7 @@ Resolved 2026-11-11 for the Ballista 55 bump (`cargo tree`, 593 crates in `Cargo - **Third correctness bug, found on the first CUDA machine (2026-09-06, Tesla T4):** `oxide_ag_slot` in `aggregation.cu` let a thread that lost the CAS for a group-table slot compare the slot's key through a plain load after spinning on the state word. That load could observe the pre-publication key, so the loser probed on and inserted the same key in a second slot; every pass-2 lookup resolved to the first slot, and the host emitted the phantom as a duplicate group with `COUNT` 0 and `NULL` aggregates (`3|NULL|0|NULL|NULL` next to the real `3|489.0|40|…`). Deterministic on the T4 for the demo table (100 keys, 4000 rows) — the compute conformance suite's 10-key fixtures never hit it. Fix: the state and key are read through `volatile` loads with a fence between them that pairs with the publisher's fence; lookups in later launches need neither. Regression test at the device layer: `aggregate_matches_host_on_the_demo_distribution` (`#[ignore]`, needs a GPU), red on the old kernel and green on the fix on the same machine. Lesson, same as the Metal one: "compiles with `--features cuda`" is not a verification status; the row above says what ran. - **Second correctness bug, found running the README's 1M-row quickstart against a real cluster (2026-09-01):** the aggregate lowering replaced the Final/Partial pair *and the exchange between them*, leaving `GpuAggregateExec` directly over a multi-partition scan. Embedded mode is fine (the exec collects every input partition itself), but Ballista cuts shuffle stages exactly at exchange nodes (`CoalescePartitionsExec` / `RepartitionExec` / `SortPreservingMergeExec`), so the distributed plan lost every scan partition but one — `SUM(v)` came back ~16× too small. Every earlier cluster test used files under DataFusion's 10 MiB `repartition_file_min_size`, so scans were never byte-range-split and the shape never existed. Fix: the rule now keeps one `CoalescePartitionsExec` under `GpuAggregateExec` whenever the source is multi-partition; `cluster_sql_matches_embedded_sql` now generates an 11 MiB file so the multi-partition shape is pinned in CI; verified by hand that the 1M-row cluster output is byte-identical to embedded. Since 0.3.0 the rule no longer replaces the exchange at all: it lowers the two halves separately and keeps DataFusion's own exchange between them (#90), so the stage cut falls where DataFusion put it. - Metal v1 compares `Int64` only (no `double` on most Apple GPUs); `Float64` predicates return `Unsupported` and take the CPU path. +- `Float64` filters compare in DataFusion's order, which is not Arrow's (#28): DataFusion 55 reads `-0.0` as `+0.0` on both sides before Arrow's totalOrder kernels compare them, so the CPU reference does the same, and the CUDA kernel compares sign-adjusted bit patterns with `-0.0` given `+0.0`'s. A NaN sorts above `+inf`, and one with its sign bit set (x86's default NaN) below `-inf`; NaNs are equal only bit for bit. The 55 bump moved this order without a failing test, since no fixture held a `-0.0`, so the conformance suite also writes the order out by hand and fails naming DataFusion if it moves again. - Storage keeps no private format: `oxidelake-storage` owns Parquet writer properties, session pruning settings, Arrow IPC cache files and the object-store layer; pruning is *proven* by reading `row_groups_pruned_statistics` / `row_groups_pruned_bloom_filter` back from the executed plan rather than assumed. - The io_uring store implements only the data path (`get_opts` ranged reads, `put_opts` overwrite writes) on its ring thread and delegates metadata operations to the wrapped `LocalFileSystem`, which is what makes the two stores behaviourally identical. An overwrite is written to a staged `#` file and renamed into place, as `LocalFileSystem` does, and returns the e_tag `LocalFileSystem` computes for the result (inode, mtime in microseconds, size): `head` answers through `LocalFileSystem`, so the two must agree (#111). A get is opened, and its preconditions and range checked, by `LocalFileSystem::get_opts`; the ring reads from the descriptor that check was made on (#113), at most 8 MiB per job, as the consumer pulls the stream (#112). @@ -99,6 +100,7 @@ Resolved 2026-11-11 for the Ballista 55 bump (`cargo tree`, 593 crates in `Cargo - Embedded sessions wire their `TelemetryHub` into the placement rule (`HardwarePlacementRule::with_telemetry`), so every `Gpu*Exec` a session plans reports per-batch counters; `oxide tui --query` renders the executed plan, each operator's own counters (read from the exec instance through `operator_stats()`: one hub entry per instance, shared by its partitions — merging them by operator name, as this did until 0.3.0, showed same-named operators each other's sums, #123) and per-column profiles (min/max/nulls/quantiles via one aggregation query per table). - Security + performance audit (2026-09-02, see [docs/audit-2026-09-02.md](docs/audit-2026-09-02.md)) — decisions taken: - The operator layer, not the backends, owns column plumbing: only the columns a kernel reads are uploaded; projected columns of device-ineligible types (`Utf8`, …) stay on the host and are gathered with Arrow `take` at the row ids the device compacted (a synthetic `__oxide_row` column travels with the sub-batch). A string column in the projection no longer sends the whole batch to the CPU path. + - The transfer format carries one validity bit per row, so a `FixedSizeList` with a NULL element inside a valid row cannot travel (#105) — the element used to come back from a CUDA or Metal filter, or a CUDA join, as a valid `0.0`. `columns::extract` refuses such a column (`Unsupported`), and the operator layer keeps it on the host and gathers it at the device's row ids, as it does a `Utf8` column, so the filter or join still runs on the device. Vector distance, whose kernel has to read the column, runs such a batch on the CPU reference. NULL elements under a NULL row do not count (`append_null` leaves them), and are counted with a popcount per NULL row rather than by visiting every element, since every upload of a nullable vector column asks. A join's build side is checked once, when its `JoinBuild` is made, since its device copy serves every probe batch (#45); each probe batch is checked as it comes. Not done: carrying element validity through the device gathers, which would keep such a column on the device too, at the price of changing the CUDA gathers and the Metal kernels. - Backends declare what they support before anything is uploaded (`GpuBackend::supports_predicate` / `supports_hash_join` / `supports_aggregate`, default `true`; Metal says `false` for joins, aggregates and non-`Int64` predicates). - A hash join's build side is hashed once (`JoinBuild` → `kernels::JoinTable`, a flat row array grouped by key) and uploaded once per operator; probes gather only projected columns. Previously the table was rebuilt on the CPU and the build side re-uploaded for every probe batch. - Column transfers are zero-copy where the transport allows: `ColumnBytes` holds Arrow `Buffer` slices, rebuilding moves the downloaded buffers, and Metal downloads alias the shared `MTLBuffer` through `Buffer::from_custom_allocation` (the `Arc` keeps it alive). One memcpy into shared memory per upload remains (Arrow allocations are not page-aligned). diff --git a/crates/oxidelake-compute/src/operator.rs b/crates/oxidelake-compute/src/operator.rs index 0d5b25d..2a81baa 100644 --- a/crates/oxidelake-compute/src/operator.rs +++ b/crates/oxidelake-compute/src/operator.rs @@ -11,7 +11,8 @@ //! leave the host: the device also compacts a synthetic row-id column and //! the operator gathers those columns with Arrow `take` afterwards, so a //! string column in the projection no longer forces a whole batch onto the -//! CPU path; +//! CPU path. A vector column with a NULL element inside a valid row stays +//! there too, since the transfer format cannot carry that NULL (#105); //! * a backend is asked whether it supports an operation *before* anything is //! uploaded ([`GpuBackend::supports_predicate`] and friends); //! * a hash join's build side is hashed once ([`JoinBuild`]), then uploaded @@ -49,6 +50,25 @@ fn device_eligible(dt: &DataType) -> bool { || vector_dimension(dt).is_some() } +/// Whether a projected `column` is uploaded, rather than kept on the host and +/// gathered at the row ids the device selected. +/// +/// The type decides first. A vector column of a device type stays on the host +/// as well when a valid row holds a NULL element: the transfer format has one +/// validity bit per row, so a device filter or join would hand the element +/// back as a valid number (#105). Gathered on the host it keeps its NULL, and +/// the batch still runs on the device instead of falling back whole. +fn travels(column: &ArrayRef) -> Result { + Ok(device_eligible(column.data_type()) + && oxidelake_device::columns::row_with_null_element(column.as_ref())?.is_none()) +} + +/// [`travels`] for column `index` of `batch`, which must exist. +fn column_travels(batch: &RecordBatch, index: usize) -> Result { + field(&batch.schema(), index)?; + travels(batch.column(index)) +} + fn push_unique(cols: &mut Vec, index: usize) { if !cols.contains(&index) { cols.push(index); @@ -158,17 +178,38 @@ pub struct JoinBuild { /// partition produces it — carries them. A join whose probe side yields /// no batch at all records none, and so reports no build rows either. rows_counted: AtomicBool, + /// Per column, whether it [`travels`] to the device. Every probe batch's + /// [`JoinPlan`] asks; the build side never changes and is uploaded once + /// per operator (#45), so it is checked once here rather than once per + /// probe batch — for a nullable vector column, a pass over its rows. + uploadable: Vec, } impl JoinBuild { /// Hashes `batch` on its `Int64` column `key`. pub fn new(batch: RecordBatch, key: usize) -> Result { let table = JoinTable::build(&batch, key)?; + let uploadable = batch + .columns() + .iter() + .map(travels) + .collect::>()?; Ok(Self { batch, key, table, rows_counted: AtomicBool::new(false), + uploadable, + }) + } + + /// Whether build column `index` [`travels`] to the device. + fn uploadable(&self, index: usize) -> Result { + self.uploadable.get(index).copied().ok_or_else(|| { + EngineError::plan(format!( + "column index {index} out of range for a build side with {} columns", + self.uploadable.len() + )) }) } @@ -230,15 +271,18 @@ struct JoinPlan { } impl JoinPlan { + /// The plan for one probe batch `left` against `build`. Which columns + /// travel depends on what they hold, not only their type (#105): the + /// probe batch is checked here, each time; the build side was checked + /// once, when its [`JoinBuild`] was made. fn new( - left: &Schema, - right: &Schema, + left: &RecordBatch, + build: &JoinBuild, left_key: usize, - right_key: usize, projection: Option<&[usize]>, ) -> Result { - let width = left.fields().len(); - let all = width + right.fields().len(); + let width = left.num_columns(); + let all = width + build.batch().num_columns(); let selected: Vec = match projection { Some(p) => p.to_vec(), None => (0..all).collect(), @@ -249,18 +293,18 @@ impl JoinPlan { ))); } let left_plan = GpuOperator::side_plan( - left, left_key, selected.iter().copied().filter(|&i| i < width), + |index| column_travels(left, index), )?; let right_plan = GpuOperator::side_plan( - right, - right_key, + build.key(), selected .iter() .copied() .filter(|&i| i >= width) .map(|i| i - width), + |index| build.uploadable(index), )?; Ok(Self { selected, @@ -589,7 +633,7 @@ impl GpuOperator { let schema = batch.schema(); let eligible: Vec = projection .iter() - .map(|&i| field(&schema, i).map(|f| device_eligible(f.data_type()))) + .map(|&i| column_travels(batch, i)) .collect::>()?; let mut device_cols = predicate.columns(); device_cols.dedup(); @@ -769,15 +813,18 @@ impl GpuOperator { Ok(Some(out)) } + /// One join side's plan: its key, then each `selected` column that + /// `travels`; any other selected column is gathered on the host at row + /// ids. fn side_plan( - schema: &Schema, key: usize, selected: impl Iterator, + travels: impl Fn(usize) -> Result, ) -> Result { let mut device_cols = vec![key]; let mut row_ids = false; for index in selected { - if device_eligible(field(schema, index)?.data_type()) { + if travels(index)? { push_unique(&mut device_cols, index); } else { row_ids = true; @@ -877,13 +924,7 @@ impl GpuOperator { left_key: usize, projection: Option<&[usize]>, ) -> Result { - let plan = JoinPlan::new( - &left.schema(), - &build.batch().schema(), - left_key, - build.key(), - projection, - )?; + let plan = JoinPlan::new(left, build, left_key, projection)?; let left_sub = plan.left.sub_batch(left)?; let key = plan .left @@ -1370,6 +1411,58 @@ mod tests { assert_eq!(build.batch().num_rows(), 4); } + /// #105: a vector column whose valid rows hold a NULL element is planned + /// like a `Utf8` column — kept off the device and gathered at row ids — + /// on either side of a join, while the same column with NULL elements + /// only under its NULL row is uploaded. + #[test] + fn a_vector_column_with_null_elements_in_valid_rows_stays_on_the_host() { + use arrow::array::{Array, FixedSizeListArray, Float32Array}; + use arrow::buffer::NullBuffer; + + let with = |second: Option| { + let vectors = FixedSizeListArray::try_new( + Arc::new(Field::new("item", DataType::Float32, true)), + 2, + Arc::new(Float32Array::from(vec![ + Some(1.0), + second, + None, + None, + Some(5.0), + Some(6.0), + ])), + Some(NullBuffer::from(vec![true, false, true])), + ) + .unwrap(); + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("k", DataType::Int64, false), + Field::new("vec", vectors.data_type().clone(), true), + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(vectors)], + ) + .unwrap() + }; + let sides = |probe: &RecordBatch, build: &RecordBatch| { + let build = JoinBuild::new(build.clone(), 0).unwrap(); + let plan = JoinPlan::new(probe, &build, 0, None).unwrap(); + (plan.left, plan.right) + }; + let uploaded = SidePlan { + device_cols: vec![0, 1], + row_ids: false, + }; + let gathered = SidePlan { + device_cols: vec![0], + row_ids: true, + }; + let (whole, holed) = (with(Some(2.0)), with(None)); + assert_eq!(sides(&whole, &whole), (uploaded.clone(), uploaded.clone())); + assert_eq!(sides(&holed, &whole), (gathered.clone(), uploaded.clone())); + assert_eq!(sides(&whole, &holed), (uploaded, gathered)); + } + // --- the CPU-fallback counter (#32) ------------------------------------ fn int_predicate() -> Predicate { diff --git a/crates/oxidelake-compute/tests/conformance.rs b/crates/oxidelake-compute/tests/conformance.rs index 96411e1..55df1bc 100644 --- a/crates/oxidelake-compute/tests/conformance.rs +++ b/crates/oxidelake-compute/tests/conformance.rs @@ -980,3 +980,598 @@ async fn join_collects_repartitioned_build_side_once() { .with_backend(cpu()); assert_eq!(exec_rows(&ctx, Arc::new(join)).await, expected); } + +/// NULL elements inside vectors through the device transfer format (#105). +/// +/// The format carries one validity bit per row, so a NULL element inside a +/// valid row used to come back from a CUDA or Metal filter, or a CUDA join, +/// as a valid `0.0`. The CPU backend never moves bytes, which is why the +/// suite above could not see it: `TransferSim` can. +mod vector_null_elements { + use arrow::array::AsArray; + use arrow::datatypes::Float32Type; + use oxidelake_compute::JoinBuild; + use oxidelake_core::{DeviceId, EngineError}; + use oxidelake_device::cpu::kernels; + use oxidelake_device::{ + AggregateArgs, DeviceBatch, DeviceBuffer, DeviceJoinMatches, DeviceJoinTable, DeviceStream, + FilterProjectArgs, HashJoinArgs, HostBuffer, JoinBuildArgs, JoinProbeArgs, MemoryInfo, + VectorDistanceArgs, columns, + }; + + use super::*; + + /// A backend that claims to be CUDA and moves every batch through the + /// device byte format — `columns::extract_batch` on upload, + /// `columns::rebuild_batch` on download, what `CudaBackend` and + /// `MetalBackend` do around their copies — while the kernels run on the + /// CPU reference. On a machine with no GPU it is the closest thing to a + /// device: whatever the format cannot carry comes back as a wrong row. + #[derive(Debug)] + struct TransferSim(CpuBackend); + + impl TransferSim { + fn shared() -> Arc { + Arc::new(Self(CpuBackend::new())) + } + + fn through_the_format(batch: &RecordBatch) -> Result { + columns::rebuild_batch(&batch.schema(), columns::extract_batch(batch)?) + } + } + + impl GpuBackend for TransferSim { + fn kind(&self) -> BackendKind { + BackendKind::Cuda + } + fn device_id(&self) -> DeviceId { + DeviceId::new(BackendKind::Cuda, 0) + } + fn memory_info(&self) -> Result { + self.0.memory_info() + } + fn alloc_device(&self, bytes: usize) -> Result { + self.0.alloc_device(bytes) + } + fn alloc_pinned_host(&self, bytes: usize) -> Result { + self.0.alloc_pinned_host(bytes) + } + fn create_stream(&self) -> Result { + self.0.create_stream() + } + fn copy_h2d( + &self, + stream: &DeviceStream, + src: &HostBuffer, + dst: &mut DeviceBuffer, + ) -> Result<(), EngineError> { + self.0.copy_h2d(stream, src, dst) + } + fn copy_d2h( + &self, + stream: &DeviceStream, + src: &DeviceBuffer, + dst: &mut HostBuffer, + ) -> Result<(), EngineError> { + self.0.copy_d2h(stream, src, dst) + } + fn synchronize(&self, stream: &DeviceStream) -> Result<(), EngineError> { + self.0.synchronize(stream) + } + fn upload( + &self, + stream: &DeviceStream, + batch: &RecordBatch, + ) -> Result { + self.0.upload(stream, &Self::through_the_format(batch)?) + } + fn download( + &self, + stream: &DeviceStream, + batch: &DeviceBatch, + ) -> Result { + Self::through_the_format(&self.0.download(stream, batch)?) + } + fn filter_project( + &self, + stream: &DeviceStream, + args: FilterProjectArgs<'_>, + ) -> Result { + self.0.filter_project(stream, args) + } + fn hash_join( + &self, + stream: &DeviceStream, + args: HashJoinArgs<'_>, + ) -> Result { + self.0.hash_join(stream, args) + } + fn prepare_join_build( + &self, + stream: &DeviceStream, + args: JoinBuildArgs<'_>, + ) -> Result { + self.0.prepare_join_build(stream, args) + } + fn probe_join( + &self, + stream: &DeviceStream, + args: JoinProbeArgs<'_>, + ) -> Result { + self.0.probe_join(stream, args) + } + fn aggregate( + &self, + stream: &DeviceStream, + args: AggregateArgs<'_>, + ) -> Result { + self.0.aggregate(stream, args) + } + fn vector_distance( + &self, + stream: &DeviceStream, + args: VectorDistanceArgs<'_>, + ) -> Result { + self.0.vector_distance(stream, args) + } + } + + /// `id Int64`, `k Int64?`, `vec FixedSizeList?` with a + /// nullable child. Every NULL row holds NULL elements, the way a + /// builder's `append_null` leaves it; with `holes`, about one valid row in + /// five holds a NULL element too — the shape the format cannot carry. + fn gen_null_elements(seed: u64, rows: usize, holes: bool) -> RecordBatch { + let mut rng = StdRng::seed_from_u64(seed ^ 0x0e1e_3e17); + let k: Vec> = (0..rows) + .map(|_| (!rng.random_bool(0.1)).then(|| rng.random_range(0..10i64))) + .collect(); + let valid: Vec = (0..rows).map(|_| !rng.random_bool(0.15)).collect(); + let mut elements: Vec> = Vec::with_capacity(rows * DIM); + for &row_valid in &valid { + let hole = + (holes && row_valid && rng.random_bool(0.2)).then(|| rng.random_range(0..DIM)); + for e in 0..DIM { + elements + .push((row_valid && hole != Some(e)).then(|| rng.random_range(-5.0f32..5.0))); + } + } + let vectors = FixedSizeListArray::try_new( + Arc::new(Field::new("item", DataType::Float32, true)), + DIM as i32, + Arc::new(Float32Array::from(elements)), + Some(NullBuffer::from(valid)), + ) + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("k", DataType::Int64, true), + Field::new("vec", vectors.data_type().clone(), true), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from_iter_values(0..rows as i64)), + Arc::new(Int64Array::from(k)), + Arc::new(vectors), + ], + ) + .unwrap() + } + + async fn check_filter(backend: Arc, seed: u64, rows: usize) { + let ctx = SessionContext::new(); + let batch = gen_null_elements(seed, rows, true); + ctx.register_batch("t", batch.clone()).unwrap(); + let expected = sql_rows(&ctx, "SELECT id, vec FROM t WHERE k >= 3").await; + let exec = GpuFilterExec::try_new( + physical_plan(&ctx, batch).await, + Predicate::compare(1, Comparison::GtEq, Literal::Int64(3)), + vec![0, 2], + backend.kind(), + ) + .unwrap() + .with_backend(backend); + let actual = exec_rows(&ctx, Arc::new(exec)).await; + assert_eq!(actual, expected, "filter seed={seed} rows={rows}"); + } + + /// The vector column on the probe side, then on the build side. + async fn check_join(backend: Arc, seed: u64, rows: usize) { + let ctx = SessionContext::new(); + let vectors = gen_null_elements(seed, rows, true); + let names = gen_right(seed, rows / 2 + 1); + ctx.register_batch("v", vectors.clone()).unwrap(); + ctx.register_batch("r", names.clone()).unwrap(); + let expected = sql_rows( + &ctx, + "SELECT v.id, v.k, v.vec, r.rk, r.name FROM v INNER JOIN r ON v.k = r.rk", + ) + .await; + let exec = GpuHashJoinExec::try_new( + physical_plan(&ctx, vectors.clone()).await, + physical_plan(&ctx, names.clone()).await, + 1, + 0, + backend.kind(), + ) + .unwrap() + .with_backend(Arc::clone(&backend)); + let actual = exec_rows(&ctx, Arc::new(exec)).await; + assert_eq!(actual, expected, "probe-side join seed={seed} rows={rows}"); + + let expected = sql_rows( + &ctx, + "SELECT r.rk, r.name, v.id, v.k, v.vec FROM r INNER JOIN v ON r.rk = v.k", + ) + .await; + let exec = GpuHashJoinExec::try_new( + physical_plan(&ctx, names).await, + physical_plan(&ctx, vectors).await, + 0, + 1, + backend.kind(), + ) + .unwrap() + .with_backend(backend); + let actual = exec_rows(&ctx, Arc::new(exec)).await; + assert_eq!(actual, expected, "build-side join seed={seed} rows={rows}"); + } + + /// Runs `run` on a `GpuOperator` over `backend` and returns what it + /// produced with the operator's `(fallback_batches, bytes_h2d)`: the + /// witness of which path it took. + fn witnessed( + backend: Arc, + run: impl FnOnce(&GpuOperator) -> T, + ) -> (T, u64, u64) { + let hub = TelemetryHub::new(); + let stats = hub.register_operator("GpuOperator", backend.kind()); + let operator = GpuOperator::new(backend, Some(Arc::clone(&stats))).unwrap(); + let out = run(&operator); + let snapshot = stats.snapshot(); + (out, snapshot.fallback_batches, snapshot.bytes_h2d) + } + + /// One filter batch through a `GpuOperator` on `backend`, checked against + /// the CPU reference; returns its `(fallback_batches, bytes_h2d)`. + pub(super) fn filter_once( + backend: Arc, + batch: &RecordBatch, + predicate: &Predicate, + projection: &[usize], + ) -> (u64, u64) { + let (out, fallbacks, h2d) = witnessed(backend, |op| { + op.filter_project(batch, predicate, projection).unwrap() + }); + assert_eq!( + out, + kernels::filter_project(batch, predicate, projection).unwrap(), + "device path and CPU reference disagree" + ); + (fallbacks, h2d) + } + + /// One probe batch joined against `build`, checked against the CPU + /// reference; returns its `(fallback_batches, bytes_h2d)`. The output + /// comes out in pieces of at most `CHUNK` rows (#95), so a column kept on + /// the host is gathered at each piece's row ids, not once. + fn join_once( + backend: Arc, + probe: &RecordBatch, + probe_key: usize, + build: &RecordBatch, + build_key: usize, + ) -> (u64, u64) { + const CHUNK: usize = 61; + let build = JoinBuild::new(build.clone(), build_key).unwrap(); + let (pieces, fallbacks, h2d) = witnessed(backend, |op| { + let mut probed = op.hash_join(probe, &build, probe_key, None, CHUNK).unwrap(); + let mut pieces = Vec::new(); + while let Some(piece) = op.next_join_chunk(&mut probed, &build).unwrap() { + pieces.push(piece); + } + pieces + }); + assert!(pieces.len() > 1, "{} piece(s)", pieces.len()); + let reference = + kernels::hash_join_probe(probe, probe_key, build.batch(), build.table(), None).unwrap(); + assert_eq!( + sorted_rows(&pieces), + sorted_rows(&[reference]), + "device path and CPU reference disagree" + ); + (fallbacks, h2d) + } + + /// Equal rows prove nothing if every batch quietly took the CPU path. A + /// filter or a join runs on the device whether or not a valid row holds a + /// NULL element: such a column is gathered on the host, not uploaded — + /// `extract`, and so `TransferSim`, would refuse it and count a fallback. + /// A vector distance has to read the column on the device, so over such + /// a batch it is the one that runs on the CPU reference, counted. + fn assert_device_path_witnessed(backend: &Arc) { + let predicate = Predicate::compare(1, Comparison::GtEq, Literal::Int64(3)); + let names = gen_right(5, 40); + let query = [0.5f32, -1.0, 2.0, 0.25]; + for holes in [false, true] { + let batch = gen_null_elements(5, 300, holes); + let vectors = batch.column(2); + assert!(vectors.null_count() > 0, "the fixture has NULL rows"); + assert_eq!( + columns::row_with_null_element(vectors.as_ref()) + .unwrap() + .is_some(), + holes, + "the fixture's valid rows hold NULL elements" + ); + let (fallbacks, h2d) = filter_once(Arc::clone(backend), &batch, &predicate, &[0, 2]); + assert_eq!(fallbacks, 0, "filter fell back (holes: {holes})"); + assert!(h2d > 0, "filter uploaded nothing (holes: {holes})"); + if backend.supports_hash_join() { + let probe = join_once(Arc::clone(backend), &batch, 1, &names, 0); + let build = join_once(Arc::clone(backend), &names, 0, &batch, 1); + for (side, (fallbacks, h2d)) in [("probe", probe), ("build", build)] { + assert_eq!(fallbacks, 0, "{side}-side join fell back (holes: {holes})"); + assert!(h2d > 0, "{side}-side join uploaded nothing"); + } + } + let (out, fallbacks, _) = witnessed(Arc::clone(backend), |op| { + op.vector_distance(&batch, 2, &query, DistanceMetric::L2, "d") + .unwrap() + }); + let expected = u64::from(holes); + assert_eq!(fallbacks, expected, "vector distance (holes: {holes})"); + let reference = + kernels::vector_distance(&batch, 2, &query, DistanceMetric::L2, "d").unwrap(); + let got = out.column(3).as_primitive::(); + let want = reference.column(3).as_primitive::(); + assert_eq!(got.nulls(), want.nulls(), "vector distance NULLs"); + for (row, (g, w)) in got.iter().zip(want.iter()).enumerate() { + if let (Some(g), Some(w)) = (g, w) { + assert!((g - w).abs() < 1e-4, "row {row}: {g} vs {w}"); + } + } + } + } + + #[tokio::test] + async fn null_vector_elements_survive_the_device_format() { + let backend = TransferSim::shared(); + for &seed in &SEEDS { + for &rows in &SIZES { + check_filter(Arc::clone(&backend), seed, rows).await; + check_join(Arc::clone(&backend), seed, rows).await; + } + } + assert_device_path_witnessed(&backend); + } + + /// The same on a real device. Run on a GPU box with + /// `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored`. + #[tokio::test] + #[ignore = "requires a GPU backend (CUDA or Metal) on this machine"] + async fn gpu_backend_keeps_null_vector_elements_when_available() { + let backend = HardwareDetector::select().unwrap(); + assert!( + backend.kind().is_gpu(), + "no GPU backend detected: {:?}", + backend.kind() + ); + for &seed in &SEEDS { + for &rows in &SIZES { + check_filter(Arc::clone(&backend), seed, rows).await; + check_join(Arc::clone(&backend), seed, rows).await; + } + } + assert_device_path_witnessed(&backend); + } +} + +/// IEEE special values in Float64 filters (#28). +/// +/// DataFusion 55 compares floats in IEEE totalOrder (`f64::total_cmp`: -NaN < +/// -inf < … < -0.0 < +0.0 < … < +inf < +NaN) after reading -0.0 as +0.0 on +/// both sides. The CUDA filter kernel compared with plain IEEE `>`/`==`, so +/// `NaN > 4.0` was false there; the CPU reference called Arrow's totalOrder +/// kernels as they are, so `-0.0 = 0.0` was false there. `gen_left`'s `v` +/// holds none of these values, so the suite above could see neither. They +/// stay out of it: its `v` also feeds the aggregate check, and MIN/MAX over +/// NaN and signed zeros is #101's. +mod special_floats { + use std::cmp::Ordering; + + use arrow::array::{AsArray, BooleanArray}; + use arrow::compute::filter_record_batch; + use arrow::datatypes::{Float64Type, Int64Type}; + + use super::vector_null_elements::filter_once; + use super::*; + + /// Every value where float comparison is subtle, ordinary ones between + /// them, and the two subnormals nearest zero. + const VALUES: [f64; 12] = [ + f64::NAN, + -f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + 0.0, + -0.0, + -1.5, + 2.0, + 4.0, + 4.5, + 5e-324, + -5e-324, + ]; + + /// `k Int64?`, `v Float64?` drawn from [`VALUES`] (one row in ten NULL), + /// `s Utf8` naming the row, so rows that render alike stay apart. + fn gen_special_floats(seed: u64, rows: usize) -> RecordBatch { + let mut rng = StdRng::seed_from_u64(seed ^ 0x5bec_1a1f); + let k: Vec> = (0..rows) + .map(|_| (!rng.random_bool(0.1)).then(|| rng.random_range(0..10i64))) + .collect(); + let v: Vec> = (0..rows) + .map(|_| (!rng.random_bool(0.1)).then(|| VALUES[rng.random_range(0..VALUES.len())])) + .collect(); + let s: Vec = (0..rows).map(|i| format!("r{i}")).collect(); + let schema = Arc::new(Schema::new(vec![ + Field::new("k", DataType::Int64, true), + Field::new("v", DataType::Float64, true), + Field::new("s", DataType::Utf8, false), + ])); + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(k)), + Arc::new(Float64Array::from(v)), + Arc::new(StringArray::from(s)), + ], + ) + .unwrap() + } + + /// Each predicate in SQL and as the plan's `Predicate` (`k` is column 0, + /// `v` column 1). The literals include -0.0, NaN and both infinities. + fn predicates() -> Vec<(&'static str, Predicate)> { + let v = |op, x| Predicate::compare(1, op, Literal::Float64(x)); + vec![ + ("v > 4.0", v(Comparison::Gt, 4.0)), + ("v >= 4.5", v(Comparison::GtEq, 4.5)), + ("v < 0.0", v(Comparison::Lt, 0.0)), + ("v > -0.0", v(Comparison::Gt, -0.0)), + ("v <= -0.0", v(Comparison::LtEq, -0.0)), + ("v = 0.0", v(Comparison::Eq, 0.0)), + ("v = -0.0", v(Comparison::Eq, -0.0)), + ("v >= 'NaN'::double", v(Comparison::GtEq, f64::NAN)), + ("v = 'NaN'::double", v(Comparison::Eq, f64::NAN)), + ("v > 'inf'::double", v(Comparison::Gt, f64::INFINITY)), + ("v < '-inf'::double", v(Comparison::Lt, f64::NEG_INFINITY)), + ( + "k >= 2 AND v > 4.0", + Predicate::and( + Predicate::compare(0, Comparison::GtEq, Literal::Int64(2)), + v(Comparison::Gt, 4.0), + ), + ), + ] + } + + /// Whether `predicate` selects `row` in DataFusion 55's float order, + /// written out from `f64::total_cmp` rather than through Arrow or + /// DataFusion. The 55 bump moved that order once, for -0.0, without a + /// test noticing; if it moves again, this says so before the comparison + /// with the operator does. + fn selects(batch: &RecordBatch, predicate: &Predicate, row: usize) -> bool { + match predicate { + Predicate::Compare { + column, + op, + literal, + } => { + let col = batch.column(*column); + if col.is_null(row) { + return false; + } + // `== 0.0` holds for both zeros and for nothing else. + let zeros_as_one = |x: f64| if x == 0.0 { 0.0 } else { x }; + let ord: Ordering = match literal { + Literal::Int64(x) => col.as_primitive::().value(row).cmp(x), + Literal::Float64(x) => { + let value = col.as_primitive::().value(row); + zeros_as_one(value).total_cmp(&zeros_as_one(*x)) + } + }; + match op { + Comparison::Eq => ord.is_eq(), + Comparison::Lt => ord.is_lt(), + Comparison::LtEq => ord.is_le(), + Comparison::Gt => ord.is_gt(), + Comparison::GtEq => ord.is_ge(), + } + } + Predicate::And(l, r) => selects(batch, l, row) && selects(batch, r, row), + } + } + + /// `SELECT s, k, v … WHERE predicate` by [`selects`]. + fn rows_by_hand(batch: &RecordBatch, predicate: &Predicate) -> Vec { + let keep: BooleanArray = (0..batch.num_rows()) + .map(|row| Some(selects(batch, predicate, row))) + .collect(); + let projected = batch.project(&[2, 0, 1]).unwrap(); + sorted_rows(&[filter_record_batch(&projected, &keep).unwrap()]) + } + + async fn check_filter(backend: Arc, seed: u64, rows: usize) { + let ctx = SessionContext::new(); + let batch = gen_special_floats(seed, rows); + ctx.register_batch("t", batch.clone()).unwrap(); + for (sql, predicate) in predicates() { + let expected = sql_rows(&ctx, &format!("SELECT s, k, v FROM t WHERE {sql}")).await; + assert_eq!( + expected, + rows_by_hand(&batch, &predicate), + "DataFusion's float order moved for `{sql}` (seed={seed} rows={rows}): \ + the CPU reference and filter_project.cu must follow it" + ); + let exec = GpuFilterExec::try_new( + physical_plan(&ctx, batch.clone()).await, + predicate, + vec![2, 0, 1], + backend.kind(), + ) + .unwrap() + .with_backend(Arc::clone(&backend)); + let actual = exec_rows(&ctx, Arc::new(exec)).await; + assert_eq!(actual, expected, "`{sql}` seed={seed} rows={rows}"); + } + } + + #[tokio::test] + async fn cpu_backend_filters_special_floats_like_datafusion() { + // A fixture that lost a value would make the check prove nothing. + let sample = gen_special_floats(1, 1000); + let v = sample.column(1).as_primitive::(); + for value in VALUES { + assert!( + v.iter().flatten().any(|x| x.to_bits() == value.to_bits()), + "no {value:?} in the fixture" + ); + } + for &seed in &SEEDS { + for &rows in &SIZES { + check_filter(cpu(), seed, rows).await; + } + } + } + + /// The same on a real device; on CUDA the comparisons must also have run + /// there (Metal has no `double` and declines Float64 predicates, so it + /// only has to agree). Run on a GPU box with + /// `OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored`. + #[tokio::test] + #[ignore = "requires a GPU backend (CUDA or Metal) on this machine"] + async fn gpu_backend_filters_special_floats_like_datafusion_when_available() { + let backend = HardwareDetector::select().unwrap(); + assert!( + backend.kind().is_gpu(), + "no GPU backend detected: {:?}", + backend.kind() + ); + for &seed in &SEEDS { + for &rows in &SIZES { + check_filter(Arc::clone(&backend), seed, rows).await; + } + } + let batch = gen_special_floats(3, 1000); + for (sql, predicate) in predicates() { + let (fallbacks, h2d) = + filter_once(Arc::clone(&backend), &batch, &predicate, &[2, 0, 1]); + if backend.supports_predicate(&predicate) { + assert_eq!(fallbacks, 0, "`{sql}` ran on the CPU reference"); + assert!(h2d > 0, "`{sql}` uploaded nothing"); + } + } + } +} diff --git a/crates/oxidelake-device/kernels/cuda/filter_project.cu b/crates/oxidelake-device/kernels/cuda/filter_project.cu index 9e2d2a3..9a0dfaa 100644 --- a/crates/oxidelake-device/kernels/cuda/filter_project.cu +++ b/crates/oxidelake-device/kernels/cuda/filter_project.cu @@ -6,7 +6,8 @@ // accesses; grid sizes are computed on the host. // // Pipeline (host orchestrated, all launches on one stream): -// 1. oxide_compare_{i64,f64} : one byte mask per comparison leaf +// 1. oxide_compare_{i64,f64} : one byte mask per comparison leaf (f64 in +// DataFusion's order, as the CPU reference) // 2. oxide_mask_and : conjunction of leaf masks // 3. oxide_block_count : selected rows per 256-thread block // 4. (host) exclusive scan of block counts -> block offsets, total @@ -43,6 +44,21 @@ extern "C" __global__ void oxide_compare_i64(const long long* __restrict__ value mask[i] = (unsigned char)r; } +// The order DataFusion's own filter compares doubles in, as a signed integer +// key (#28): IEEE 754 totalOrder, -NaN < -inf < ... < -0.0 < +0.0 < ... < +// +inf < +NaN, except that -0.0 is +0.0 — DataFusion 55 rewrites -0.0 to +// +0.0 on both sides before Arrow's totalOrder kernels compare them. The CPU +// reference does the same. Plain `>`/`==` on doubles does not: there +// `NaN > 4.0` is false, where DataFusion has it true. Flipping the 63 +// magnitude bits of a negative value makes a signed comparison of the bit +// patterns follow totalOrder (the transform `f64::total_cmp` applies), so +// equal keys mean equal bits, -0.0 aside. +extern "C" __device__ __forceinline__ long long oxide_f64_order_key(double v) { + long long bits = __double_as_longlong(v); + if ((unsigned long long)bits == 0x8000000000000000ULL) return 0; // -0.0 + return bits < 0 ? (bits ^ 0x7fffffffffffffffLL) : bits; +} + extern "C" __global__ void oxide_compare_f64(const double* __restrict__ values, const unsigned char* __restrict__ validity, int op, @@ -52,14 +68,15 @@ extern "C" __global__ void oxide_compare_f64(const double* __restrict__ values, unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= n) return; if (!oxide_is_valid(validity, i)) { mask[i] = 0; return; } - double v = values[i]; + long long v = oxide_f64_order_key(values[i]); + long long key = oxide_f64_order_key(literal); int r; switch (op) { - case 0: r = v == literal; break; - case 1: r = v < literal; break; - case 2: r = v <= literal; break; - case 3: r = v > literal; break; - default: r = v >= literal; break; + case 0: r = v == key; break; + case 1: r = v < key; break; + case 2: r = v <= key; break; + case 3: r = v > key; break; + default: r = v >= key; break; } mask[i] = (unsigned char)r; } diff --git a/crates/oxidelake-device/src/columns.rs b/crates/oxidelake-device/src/columns.rs index f2b61bf..3b8ca03 100644 --- a/crates/oxidelake-device/src/columns.rs +++ b/crates/oxidelake-device/src/columns.rs @@ -3,7 +3,10 @@ //! GPU backends move raw Arrow buffers: fixed-width values plus a packed //! validity bitmap. This module extracts them from any (possibly sliced) //! array of a supported type and rebuilds arrays from downloaded bytes. It -//! is backend-independent, so it is unit-tested on the CPU. +//! is backend-independent, so it is unit-tested on the CPU. The bitmap has +//! one bit per row: a vector column's elements travel without validity of +//! their own, so [`extract`] refuses a NULL element inside a valid row rather +//! than return it as a number (#105). //! //! Extraction is zero-copy: values are [`Buffer`] slices of the array's own //! allocation and validity is the array's bitmap (re-packed only when a slice @@ -98,7 +101,94 @@ fn slice_checked( Ok(buffer.slice_with_length(start, len)) } +/// The first row of a vector column that is valid but holds a NULL element, +/// or `None`, which it always is for a column of any other type. +/// +/// It is the one content of a device-eligible column that the device format +/// cannot carry: the bitmap has one bit per *row*, so the element would come +/// back from a device as a valid number (#105). [`extract`] refuses such a +/// column, and the operator layer keeps it on the host instead of uploading +/// it. NULL elements under a NULL row do not count: the row is NULL whatever +/// they hold, and a nullable vector column built with `append_null` has +/// exactly those, so counting them would keep every nullable vector column +/// off the device. +pub fn row_with_null_element(array: &dyn Array) -> Result, EngineError> { + let DataType::FixedSizeList(field, size) = array.data_type() else { + return Ok(None); + }; + if *field.data_type() != DataType::Float32 { + return Ok(None); + } + let size = + usize::try_from(*size).map_err(|_| EngineError::plan("negative FixedSizeList size"))?; + let data = array.to_data(); + let child = data + .child_data() + .first() + .ok_or_else(|| EngineError::format("FixedSizeList array without child data"))?; + null_element_row(data.nulls(), child.nulls(), data.offset(), data.len(), size) +} + +/// [`row_with_null_element`] over a list's parts: `len` rows of `size` +/// elements from row `offset`, with `rows` and `elements` the list's and its +/// child's validity. +fn null_element_row( + rows: Option<&NullBuffer>, + elements: Option<&NullBuffer>, + offset: usize, + len: usize, + size: usize, +) -> Result, EngineError> { + let Some(elements) = elements.filter(|e| e.null_count() > 0) else { + return Ok(None); + }; + let end = offset + .checked_add(len) + .and_then(|rows| rows.checked_mul(size)); + if end.is_none_or(|end| end > elements.len()) { + return Err(EngineError::format(format!( + "vector column: rows {offset}..{} of {size} elements reach past its {} child values", + offset.saturating_add(len), + elements.len() + ))); + } + let elements = elements.slice(offset * size, len * size); + let nulls = elements.null_count(); + if nulls == 0 { + return Ok(None); + } + // A nullable column whose NULL rows hold NULL elements is the common + // shape, and every upload of one asks this. Counting the NULL elements + // under NULL rows (a popcount per NULL row) answers it without visiting + // each element of each valid row: if they are all of them, no valid row + // holds one. + if let Some(rows) = rows { + let bits = elements.inner(); + let valid_in = |row: usize| { + bits.inner() + .count_set_bits_offset(bits.offset() + row * size, size) + }; + let under_null_rows: usize = (0..len) + .filter(|&row| rows.is_null(row)) + .map(|row| size - valid_in(row)) + .sum(); + if under_null_rows == nulls { + return Ok(None); + } + } + Ok(elements + .iter() + .enumerate() + .filter(|&(_, valid)| !valid) + .map(|(element, _)| element / size) + .find(|&row| rows.is_none_or(|r| r.is_valid(row)))) +} + /// Extracts the raw bytes of a supported column without copying them. +/// +/// A vector column with a NULL element inside a valid row +/// ([`row_with_null_element`]) is refused as [`EngineError::Unsupported`]: +/// this format cannot carry the element's NULL. pub fn extract(array: &ArrayRef) -> Result { let data = array.to_data(); let len = data.len(); @@ -133,6 +223,16 @@ pub fn extract(array: &ArrayRef) -> Result { .ok_or_else(|| EngineError::format("FixedSizeList child without a value buffer"))?; let start = (child.offset() + offset * size) * 4; let values = slice_checked(buffer, start, len * size * 4, "vector column")?; + if let Some(row) = null_element_row(data.nulls(), child.nulls(), offset, len, size)? { + return Err(EngineError::unsupported( + "device.vector_null_element", + format!( + "row {row} of the vector column is valid but holds a NULL element, \ + which the device format (one validity bit per row) would return \ + as a number" + ), + )); + } Ok(ColumnBytes { data_type: dt.clone(), len, @@ -311,4 +411,110 @@ mod tests { let err = extract(&arr).unwrap_err(); assert!(err.is_unsupported()); } + + /// Two-element vectors over `elements`, with optional row validity. + fn vectors(elements: Vec>, rows: Option>) -> ArrayRef { + Arc::new( + FixedSizeListArray::try_new( + Arc::new(Field::new("item", DataType::Float32, true)), + 2, + Arc::new(Float32Array::from(elements)), + rows.map(NullBuffer::from), + ) + .unwrap(), + ) + } + + /// #105: the rebuilt column used to hold `[1.0, 0.0]` where the original + /// held `[1.0, NULL]` — the element bitmap was dropped on extraction. + #[test] + fn a_null_element_in_a_valid_row_is_refused() { + let arr = vectors( + vec![Some(1.0), None, Some(3.0), Some(4.0)], + Some(vec![true, true]), + ); + let err = extract(&arr).unwrap_err(); + assert!(err.is_unsupported(), "{err}"); + assert!(err.to_string().contains("row 0"), "{err}"); + } + + /// What a builder's `append_null` leaves: NULL elements under a NULL row. + /// The row is NULL whatever they hold, so the column stays eligible and + /// round-trips equal. + #[test] + fn null_elements_under_null_rows_round_trip() { + let arr = vectors( + vec![Some(1.0), Some(2.0), None, None, Some(5.0), Some(6.0)], + Some(vec![true, false, true]), + ); + let back = rebuild(extract(&arr).unwrap()).unwrap(); + assert_eq!(back.as_ref(), arr.as_ref()); + } + + /// Only the extracted rows are checked: a slice that leaves the NULL + /// element out extracts, and round-trips equal. + #[test] + fn only_the_extracted_rows_are_checked() { + let arr = vectors( + vec![Some(1.0), None, Some(3.0), Some(4.0), Some(5.0), Some(6.0)], + None, + ); + assert!(extract(&arr).unwrap_err().is_unsupported()); + assert!(extract(&arr.slice(0, 1)).unwrap_err().is_unsupported()); + let tail = arr.slice(1, 2); + let back = rebuild(extract(&tail).unwrap()).unwrap(); + assert_eq!(back.as_ref(), tail.as_ref()); + } + + /// The shapes that decide the check: a NULL element in a valid row is + /// found, NULL elements under NULL rows never are, and the counting + /// shortcut is not fooled when the counts match but the positions do not. + #[test] + fn null_elements_count_only_in_valid_rows() { + let found = |elements: Vec>, rows: Option>| { + row_with_null_element(vectors(elements, rows).as_ref()).unwrap() + }; + assert_eq!( + found(vec![Some(1.0), Some(2.0), Some(3.0), None], None), + Some(1) + ); + assert_eq!( + found( + vec![None, None, Some(3.0), Some(4.0), Some(5.0), None], + Some(vec![false, true, false]), + ), + None + ); + // Two NULL elements, and two elements under the NULL row — but one of + // the NULLs is in valid row 0. + assert_eq!( + found( + vec![Some(1.0), None, None, Some(4.0)], + Some(vec![true, false]), + ), + Some(0) + ); + let ints: ArrayRef = Arc::new(Int64Array::from(vec![None, Some(1)])); + assert_eq!(row_with_null_element(ints.as_ref()).unwrap(), None); + } + + /// arrow-rs lists always present offset 0 with a sliced child, so a + /// list's own offset only reaches the check through its parts. + #[test] + fn the_check_counts_rows_from_the_list_offset() { + let elements = NullBuffer::from(vec![true, false, true, true, false, false]); + // Rows 1 and 2 of a list of pairs: [valid, valid] and [NULL, NULL] + // under a NULL row; the NULL element in row 0 is outside. + let rows = NullBuffer::from(vec![true, false]); + assert_eq!( + null_element_row(Some(&rows), Some(&elements), 1, 2, 2).unwrap(), + None + ); + assert_eq!( + null_element_row(None, Some(&elements), 0, 1, 2).unwrap(), + Some(0) + ); + // Rows past the child are an error, not a panic. + assert!(null_element_row(None, Some(&elements), 2, 2, 2).is_err()); + } } diff --git a/crates/oxidelake-device/src/cpu/kernels.rs b/crates/oxidelake-device/src/cpu/kernels.rs index fc04d23..cdd2b37 100644 --- a/crates/oxidelake-device/src/cpu/kernels.rs +++ b/crates/oxidelake-device/src/cpu/kernels.rs @@ -2,7 +2,8 @@ //! `RecordBatch`es. These define the semantics the GPU kernels must match: //! //! * filter: a comparison against `NULL` is `NULL`, and `NULL` predicates drop -//! the row (SQL `WHERE` semantics); +//! the row (SQL `WHERE` semantics); `Float64` compares as DataFusion's own +//! filter does, in IEEE 754 totalOrder with `-0.0` read as `+0.0`; //! * join: `NULL` keys never match; //! * aggregate: `NULL` keys form their own group; `SUM/MIN/MAX` skip `NULL`s //! and are `NULL` for groups with no values; `COUNT` counts non-`NULL`s; @@ -56,7 +57,45 @@ fn int64_column<'a>( }) } +const NEGATIVE_ZERO_BITS: u64 = (-0.0f64).to_bits(); + +/// `-0.0` as `+0.0`; every other value, NaNs included, as it is. +fn positive_zero(v: f64) -> f64 { + if v.to_bits() == NEGATIVE_ZERO_BITS { + 0.0 + } else { + v + } +} + +/// A `Float64` column with its `-0.0`s read as `+0.0`; any other column, or +/// one holding no `-0.0`, as it is. +/// +/// Arrow's `cmp` kernels order floats by IEEE 754 totalOrder, where +/// `-0.0 < +0.0`. DataFusion 55 rewrites `-0.0` to `+0.0` on both sides before +/// it calls them (`apply_cmp`), so its `FilterExec` has `-0.0 = 0.0` true and +/// `-0.0 < 0.0` false, and a GPU-placed filter has to select the rows that +/// filter selects (#28). Scanning first leaves the usual column uncopied, as +/// DataFusion's own normalization does. +fn negative_zeros_as_positive(col: &ArrayRef) -> ArrayRef { + match col.as_any().downcast_ref::() { + Some(values) + if values + .values() + .iter() + .any(|v| v.to_bits() == NEGATIVE_ZERO_BITS) => + { + Arc::new(values.unary::<_, Float64Type>(positive_zero)) + } + _ => Arc::clone(col), + } +} + /// Evaluates a predicate to a boolean mask (nulls where any operand is null). +/// +/// `Float64` compares as DataFusion does: IEEE 754 totalOrder (a NaN sorts +/// above `+inf`, or below `-inf` when its sign bit is set, and two NaNs are +/// equal only bit for bit), with `-0.0` read as `+0.0`. pub fn evaluate_predicate( batch: &RecordBatch, predicate: &Predicate, @@ -80,9 +119,10 @@ pub fn evaluate_predicate( } let scalar: ArrayRef = match literal { Literal::Int64(v) => Arc::new(Int64Array::from(vec![*v])), - Literal::Float64(v) => Arc::new(Float64Array::from(vec![*v])), + Literal::Float64(v) => Arc::new(Float64Array::from(vec![positive_zero(*v)])), }; let scalar = Scalar::new(scalar); + let col = &negative_zeros_as_positive(col); let mask = match op { Comparison::Eq => cmp::eq(col, &scalar), Comparison::Lt => cmp::lt(col, &scalar), @@ -947,6 +987,39 @@ mod tests { assert_eq!(ks.values(), &[2, 5]); } + /// The order DataFusion 55's own filter compares floats in (#28). + #[test] + fn float_comparisons_order_as_datafusion_does() { + let values = [ + f64::NAN, + -f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + 0.0, + -0.0, + 4.0, + ]; + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("v", DataType::Float64, false)])), + vec![Arc::new(Float64Array::from(values.to_vec()))], + ) + .unwrap(); + let selected = |op, x| -> Vec { + let predicate = Predicate::compare(0, op, Literal::Float64(x)); + let mask = evaluate_predicate(&batch, &predicate).unwrap(); + (0..mask.len()).filter(|&row| mask.value(row)).collect() + }; + // A NaN is above +inf, and below -inf when its sign bit is set. + assert_eq!(selected(Comparison::Gt, 4.0), [0, 2]); + assert_eq!(selected(Comparison::Lt, f64::NEG_INFINITY), [1]); + assert_eq!(selected(Comparison::Eq, f64::NAN), [0]); + // -0.0 and +0.0 are one value, in the column and in the literal. + assert_eq!(selected(Comparison::Eq, 0.0), [4, 5]); + assert_eq!(selected(Comparison::Eq, -0.0), [4, 5]); + assert_eq!(selected(Comparison::Lt, 0.0), [1, 3]); + assert_eq!(selected(Comparison::GtEq, -0.0), [0, 2, 4, 5, 6]); + } + #[test] fn filter_type_mismatch_is_unsupported() { let pred = Predicate::compare(1, Comparison::Eq, Literal::Int64(1)); diff --git a/crates/oxidelake-runtime/src/bin/oxide.rs b/crates/oxidelake-runtime/src/bin/oxide.rs index 027e35f..5c073b7 100644 --- a/crates/oxidelake-runtime/src/bin/oxide.rs +++ b/crates/oxidelake-runtime/src/bin/oxide.rs @@ -5,7 +5,7 @@ use std::io::{self, Write}; use clap::{Parser, Subcommand}; use oxidelake_core::BackendKind; use oxidelake_runtime::{OutputFormat, OxideSession, SessionOptions, dashboard}; -use oxidelake_storage::{Compression, demo_write_options, write_demo_table}; +use oxidelake_storage::{Compression, DemoOptions, demo_write_options, write_demo_table_with}; use tracing_subscriber::EnvFilter; /// Writes `text` to stdout, treating a closed reader as success (#34). @@ -58,6 +58,12 @@ enum Command { /// Compression codec: none, lz4 or zstd. #[arg(long, default_value = "zstd")] compression: Compression, + /// Put IEEE special values into `v` on every 16th row (NaN, -0.0, + /// +0.0, +inf, -inf and a negative NaN, in turn), to compare backends + /// where float comparison is subtle. Off by default; the default table + /// is unchanged. + #[arg(long)] + special_floats: bool, }, /// Run a SQL statement and print the result. Sql { @@ -178,14 +184,22 @@ async fn main() -> anyhow::Result<()> { seed, row_group_rows, compression, + special_floats, } => { let options = demo_write_options(row_group_rows, compression); - let table = write_demo_table(std::path::Path::new(&out), rows, seed, &options)?; + let demo = DemoOptions::new().with_special_floats(special_floats); + let table = + write_demo_table_with(std::path::Path::new(&out), rows, seed, demo, &options)?; write_out(&format!( - "wrote {} rows to {} (seed {seed}, {row_group_rows} rows per row group, {})\n", + "wrote {} rows to {} (seed {seed}, {row_group_rows} rows per row group, {}{})\n", table.rows, table.path.display(), compression.as_str(), + if special_floats { + ", special floats in v" + } else { + "" + }, ))?; } Command::Sql { diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index ec2852b..407e409 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -1113,3 +1113,77 @@ fn mixed_build_a_predict_worker_is_refused_by_a_default_scheduler() { assert!(stderr.contains("no worker it can use"), "{stderr}"); assert!(started.elapsed() < Duration::from_secs(30)); } + +/// `gen-data --special-floats` writes every IEEE special value into `v`, and +/// a Float64 filter over them returns the same rows planned for the CPU +/// (DataFusion's own `FilterExec`) as for CUDA (`GpuFilterExec`: the CPU +/// reference on a machine without a GPU, the device kernel on one with). +/// DataFusion 55 has `NaN > 24.5` true and `-0.0 = 0.0` true; before #28 the +/// reference had the second false, and the kernel the first. +#[test] +fn special_floats_filter_alike_on_every_target() { + let dir = tempfile::tempdir().unwrap(); + let assert = oxide() + .args([ + "gen-data", + "--rows", + "4096", + "--out", + dir.path().to_str().unwrap(), + "--special-floats", + ]) + .assert() + .success(); + let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + assert!(stdout.contains("special floats in v"), "{stdout}"); + + // Read back with the parquet crate alone: every special value is there. + let file = File::open(dir.path().join("t.parquet")).unwrap(); + let reader = ParquetRecordBatchReaderBuilder::try_new(file) + .unwrap() + .build() + .unwrap(); + let mut bits = std::collections::BTreeSet::new(); + for batch in reader { + let batch = batch.unwrap(); + let v = batch + .column(batch.schema().index_of("v").unwrap()) + .as_any() + .downcast_ref::() + .unwrap(); + bits.extend(v.iter().flatten().map(f64::to_bits)); + } + for special in [ + f64::NAN, + -f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + -0.0, + 0.0, + ] { + assert!(bits.contains(&special.to_bits()), "no {special:?} in v"); + } + + let table_arg = format!("t={}", dir.path().display()); + for predicate in ["v > 24.5", "v < 0.0", "v = 0.0", "v <= -0.0"] { + let query = format!("SELECT id, v FROM t WHERE {predicate} ORDER BY id"); + let explain = oxide() + .args(["explain", "-q", &query, "--table", &table_arg]) + .args(["--target", "cuda"]) + .assert() + .success(); + let plan = String::from_utf8(explain.get_output().stdout.clone()).unwrap(); + assert!(plan.contains("GpuFilterExec[cuda]"), "{predicate}: {plan}"); + let rows = |target: &str| { + let assert = oxide() + .args(["sql", "-q", &query, "--table", &table_arg]) + .args(["--target", target, "--output", "csv"]) + .assert() + .success(); + String::from_utf8(assert.get_output().stdout.clone()).unwrap() + }; + let cpu = rows("cpu"); + assert!(cpu.lines().count() > 1, "{predicate} selected nothing"); + assert_eq!(rows("cuda"), cpu, "{predicate}"); + } +} diff --git a/crates/oxidelake-storage/src/datagen.rs b/crates/oxidelake-storage/src/datagen.rs index 12caad7..4a11e65 100644 --- a/crates/oxidelake-storage/src/datagen.rs +++ b/crates/oxidelake-storage/src/datagen.rs @@ -6,6 +6,12 @@ //! column that stays on the CPU, and `emb` a `FixedSizeList` //! embedding for the vector-distance operator. Generation is seeded and //! chunked, so any row count re-generates identically on every platform. +//! +//! [`DemoOptions::with_special_floats`] (`oxide gen-data --special-floats`) +//! puts IEEE special values into `v` on every [`SPECIAL_FLOAT_EVERY`]th row, +//! the values where backends' float comparisons and aggregates can disagree +//! (#28). It is an overlay on the same rows: every other value, and the +//! default table itself, stay exactly as they were. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -30,6 +36,49 @@ pub const KEY_CARDINALITY: i64 = 100; /// group regardless of `--rows`. pub const CHUNK_ROWS: u64 = 65_536; +/// With [`DemoOptions::with_special_floats`], every row whose `id` is a +/// multiple of this holds one of [`SPECIAL_FLOATS`] in `v`. +pub const SPECIAL_FLOAT_EVERY: u64 = 16; + +/// The values the special-float rows cycle through, in order: NaN, -0.0, +/// +0.0, +inf, -inf, and NaN with the sign bit set — the NaN an x86 `0.0 / +/// 0.0` produces, and the least value in IEEE totalOrder where NaN is the +/// greatest. +pub const SPECIAL_FLOATS: [f64; 6] = [ + f64::NAN, + -0.0, + 0.0, + f64::INFINITY, + f64::NEG_INFINITY, + -f64::NAN, +]; + +/// What goes into the demo table besides its size and seed. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct DemoOptions { + /// See [`Self::with_special_floats`]. + pub special_floats: bool, +} + +impl DemoOptions { + /// The default table. + pub const fn new() -> Self { + Self { + special_floats: false, + } + } + + /// Puts one of [`SPECIAL_FLOATS`] into `v` on every + /// [`SPECIAL_FLOAT_EVERY`]th row (`id` 0, 16, 32, … in turn), replacing + /// whatever value — or NULL — the row had. Nothing else changes. + #[must_use] + pub const fn with_special_floats(mut self, on: bool) -> Self { + self.special_floats = on; + self + } +} + /// The 13 values the `s` column cycles through. const S_VALUES: [&str; 13] = [ "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", @@ -63,11 +112,22 @@ pub fn demo_schema() -> SchemaRef { ])) } +/// The special value row `row_id` holds under +/// [`DemoOptions::with_special_floats`], if it holds one. +fn special_float(row_id: u64) -> Option { + if !row_id.is_multiple_of(SPECIAL_FLOAT_EVERY) { + return None; + } + let turn = (row_id / SPECIAL_FLOAT_EVERY) % SPECIAL_FLOATS.len() as u64; + SPECIAL_FLOATS.get(usize::try_from(turn).ok()?).copied() +} + fn gen_chunk( schema: &SchemaRef, first_id: u64, rows: u64, seed: u64, + demo: DemoOptions, ) -> Result { // Reseed per chunk from (seed, first_id) so a chunk's bytes do not depend // on how earlier chunks were sized. @@ -78,11 +138,20 @@ fn gen_chunk( let mut v = Vec::with_capacity(n); let mut emb = Vec::with_capacity(n * EMBEDDING_DIM); for row in 0..rows { - id.push(i64::try_from(first_id + row).unwrap_or(i64::MAX)); + let row_id = first_id + row; + id.push(i64::try_from(row_id).unwrap_or(i64::MAX)); let r = splitmix64(&mut state); k.push((!r.is_multiple_of(50)).then_some((r >> 8) as i64 % KEY_CARDINALITY)); let r = splitmix64(&mut state); - v.push((!r.is_multiple_of(40)).then(|| f64::from((r >> 8) as u32 % 100) / 4.0)); + let drawn = (!r.is_multiple_of(40)).then(|| f64::from((r >> 8) as u32 % 100) / 4.0); + // Replaced after the draw, never instead of it: the PRNG stream, and + // so every other value in the table, is the same with or without. + let special = if demo.special_floats { + special_float(row_id) + } else { + None + }; + v.push(special.or(drawn)); for _ in 0..EMBEDDING_DIM { let r = splitmix64(&mut state); emb.push(f32::from((r % 2000) as u16) / 100.0 - 10.0); @@ -116,12 +185,21 @@ fn gen_chunk( /// reseeded from its first row id, so the sequence never depends on how /// earlier chunks were sized). pub fn demo_chunks(rows: u64, seed: u64) -> impl Iterator> { + demo_chunks_with(rows, seed, DemoOptions::new()) +} + +/// [`demo_chunks`] with [`DemoOptions`]. +pub fn demo_chunks_with( + rows: u64, + seed: u64, + demo: DemoOptions, +) -> impl Iterator> { let schema = demo_schema(); (0..rows) .step_by(usize::try_from(CHUNK_ROWS).unwrap_or(usize::MAX)) .map(move |first| { let n = CHUNK_ROWS.min(rows - first); - gen_chunk(&schema, first, n, seed) + gen_chunk(&schema, first, n, seed, demo) }) } @@ -131,6 +209,15 @@ pub fn demo_batches(rows: u64, seed: u64) -> Result, EngineErro demo_chunks(rows, seed).collect() } +/// [`demo_batches`] with [`DemoOptions`]. +pub fn demo_batches_with( + rows: u64, + seed: u64, + demo: DemoOptions, +) -> Result, EngineError> { + demo_chunks_with(rows, seed, demo).collect() +} + /// What [`write_demo_table`] produced. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DemoTable { @@ -149,6 +236,17 @@ pub fn write_demo_table( rows: u64, seed: u64, options: &ParquetWriteOptions, +) -> Result { + write_demo_table_with(dir, rows, seed, DemoOptions::new(), options) +} + +/// [`write_demo_table`] with [`DemoOptions`]. +pub fn write_demo_table_with( + dir: &Path, + rows: u64, + seed: u64, + demo: DemoOptions, + options: &ParquetWriteOptions, ) -> Result { // `ParquetFileWriter::create` checks them too, but only after the // directory below exists; a refused run should leave nothing behind. @@ -156,7 +254,7 @@ pub fn write_demo_table( std::fs::create_dir_all(dir)?; let path = dir.join("t.parquet"); let mut writer = ParquetFileWriter::create(&path, demo_schema(), options)?; - for chunk in demo_chunks(rows, seed) { + for chunk in demo_chunks_with(rows, seed, demo) { writer.write(&chunk?)?; } let written = writer.close()?; @@ -202,6 +300,110 @@ mod tests { assert_eq!(long[0].slice(0, 40), short[0].slice(0, 40)); } + /// FNV-1a over every generated value (`v` and `emb` by bit pattern, NULL + /// as its own marker): the table's content, independent of how Arrow or + /// Parquet happen to lay it out. + fn content_digest(batches: &[RecordBatch]) -> u64 { + use arrow::array::{Array, AsArray}; + use arrow::datatypes::{Float32Type, Float64Type, Int64Type}; + let mut hash = 0xcbf2_9ce4_8422_2325u64; + let mut eat = |bytes: &[u8]| { + for &b in bytes { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + } + }; + for batch in batches { + let id = batch.column(0).as_primitive::(); + let k = batch.column(1).as_primitive::(); + let v = batch.column(2).as_primitive::(); + let s = batch.column(3).as_string::(); + let emb = batch.column(4).as_fixed_size_list(); + let emb = emb.values().as_primitive::(); + for row in 0..batch.num_rows() { + eat(&id.value(row).to_le_bytes()); + if k.is_null(row) { + eat(b"null"); + } else { + eat(&k.value(row).to_le_bytes()); + } + if v.is_null(row) { + eat(b"null"); + } else { + eat(&v.value(row).to_bits().to_le_bytes()); + } + eat(s.value(row).as_bytes()); + for e in 0..EMBEDDING_DIM { + eat(&emb.value(row * EMBEDDING_DIM + e).to_bits().to_le_bytes()); + } + } + } + hash + } + + /// The default table is pinned: what `oxide gen-data` writes must not + /// move unless someone means it to (a test elsewhere, or a user's own + /// comparison, may depend on the exact rows). Recorded from 0.2.0's + /// generator; two chunks, so the per-chunk reseeding is covered. + #[test] + fn the_default_table_is_unchanged() { + let rows = CHUNK_ROWS + 1000; + assert_eq!( + content_digest(&demo_batches(rows, 42).unwrap()), + 13_955_388_935_552_808_329, + "the default demo table changed" + ); + } + + /// The special-float table is the default table with `v` replaced on + /// every sixteenth row, cycling through all six values — so `oxide + /// gen-data --special-floats` pins how a backend handles each of them. + #[test] + fn special_floats_overlay_the_default_table() { + use arrow::array::{Array, AsArray}; + use arrow::datatypes::Float64Type; + let rows = CHUNK_ROWS + 1000; + let plain = demo_batches(rows, 42).unwrap(); + let special = + demo_batches_with(rows, 42, DemoOptions::new().with_special_floats(true)).unwrap(); + assert_eq!(plain.len(), special.len()); + let mut seen = [0usize; SPECIAL_FLOATS.len()]; + for (p, s) in plain.iter().zip(&special) { + // Every column but `v` is untouched. + for column in [0, 1, 3, 4] { + assert_eq!(p.column(column), s.column(column), "column {column}"); + } + let ids = s.column(0).as_primitive::(); + let (pv, sv) = ( + p.column(2).as_primitive::(), + s.column(2).as_primitive::(), + ); + for row in 0..s.num_rows() { + let id = ids.value(row).unsigned_abs(); + if id.is_multiple_of(SPECIAL_FLOAT_EVERY) { + let turn = (id / SPECIAL_FLOAT_EVERY) as usize % SPECIAL_FLOATS.len(); + assert!(sv.is_valid(row), "id {id}"); + assert_eq!( + sv.value(row).to_bits(), + SPECIAL_FLOATS[turn].to_bits(), + "id {id}" + ); + seen[turn] += 1; + } else { + assert_eq!(sv.is_valid(row), pv.is_valid(row), "id {id}"); + if sv.is_valid(row) { + assert_eq!(sv.value(row).to_bits(), pv.value(row).to_bits(), "id {id}"); + } + } + } + } + assert!(seen.iter().all(|&n| n > 0), "{seen:?}"); + // The default table is not touched by the option existing. + assert_eq!( + demo_batches_with(rows, 42, DemoOptions::default()).unwrap(), + plain + ); + } + #[test] fn writes_bloom_filtered_row_groups() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/oxidelake-storage/src/lib.rs b/crates/oxidelake-storage/src/lib.rs index f1a1e94..75ba269 100644 --- a/crates/oxidelake-storage/src/lib.rs +++ b/crates/oxidelake-storage/src/lib.rs @@ -26,8 +26,9 @@ pub mod uring; #[cfg(feature = "datagen")] pub use datagen::{ - CHUNK_ROWS, DemoTable, demo_batches, demo_chunks, demo_schema, demo_write_options, - write_demo_table, + CHUNK_ROWS, DemoOptions, DemoTable, SPECIAL_FLOAT_EVERY, SPECIAL_FLOATS, demo_batches, + demo_batches_with, demo_chunks, demo_chunks_with, demo_schema, demo_write_options, + write_demo_table, write_demo_table_with, }; pub use errors::classify_error; pub use ipc::{read_ipc_file, write_ipc_file}; diff --git a/docs/SPEC.md b/docs/SPEC.md index 156336b..1fc3c56 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -109,14 +109,14 @@ DataFusion `ExecutionPlan` implementations: `GpuFilterExec` (fused filter + proj **Deliberately bounded GPU type coverage for v1** (everything outside it stays on CPU by planner rule): -- filter + project: predicates `=, <, <=, >, >=` combined with `AND` over `Int64`/`Float64` columns against literals; projection = column selection; output is stream-compacted (block-scan prefix sums). +- filter + project: predicates `=, <, <=, >, >=` combined with `AND` over `Int64`/`Float64` columns against literals; projection = column selection; output is stream-compacted (block-scan prefix sums). `Float64` compares as DataFusion's own filter does: IEEE totalOrder with `-0.0` read as `+0.0`, so a NaN sorts above `+inf` (#28). - hash join: inner join on a single `Int64` key; an open-addressing linear-probing table in device memory with one slot per distinct key, holding that key's run in a row-index array — built once per operator on the host from the CPU reference's index and uploaded, then probed in parallel; a probe batch's matches stay on the device and its output is gathered in pieces of at most the session's batch size. - aggregate: `SUM/COUNT/MIN/MAX` over `Int64`/`Float64` grouped by one `Int64` key of low cardinality, one batch at a time with the groups merged on the host; on the device, an open-addressing index of the batch's keys, its groups numbered densely, and atomic reductions into one entry per group, so only the groups are read back. - vector distance: L2 and cosine between a query vector and a `FixedSizeList` column (shared memory + warp shuffles on CUDA; threadgroup memory + simdgroup reductions on Metal). CUDA sources: `filter_project.cu`, `hash_join.cu`, `aggregation.cu`, `vector_distance.cu`. Metal sources: `filter_project.metal`, `vector_distance.metal` (joins and aggregates stay on CPU under Metal in v1 — say so in the docs). Kernels are plain `extern "C"` entry points with explicit grid-size math and bounds checks on every global access. -**Conformance suite** (in `oxidelake-compute`): for seeded random batches — including nulls, empty batches, and 0/1/odd row counts — every `Gpu*Exec` running on `CpuBackend` must equal the corresponding stock DataFusion operator. The same suite runs against CUDA/Metal when a device is present (`#[ignore]` by default). +**Conformance suite** (in `oxidelake-compute`): for seeded random batches — including nulls, empty batches, and 0/1/odd row counts, and for `Float64` filters NaN, ±0.0, ±inf and subnormals — every `Gpu*Exec` running on `CpuBackend` must equal the corresponding stock DataFusion operator. The same suite runs against CUDA/Metal when a device is present (`#[ignore]` by default). ### 2.4 Storage — `oxidelake-storage`: Parquet, Arrow IPC, io_uring object store