diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ec13fd..a24e659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,18 @@ versions (0.x) may contain breaking changes; they are always listed under a come back in build order, as the CPU reference returns them. Not yet run on a GPU (STATUS.md). +- **`oxide sql --output json` keeps the key of a NULL and tells NaN from + NULL** (#124). Every object now carries every column, a NULL as `null`; + the key used to be left out, so a script could not tell a NULL from a + column that does not exist. NaN, infinity and negative infinity, which + JSON has no number for, are the strings `"NaN"`, `"Infinity"` and + `"-Infinity"` in every float type, inside lists, structs and + dictionaries too; all three used to be written `null`, like a NULL. A + script that took a missing key for NULL reads `null` instead, and one + that reads a float column accepts the three strings, which Python's + `float()` and JavaScript's `Number()` read back. `--help` and the README + say so. + ### Fixed - **A LIMIT over a GPU-placed filter or join returns its row count again** @@ -426,6 +438,15 @@ versions (0.x) may contain breaking changes; they are always listed under a `build_description()` are public, and `make test-mixed-build` runs both cases with real binaries. + +- **`OxideFrame::show()` no longer panics when stdout closes** (#125). It + was DataFusion's `DataFrame::show`, whose `println!` panics on a closed + pipe, so a program showing a frame into `… | head -1` died with `failed + printing to stdout: Broken pipe`: the crash #34 fixed in `oxide sql` and + left in the library. `show` now writes the same table itself, and a + reader that has gone is a clean stop that returns `Ok`, as `oxide sql` + exits 0 there; any other write failure is an `EngineError::Io`. + ### Fixed - **A crates.io error can no longer switch the release's semver check off.** diff --git a/README.md b/README.md index 9dfbc2c..d68755f 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ error, never a silent fallback. | `--cluster` | `sql` | — | Runs on a Ballista scheduler (`df://host:port`) instead of in-process. | | `--target` | `sql`, `explain`, `tui` | detected | Plans for `cpu`, `cuda` or `metal`. Placement only: execution uses the hardware that is present. Embedded mode only — on a cluster the scheduler decides. | | `--batch-size` | `sql`, `explain`, `tui` | 8192, or 65536 on a GPU target | Rows per record batch. Batch boundaries never change results; larger batches amortise the host↔device round trip. `0` is refused. With `--cluster` the GPU default is the scheduler's call (its target), and a size given here is kept. | -| `--output` | `sql` | `table` | `table`, `json` (an array of objects) or `csv` (RFC 4180 with a header). An empty result still prints the CSV header and `[]`, so a script can tell "no rows" from "the query failed". | +| `--output` | `sql` | `table` | `table`, `json` (an array of objects, one per row, each carrying every column) or `csv` (RFC 4180 with a header). In `json` a NULL is `null`, and NaN, infinity and negative infinity, which JSON has no number for, are the strings `"NaN"`, `"Infinity"` and `"-Infinity"`, which Python's `float()` and JavaScript's `Number()` read back. An empty result still prints the CSV header and `[]`, so a script can tell "no rows" from "the query failed". | | `--rows` | `gen-data` | `1000000` | Rows in the demo table. | | `--out` | `gen-data` | — | Output directory; writes `/t.parquet`. | | `--seed` | `gen-data` | `42` | PRNG seed. The same seed always writes the same bytes. | diff --git a/STATUS.md b/STATUS.md index 3163c9f..5fbb791 100644 --- a/STATUS.md +++ b/STATUS.md @@ -52,7 +52,7 @@ Filled in as phases complete. Every component goes under exactly one column — | `oxide gen-data` (deterministic SplitMix64 dataset, Bloom filters on `id`/`k`) | datagen unit tests + CLI e2e with independent `parquet`-crate verification | | | | `oxide sql` / `oxide explain --target` / spawned-cluster `--cluster` equality | `oxidelake-runtime/tests/cli.rs` (assert_cmd, real `oxide-scheduler` + `oxide-worker` processes) | | | | Embedded cpu/cuda/metal target equivalence (incl. the vector query) | `oxidelake-runtime/tests/embedded.rs`; **(macOS)** the metal target actually executes on the device; **(T4)** the cuda target actually executes on the device — this test is what caught the aggregation kernel bug (failed 8 of 8 runs before the fix, 8 of 8 green after); the README quickstart (`gen-data` 1M rows → `explain`/`sql --target cuda`) plans `GpuFilterExec[cuda]` + `GpuAggregateExec[cuda]` and returns the same 98 group rows as `--target cpu` | | | -| `OxideFrame` DataFrame API (filter/select/join/aggregate/vector_distance/explain/collect) | `oxidelake-api/tests/dataframe.rs` vs SQL equivalents | | | +| `OxideFrame` DataFrame API (filter/select/join/aggregate/vector_distance/explain/collect/show) | `oxidelake-api/tests/dataframe.rs` vs SQL equivalents; `show` run in a child process, whole and into a closed pipe (`tests/show_closed_pipe.rs`, #125) | | | | `oxide tui` (query dashboard: plan DAG + live telemetry + column profiles) | dashboard unit test (plan tags, real counters, profiles); driven end to end in a sized PTY (demo + `--query --target metal`), `q` exits 0 | | | ## Resolved dependency set diff --git a/crates/oxidelake-api/src/frame.rs b/crates/oxidelake-api/src/frame.rs index aa8d2f8..cf10cbc 100644 --- a/crates/oxidelake-api/src/frame.rs +++ b/crates/oxidelake-api/src/frame.rs @@ -8,6 +8,7 @@ //! `SELECT *, l2_distance(emb, …) AS d` and lowers to `GpuVectorDistanceExec` //! on a GPU target. +use std::io::Write; use std::sync::Arc; use datafusion::arrow::array::RecordBatch; @@ -127,9 +128,28 @@ impl OxideFrame { Ok(self.inner.collect().await?) } - /// Executes the frame and prints it as a table. + /// Executes the frame and prints it on stdout as a table, formatted as + /// DataFusion's `DataFrame::show` formats it. + /// + /// A reader that goes away before the table is written, as `… | head -1` + /// does once it has its line, is a clean stop: `show` returns `Ok`, as + /// `oxide sql` exits 0 there (#34). Any other write failure is + /// [`EngineError::Io`]. pub async fn show(self) -> Result<(), EngineError> { - Ok(self.inner.show().await?) + // Not `DataFrame::show`: its `println!` panics on a closed pipe + // (#125). `to_string` is what it prints, so the text is the same. + let table = self.inner.to_string().await?; + // Locked after the last await: a `StdoutLock` is not `Send`, and + // holding one across an await would make this future unspawnable. + let mut stdout = std::io::stdout().lock(); + match stdout + .write_all(table.as_bytes()) + .and_then(|()| stdout.write_all(b"\n")) + .and_then(|()| stdout.flush()) + { + Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()), + other => other.map_err(EngineError::from), + } } } diff --git a/crates/oxidelake-api/tests/dataframe.rs b/crates/oxidelake-api/tests/dataframe.rs index a2db16a..42e3c3e 100644 --- a/crates/oxidelake-api/tests/dataframe.rs +++ b/crates/oxidelake-api/tests/dataframe.rs @@ -216,3 +216,44 @@ async fn read_parquet_and_explain_show_placement() { let rows = frame.collect().await.unwrap(); assert!(rows.iter().map(RecordBatch::num_rows).sum::() > 0); } + +/// `show` prints the table DataFusion's `DataFrame::show` printed, then a +/// newline, and nothing else (#125 replaced its `println!`). It writes to +/// the process's stdout, so the check runs it in a child, this test again, +/// with stdout piped. The closed-pipe case is `tests/show_closed_pipe.rs`. +#[tokio::test] +async fn show_prints_the_table_and_a_newline() { + const CHILD: &str = "OXIDELAKE_TEST_SHOW_TABLE_CHILD"; + const NAME: &str = "show_prints_the_table_and_a_newline"; + const QUERY: &str = "SELECT 1 AS a, CAST(NULL AS VARCHAR) AS b"; + let session = OxideSession::local().unwrap(); + if std::env::var_os(CHILD).is_some() { + let shown = session.sql_frame(QUERY).await.unwrap().show().await; + // Out before the harness prints its result line after the table. + std::process::exit(if shown.is_ok() { 0 } else { 3 }); + } + let table = session + .sql_frame(QUERY) + .await + .unwrap() + .into_inner() + .to_string() + .await + .unwrap(); + assert!(table.contains("| 1 |"), "{table}"); + + // `--nocapture`, so a `print!`-based `show` reaches the pipe too. + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args([NAME, "--exact", "--nocapture", "--quiet"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(0), "{stderr}"); + // The harness's "running 1 test" line, then exactly the table. + let stdout = String::from_utf8(out.stdout).unwrap(); + assert!( + stdout.ends_with(&format!("\n{table}\n")), + "expected the table then a newline:\n{table}\ngot:\n{stdout}" + ); +} diff --git a/crates/oxidelake-api/tests/show_closed_pipe.rs b/crates/oxidelake-api/tests/show_closed_pipe.rs new file mode 100644 index 0000000..a588744 --- /dev/null +++ b/crates/oxidelake-api/tests/show_closed_pipe.rs @@ -0,0 +1,104 @@ +//! `OxideFrame::show()` into a reader that goes away (#125). +//! +//! `… | head -1` is the most ordinary thing a shell does to a program that +//! prints a table, and `show()` used to panic on it: it was DataFusion's +//! `DataFrame::show`, whose `println!` panics when stdout is a closed pipe — +//! the crash #34 fixed in the `oxide` binary and left in the library. +//! +//! This is its own test binary, with nothing beside it that forks. A process +//! that another test forks while this one holds the pipe's read end keeps a +//! copy until it execs, and no write fails with `EPIPE` while a reader is +//! left. With a table this size that only delays the result (a sibling that +//! held the read end for 2 s delayed the panic, and the fix's clean stop, by +//! 2 s), but a closed-pipe test should not depend on its neighbours' timing. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::io::{BufRead, BufReader}; +use std::process::{Command, Stdio}; + +use oxidelake_api::prelude::*; + +/// Set in the child the test spawns: the process whose stdout is closed. +const CHILD: &str = "OXIDELAKE_TEST_SHOW_CHILD"; +const NAME: &str = "show_into_a_closed_pipe_returns_instead_of_panicking"; + +/// Prints a table far larger than a pipe buffer, says on stderr what `show` +/// returned, and exits with that answer before the test harness can print +/// anything more into the closed pipe. +async fn child() { + let session = OxideSession::local().unwrap(); + // About 1.3 MB of table: a pipe buffer holds 64 KiB, so `show` is still + // writing when the reader goes. + let frame = session + .sql_frame("SELECT value AS id, value * 3 AS k FROM generate_series(1, 50000)") + .await + .unwrap(); + match frame.show().await { + Ok(()) => { + eprintln!("show returned Ok"); + std::process::exit(0); + } + Err(e) => { + eprintln!("show returned Err: {e}"); + std::process::exit(3); + } + } +} + +/// The reader takes the table's first line and goes, as `head -1` does; the +/// writer must stop cleanly, with `Ok`, as `oxide sql` does (#34). +#[tokio::test] +async fn show_into_a_closed_pipe_returns_instead_of_panicking() { + if std::env::var_os(CHILD).is_some() { + child().await; + return; + } + // `--nocapture`, or the harness would capture the old `println!` into a + // buffer and the closed pipe would never be written to; `--quiet`, so the + // harness prints nothing between its first line and the table. + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([NAME, "--exact", "--nocapture", "--quiet"]) + .env(CHILD, "1") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let mut line = String::new(); + let mut saw_table = false; + while stdout.read_line(&mut line).unwrap() > 0 { + if line.starts_with("+-") { + saw_table = true; + break; + } + line.clear(); + } + drop(stdout); + + let out = child.wait_with_output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(saw_table, "the child printed no table:\n{stderr}"); + assert!( + !stderr.contains("panicked"), + "a closed pipe is not a crash:\n{stderr}" + ); + assert!( + stderr.contains("show returned Ok"), + "a reader that goes away is a clean stop:\n{stderr}" + ); + assert_eq!(out.status.code(), Some(0), "{stderr}"); +} + +/// `show` stays spawnable. The stdout lock it writes through is not `Send`, +/// so it is taken after the query's last await; held across the query, it +/// would stop every `tokio::spawn(frame.show())` from compiling. No process +/// is forked here, so this shares the binary safely. +#[test] +fn show_is_send() { + fn spawnable(_: F) {} + let session = OxideSession::local().unwrap(); + let frame = OxideFrame::new(session.ctx().read_empty().unwrap()); + spawnable(frame.show()); +} diff --git a/crates/oxidelake-runtime/src/bin/oxide.rs b/crates/oxidelake-runtime/src/bin/oxide.rs index 0f10ca8..027e35f 100644 --- a/crates/oxidelake-runtime/src/bin/oxide.rs +++ b/crates/oxidelake-runtime/src/bin/oxide.rs @@ -79,7 +79,10 @@ enum Command { /// GPU-target default (65536). Batch boundaries never change results. #[arg(long, value_name = "ROWS")] batch_size: Option, - /// How to print the result: table, json or csv. + /// How to print the result: table, json or csv. In json every object + /// carries every column, a NULL as `null`, and NaN, infinity and + /// negative infinity, which JSON has no number for, as the strings + /// "NaN", "Infinity" and "-Infinity". #[arg(long, value_name = "FORMAT", default_value = "table")] output: OutputFormat, }, diff --git a/crates/oxidelake-runtime/src/output.rs b/crates/oxidelake-runtime/src/output.rs index af3b884..3904a06 100644 --- a/crates/oxidelake-runtime/src/output.rs +++ b/crates/oxidelake-runtime/src/output.rs @@ -8,9 +8,17 @@ use std::io::Write; use std::str::FromStr; +use std::sync::{Arc, LazyLock}; -use datafusion::arrow::array::RecordBatch; -use datafusion::arrow::datatypes::SchemaRef; +use datafusion::arrow::array::{Array, ArrowPrimitiveType, AsArray, PrimitiveArray, RecordBatch}; +use datafusion::arrow::datatypes::{ + DataType, FieldRef, Float16Type, Float32Type, Float64Type, SchemaRef, +}; +use datafusion::arrow::error::ArrowError; +use datafusion::arrow::json::writer::{ + Encoder, EncoderFactory, EncoderOptions, JsonArray, NullableEncoder, WriterBuilder, + make_encoder, +}; use datafusion::arrow::util::pretty::pretty_format_batches; use oxidelake_core::EngineError; @@ -21,7 +29,9 @@ pub enum OutputFormat { /// An aligned ASCII table (the default). #[default] Table, - /// A JSON array of objects, one per row. + /// A JSON array of objects, one per row, each carrying every column: a + /// NULL is `null`, and NaN and the infinities, which JSON has no number + /// for, are the strings `"NaN"`, `"Infinity"` and `"-Infinity"`. Json, /// RFC 4180 CSV with a header row. Csv, @@ -76,7 +86,14 @@ pub fn render( OutputFormat::Table => Ok(format!("{}\n", pretty_format_batches(batches)?)), OutputFormat::Json => { let mut buffer = Vec::new(); - let mut writer = datafusion::arrow::json::ArrayWriter::new(&mut buffer); + // arrow-json leaves a NULL's key out of its object by default, so + // a script could not tell a NULL from a column that does not + // exist; and it writes NaN and both infinities as `null`, so it + // could not tell them from a NULL either (#124). + let mut writer = WriterBuilder::new() + .with_explicit_nulls(true) + .with_encoder_factory(Arc::new(NonFiniteFloats)) + .build::<_, JsonArray>(&mut buffer); writer.write_batches(&batches.iter().collect::>())?; writer.finish()?; finish(buffer) @@ -100,6 +117,90 @@ pub fn render( } } +/// arrow-json's options with no encoder factory, which [`NonFiniteFloats`] +/// builds its fallback encoders with: the same options would hand the array +/// straight back to the factory. +static PLAIN: LazyLock = LazyLock::new(EncoderOptions::default); + +/// Writes NaN, infinity and negative infinity as the JSON strings `"NaN"`, +/// `"Infinity"` and `"-Infinity"` (#124). +/// +/// JSON has no number for any of the three, and arrow-json writes all of +/// them as `null`: a NaN read back as a NULL, which a query engine must not +/// confuse. These strings are what Python's `float()` and JavaScript's +/// `Number()` read back as the same values. Every finite value is handed to +/// arrow-json's own encoder, so its formatting does not change. arrow-json +/// asks the factory for every array it encodes, the values of lists, +/// structs and dictionaries included, so a float nested anywhere is covered. +#[derive(Debug)] +struct NonFiniteFloats; + +impl EncoderFactory for NonFiniteFloats { + fn make_default_encoder<'a>( + &self, + field: &'a FieldRef, + array: &'a dyn Array, + _options: &'a EncoderOptions, + ) -> Result>, ArrowError> { + let encoder: Box = match array.data_type() { + DataType::Float16 => Box::new(FloatEncoder::new( + array.as_primitive::(), + field, + |v| v.to_f64(), + )?), + DataType::Float32 => Box::new(FloatEncoder::new( + array.as_primitive::(), + field, + f64::from, + )?), + DataType::Float64 => Box::new(FloatEncoder::new( + array.as_primitive::(), + field, + |v| v, + )?), + _ => return Ok(None), + }; + Ok(Some(NullableEncoder::new(encoder, array.nulls().cloned()))) + } +} + +/// One float array: the three non-finite values as strings, everything else +/// through arrow-json's encoder for the same array. +struct FloatEncoder<'a, T: ArrowPrimitiveType> { + array: &'a PrimitiveArray, + to_f64: fn(T::Native) -> f64, + finite: NullableEncoder<'a>, +} + +impl<'a, T: ArrowPrimitiveType> FloatEncoder<'a, T> { + fn new( + array: &'a PrimitiveArray, + field: &'a FieldRef, + to_f64: fn(T::Native) -> f64, + ) -> Result { + Ok(Self { + array, + to_f64, + finite: make_encoder(field, array, &PLAIN)?, + }) + } +} + +impl Encoder for FloatEncoder<'_, T> { + fn encode(&mut self, idx: usize, out: &mut Vec) { + let value = (self.to_f64)(self.array.value(idx)); + if value.is_nan() { + out.extend_from_slice(b"\"NaN\""); + } else if value == f64::INFINITY { + out.extend_from_slice(b"\"Infinity\""); + } else if value == f64::NEG_INFINITY { + out.extend_from_slice(b"\"-Infinity\""); + } else { + self.finite.encode(idx, out); + } + } +} + /// Turns a writer's buffer into a newline-terminated `String`. fn finish(mut buffer: Vec) -> Result { if !buffer.ends_with(b"\n") { @@ -114,8 +215,12 @@ fn finish(mut buffer: Vec) -> Result { mod tests { use std::sync::Arc; - use datafusion::arrow::array::{Int64Array, StringArray}; - use datafusion::arrow::datatypes::{DataType, Field, Schema}; + use datafusion::arrow::array::{ + ArrayRef, DictionaryArray, FixedSizeListArray, Float32Array, Float64Array, Int8Array, + Int64Array, StringArray, StructArray, + }; + use datafusion::arrow::compute::cast; + use datafusion::arrow::datatypes::{DataType, Field, Int8Type, Schema}; use super::*; @@ -152,10 +257,119 @@ mod tests { assert!(message.contains("table, json, csv"), "{message}"); } + /// Every object carries every column, a NULL as `null` (#124). arrow-json + /// leaves a NULL's key out by default, and a script could not tell a + /// NULL from a column that does not exist: this row used to be `{}`. #[test] - fn json_is_an_array_of_objects_and_drops_nulls() { + fn json_is_an_array_of_objects_with_every_column() { let text = render(&schema(), &[batch()], OutputFormat::Json).unwrap(); - assert_eq!(text, "[{\"k\":1,\"name\":\"a,b\"},{}]\n"); + assert_eq!( + text, + "[{\"k\":1,\"name\":\"a,b\"},{\"k\":null,\"name\":null}]\n" + ); + } + + /// NaN and the infinities have no JSON number, and arrow-json wrote all + /// three as `null`, which is how a NULL is written (#124). They are + /// strings now, in every float type and inside a list, while finite + /// values and NULLs keep their encoding. + #[test] + fn json_writes_nan_and_the_infinities_as_strings() { + let item = Arc::new(Field::new("item", DataType::Float32, true)); + let schema = Arc::new(Schema::new(vec![ + Field::new("d", DataType::Float64, true), + Field::new("f", DataType::Float32, true), + Field::new("h", DataType::Float16, true), + Field::new("v", DataType::FixedSizeList(Arc::clone(&item), 2), true), + ])); + let d = Float64Array::from(vec![ + Some(f64::NAN), + Some(f64::INFINITY), + Some(f64::NEG_INFINITY), + Some(1.5), + None, + ]); + let f = Float32Array::from(vec![ + Some(f32::NEG_INFINITY), + Some(f32::NAN), + Some(0.25), + Some(f32::INFINITY), + None, + ]); + // Arrow's cast keeps NaN and the infinities, and spares this crate a + // dependency on `half` for one test column. + let h = cast( + &Float32Array::from(vec![ + Some(0.5), + Some(f32::NEG_INFINITY), + Some(f32::NAN), + Some(f32::INFINITY), + None, + ]), + &DataType::Float16, + ) + .unwrap(); + let v = FixedSizeListArray::new( + item, + 2, + Arc::new(Float32Array::from(vec![ + Some(f32::NAN), + Some(0.5), + None, + Some(f32::INFINITY), + Some(0.0), + Some(0.0), + Some(0.0), + Some(0.0), + Some(0.0), + Some(0.0), + ])), + Some(vec![true, true, true, true, false].into()), + ); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(d), Arc::new(f), h, Arc::new(v)], + ) + .unwrap(); + let text = render(&schema, &[batch], OutputFormat::Json).unwrap(); + assert_eq!( + text, + concat!( + "[{\"d\":\"NaN\",\"f\":\"-Infinity\",\"h\":0.5,\"v\":[\"NaN\",0.5]},", + "{\"d\":\"Infinity\",\"f\":\"NaN\",\"h\":\"-Infinity\",\"v\":[null,\"Infinity\"]},", + "{\"d\":\"-Infinity\",\"f\":0.25,\"h\":\"NaN\",\"v\":[0.0,0.0]},", + "{\"d\":1.5,\"f\":\"Infinity\",\"h\":\"Infinity\",\"v\":[0.0,0.0]},", + "{\"d\":null,\"f\":null,\"h\":null,\"v\":null}]\n", + ) + ); + } + + /// arrow-json builds the encoder of a struct's fields and of a + /// dictionary's values through the same factory, so a float there is + /// written the same way, and a NULL field of a struct keeps its key. + #[test] + fn json_reaches_floats_inside_structs_and_dictionaries() { + let x = Arc::new(Float64Array::from(vec![Some(f64::NAN), None])) as ArrayRef; + let s = StructArray::from(vec![( + Arc::new(Field::new("x", DataType::Float64, true)), + x, + )]); + let e = DictionaryArray::::try_new( + Int8Array::from(vec![1, 0]), + Arc::new(Float64Array::from(vec![f64::NEG_INFINITY, 2.5])), + ) + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("s", s.data_type().clone(), true), + Field::new("e", e.data_type().clone(), true), + ])); + let batch = + RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(s), Arc::new(e)]).unwrap(); + let text = render(&schema, &[batch], OutputFormat::Json).unwrap(); + assert_eq!( + text, + "[{\"s\":{\"x\":\"NaN\"},\"e\":2.5},{\"s\":{\"x\":null},\"e\":\"-Infinity\"}]\n" + ); } #[test] diff --git a/crates/oxidelake-runtime/tests/cli.rs b/crates/oxidelake-runtime/tests/cli.rs index d6640b3..53d5c8a 100644 --- a/crates/oxidelake-runtime/tests/cli.rs +++ b/crates/oxidelake-runtime/tests/cli.rs @@ -392,9 +392,8 @@ fn parse_csv(stdout: &str) -> BTreeMap, i64> { .collect() } -/// `k -> n` parsed out of the JSON form. A null `k` is *absent* from the -/// object rather than `null`, which is arrow-json's encoding and is why this -/// reads the key rather than expecting it. +/// `k -> n` parsed out of the JSON form, where a NULL `k` is `null`: every +/// object carries every column (#124). fn parse_json(stdout: &str) -> BTreeMap, i64> { let trimmed = stdout.trim(); let inner = trimmed @@ -408,16 +407,24 @@ fn parse_json(stdout: &str) -> BTreeMap, i64> { .split("},{") .map(|object| { let object = object.trim_matches(['{', '}']); + // A missing `k` fails here rather than reading as a NULL: the + // demo table's NULL keys group into a row whose key must be there. let mut row = (None, None); for field in object.split(',') { let (name, value) = field.split_once(':').unwrap(); match name.trim_matches('"') { - "k" => row.0 = Some(value.parse::().unwrap()), + "k" => { + row.0 = Some((value != "null").then(|| value.parse::().unwrap())); + } "n" => row.1 = Some(value.parse::().unwrap()), other => panic!("unexpected field {other}"), } } - (row.0, row.1.expect("every row has a count")) + ( + row.0 + .unwrap_or_else(|| panic!("a row without its `k` key: {{{object}}}")), + row.1.expect("every row has a count"), + ) }) .collect() } @@ -487,6 +494,25 @@ fn an_empty_result_keeps_its_csv_header_and_json_array() { assert_eq!(run("json"), "[]\n"); } +/// The issue's own command (#124): `v` is NULL and keeps its key, and `n` is +/// NaN, which JSON has no number for and which used to be written as the +/// `null` that a NULL is written as. +#[test] +fn json_output_keeps_null_keys_and_tells_nan_from_null() { + let assert = oxide() + .args([ + "sql", + "-q", + "SELECT 1 AS k, CAST(NULL AS DOUBLE) AS v, CAST('NaN' AS DOUBLE) AS n", + "--output", + "json", + ]) + .assert() + .success(); + let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + assert_eq!(stdout, "[{\"k\":1,\"v\":null,\"n\":\"NaN\"}]\n"); +} + /// Zero rows per batch would be accepted by DataFusion and then return /// nothing, which reads as an empty result rather than as a bad flag. #[test] @@ -518,6 +544,14 @@ fn the_flags_appear_in_help() { for flag in ["--batch-size", "--output", "--target", "--cluster"] { assert!(help.contains(flag), "oxide sql --help lacks {flag}\n{help}"); } + // What `--output json` writes for a NULL and a NaN is a contract a script + // depends on, so the flag's help states it (#124). + for encoding in ["null", "\"NaN\"", "\"Infinity\"", "\"-Infinity\""] { + assert!( + help.contains(encoding), + "oxide sql --help does not say how json writes {encoding}\n{help}" + ); + } let assert = Command::cargo_bin("oxide-worker") .unwrap() diff --git a/docs/verification.md b/docs/verification.md index 2e22c87..63d374e 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -179,7 +179,7 @@ OXIDE_BACKEND=cuda cargo test -p oxidelake-compute --features cuda -- --ignored | Distributed equivalence | `oxidelake-runtime/tests` | in-process Ballista scheduler + 2 executors on ephemeral ports; `Gpu*Exec` nodes through the codec | | Embedded GPU-target equivalence | `oxidelake-runtime/tests/embedded.rs` | the same queries under cpu/cuda/metal placement targets return identical rows (multi-partition plans included) | | SQL UDFs | `oxidelake-compute/src/udf.rs` | `l2_distance` / `cosine_distance` against the reference kernels, null and coercion cases | -| DataFrame API | `oxidelake-api/tests/dataframe.rs` | every verb against its SQL equivalent; GPU-target plans show `Gpu*Exec` for fluent pipelines | +| DataFrame API | `oxidelake-api/tests/dataframe.rs`, `show_closed_pipe.rs` | every verb against its SQL equivalent; GPU-target plans show `Gpu*Exec` for fluent pipelines; `show` run in a child process, whole and into a closed pipe (in a binary of its own, so no other test forks while the pipe is open) | | TUI in-process | `oxidelake-tui/tests/tui_render_test.rs` | `ratatui::backend::TestBackend` + `insta` | | TUI end-to-end | `oxidelake-tui/tests/tui_pty_test.rs` | `termlens` driving `oxidelake-tui-demo` in a real PTY: three text snapshots, one styled, and the focus/backend colours as cell assertions | | TUI emulator invariants | `oxidelake-tui/tests/emulation.rs` | `Screen::unsupported()` pinned exactly, no terminal mode left set, snapshot-text and JSON round trips |