From 77dbdd6d5ef35cd3644223f00aa3312843772639 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:23:47 +0700 Subject: [PATCH 1/3] fix(cli): keep NULL keys and tell NaN from NULL in json output (#124) `oxide sql --output json` wrote through arrow-json's default ArrayWriter, which leaves the key of a NULL value out of its object and writes NaN, infinity and negative infinity as `null`. The issue's own command, on the base: $ oxide sql -q "SELECT 1 AS k, CAST(NULL AS DOUBLE) AS v, CAST('NaN' AS DOUBLE) AS n" --output json [{"k":1,"n":null}] so a script could tell neither a NULL from a missing column nor a NaN from a NULL. The writer is now built with explicit nulls, so every object carries every column and a NULL is `null` (a NULL field of a struct keeps its key too), and with an EncoderFactory, NonFiniteFloats, that writes the three non-finite values as the strings "NaN", "Infinity" and "-Infinity", the encoding the issue proposes. Python's float() and JavaScript's Number() read the three back (checked with python3 and node). Every finite value goes to arrow-json's own encoder, built from a factory-less copy of the options, so its formatting does not change. arrow-json asks the factory for every array it encodes, so Float16, 32 and 64 are covered, and so are the values of lists, structs and dictionaries. The WIP this finishes defined the factory but never passed it to the WriterBuilder, so NaN still came out `null`; it is wired in here. The `--output` help text, OutputFormat::Json's rustdoc, the README flag table and the CHANGELOG say what is written. Tests: - output.rs: json_is_an_array_of_objects_with_every_column (replaces json_is_an_array_of_objects_and_drops_nulls, which pinned `{}` for an all-NULL row), json_writes_nan_and_the_infinities_as_strings (Float64, Float32, Float16 and FixedSizeList columns, NULLs among the values) and json_reaches_floats_inside_structs_and_dictionaries. - cli.rs: json_output_keeps_null_keys_and_tells_nan_from_null runs the issue's command against the binary; the_flags_appear_in_help requires --help to name null, "NaN", "Infinity" and "-Infinity"; parse_json now requires the `k` key in every object, so the cross-format test, whose demo table groups NULL keys into a row, fails on a dropped key instead of reading it as a NULL. Before (base ArrayWriter, new tests): the three output.rs tests red, e.g. `[{"k":1,"name":"a,b"},{}]` and every non-finite value `null`; the CLI test red with `[{"k":1,"n":null}]`, the issue's output exactly. After: output.rs 8/8, and the four json, help and format CLI tests, green. Guards broken once each, then restored: - explicit nulls off: the three output.rs tests, the issue's CLI test (`[{"k":1,"n":"NaN"}]`) and the cross-format test ("a row without its `k` key: {"n":383}") red; - the --help sentence reverted: the_flags_appear_in_help red; - the factory not wired (the WIP as found): both float tests red; - the Float16 arm removed: the Float16 column's non-finite values `null`; - the -Infinity branch removed: the Float64 and Float32 columns and the dictionary red; - the factory's null buffer dropped: NULL floats written as 0.0. cargo fmt --check, and clippy -p oxidelake-runtime -p oxidelake-api --all-targets -D warnings: clean. Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 11 ++ README.md | 2 +- crates/oxidelake-runtime/src/bin/oxide.rs | 5 +- crates/oxidelake-runtime/src/output.rs | 230 +++++++++++++++++++++- crates/oxidelake-runtime/tests/cli.rs | 44 ++++- 5 files changed, 277 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index efcab12..5cd91a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -409,6 +409,17 @@ versions (0.x) may contain breaking changes; they are always listed under a is refused. `oxidelake_planner::codec::PLAN_FINGERPRINT` and `build_description()` are public, and `make test-mixed-build` runs both cases with real binaries. +- **`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. ### Security diff --git a/README.md b/README.md index 5a491a9..eadf818 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/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() From f8a8ddbf98d8d45af6a2a6cb502e9a7d51bc14e1 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:31:38 +0700 Subject: [PATCH 2/3] fix(api): return from OxideFrame::show() when stdout closes (#125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OxideFrame::show() was DataFusion's DataFrame::show, which is `println!("{}", self.to_string().await?)`, and `println!` panics when stdout is a closed pipe. A program showing a frame into `… | head -1` died the way `oxide sql` did before #34: panicked at library/std/src/io/stdio.rs:1166:9: failed printing to stdout: Broken pipe (os error 32) `show` now calls DataFrame::to_string, the text DataFusion's show printed (session format options and extension types included), and writes it and a newline through a locked stdout. BrokenPipe is a clean stop that returns Ok, as `oxide sql` exits 0 there (write_out in oxide.rs makes the same match); any other write error is EngineError::Io. The lock is taken after the last await: a StdoutLock is not Send, and held across the query it would make the future unspawnable. The rustdoc says all three, and STATUS.md's matrix row for OxideFrame and docs/verification.md's test layers list show and the new test binary. Tests: - tests/show_closed_pipe.rs (from the WIP), show_into_a_closed_pipe_returns_instead_of_panicking: re-runs itself as a child that shows a ~1.3 MB table (generate_series(1, 50000)), far more than a 64 KiB pipe buffer, into a pipe whose reader takes the first table line and goes; the child must report Ok and exit 0 with no panic. It has a binary of its own with nothing beside it that forks: the other test there, show_is_send, forks nothing. - tests/dataframe.rs, show_prints_the_table_and_a_newline (new): nothing tested what show() prints. The child's stdout must end with exactly DataFusion's to_string of the frame and a newline. dataframe.rs forked nothing before and has no closed-pipe test, so the child this spawns endangers none. Before (base show, new tests): the closed-pipe test red, the child panicking with the message above, then libtest failing with "io error when listing tests: ... BrokenPipe". After: api tests 5 + 2 and the doctest green. Guards broken once each, then restored: - the BrokenPipe arm removed: red, "show returned Err: I/O error: Broken pipe (os error 32)", which also shows another write error surfaces as EngineError::Io; - the newline not written: show_prints_the_table_and_a_newline red; - the lock taken before the await: show_is_send fails to compile (E0277, the ReentrantLockGuard is not Send). The library alone still compiles, so only the test catches it. The happy-path test passes on the base too, as it should: it pins the success path the rewrite had to keep. Isolation, measured with a throwaway probe (not committed): the same test beside a sibling that forks while the test holds the read end and sleeps 2 s before it execs. Fixed: show returned Ok after 2.0 s instead of 0.06 s. Base: the same panic, 1.8 s after the reader went. A forking neighbour delays this test and changes neither outcome, because the table cannot fit the pipe buffer; the module comment said the writer could "fill the buffer and succeed" and now says what was measured. Stress: each new test 200 times, 20 at a time, both at once (40 processes): 200/200 green each. cargo fmt --check, clippy -p oxidelake-api -p oxidelake-runtime --all-targets -D warnings, and rustdoc -D warnings for both: clean. Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 8 ++ STATUS.md | 2 +- crates/oxidelake-api/src/frame.rs | 24 +++- crates/oxidelake-api/tests/dataframe.rs | 41 +++++++ .../oxidelake-api/tests/show_closed_pipe.rs | 104 ++++++++++++++++++ docs/verification.md | 2 +- 6 files changed, 177 insertions(+), 4 deletions(-) create mode 100644 crates/oxidelake-api/tests/show_closed_pipe.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cd91a0..6c6aefc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -421,6 +421,14 @@ versions (0.x) may contain breaking changes; they are always listed under a `float()` and JavaScript's `Number()` read back. `--help` and the README say so. +- **`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`. + ### Security - **thrift is out of the dependency graph** (#4, #54). parquet 59 decodes diff --git a/STATUS.md b/STATUS.md index 1976e33..be2a400 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/docs/verification.md b/docs/verification.md index 609184f..69f7c01 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -152,7 +152,7 @@ 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 | From 940d9242bd6afe7394fecaf5a24efd55521456c9 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:47:31 +0700 Subject: [PATCH 3/3] docs(changelog): file #124 under Changed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit oxide sql --output json now writes NULL keys and NaN/±inf as strings; a script reading that output sees a different document, so the entry belongs with the other visible changes. It also separates it from the #92 bullet it had been joined to without a blank line. Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c6aefc..02c7272 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,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** @@ -409,17 +421,7 @@ versions (0.x) may contain breaking changes; they are always listed under a is refused. `oxidelake_planner::codec::PLAN_FINGERPRINT` and `build_description()` are public, and `make test-mixed-build` runs both cases with real binaries. -- **`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. + - **`OxideFrame::show()` no longer panics when stdout closes** (#125). It was DataFusion's `DataFrame::show`, whose `println!` panics on a closed