Repository navigation
[Variant] Parse JSON directly into builders - #11409
osipovartem wants to merge 11 commits into
Conversation
…11411) ## Which issue does this PR relate to? Benchmark requested during review of #11177 (related to #11169). It also provides a direct kernel baseline for #11409. ## What changes are included? Extend the existing `parquet-variant-compute` Criterion benchmark for `json_to_variant` with six incremental JSON shapes: Int32, fixed-point decimals, escaped strings, a 1,024-element array, an 8 KiB string, and a 100 KiB duplicate-key object. Existing short-string and nested-structure cases remain unchanged. Each input is prebuilt outside the timed loop into up to 8,000 rows and approximately 1 MiB of JSON. The new cases use the existing `bench_function` naming convention and report bytes per document plus row count in their IDs. No separate serde/builder measurements, library behavior, or public API changes. ## Validation - `cargo +1.95.0 bench -p parquet-variant-compute --bench variant_kernels --offline -- "batch_json_string_to_variant (int32|fixed_point_decimals|escaped_strings|large_array_1024|large_string_8k|duplicate_key_100k)" --quick` (all six new cases ran) - `cargo +1.99.0 clippy -p parquet-variant-compute --bench variant_kernels --offline -- -D warnings` - `cargo +1.95.0 fmt --all -- --check` - Independent read-only review: approved, no blocking findings.
b30cd6c to
0ec2458
Compare
sdf-jkl
left a comment
There was a problem hiding this comment.
Sorry for taking a while @osipovartem. Left some suggestions!
| use parquet_variant::{ObjectFieldBuilder, Variant, VariantBuilderExt}; | ||
| use serde_json::{Number, Value}; | ||
| use std::borrow::Cow; | ||
|
|
||
| const MAX_JSON_DEPTH: usize = 128; |
There was a problem hiding this comment.
MAX_JSON_DEPTH has the same meaning as parquet_variant::MAX_NESTING_DEPTH (#10352). Reusing it keeps this limit tied to the one Variant validation enforces (see the depth comment below). test_json_to_variant_limits_nesting_depth would use it too.
| use parquet_variant::{ObjectFieldBuilder, Variant, VariantBuilderExt}; | |
| use serde_json::{Number, Value}; | |
| use std::borrow::Cow; | |
| const MAX_JSON_DEPTH: usize = 128; | |
| use parquet_variant::{MAX_NESTING_DEPTH, ObjectFieldBuilder, Variant, VariantBuilderExt}; | |
| use serde_json::{Number, Value}; | |
| use std::borrow::Cow; |
| if depth > MAX_JSON_DEPTH { | ||
| return self.error("recursion limit exceeded"); | ||
| } | ||
|
|
There was a problem hiding this comment.
This check runs when a value is entered, so an empty container at the limit is never checked. 129 nested arrays with an empty innermost [] (or 128 levels whose innermost value is {}) parse fine, but the result fails validation:
let json = format!("{}[]{}", "[".repeat(128), "]".repeat(128));
let mut builder = VariantBuilder::new();
builder.append_json(&json)?; // Ok
let (metadata, value) = builder.finish();
Variant::try_new(&metadata, &value)?; // Err: Variant nesting depth exceeds the maximum of 128Variant validation limits containers (depth >= MAX_NESTING_DEPTH in variant/list.rs and object.rs), so checking when a container is entered matches it exactly: 128 nested containers accepted, 129 rejected, whatever the innermost value is. Suggest removing this check and calling a small check_depth at the start of parse_array and parse_object (suggestions below), plus a regression case with an empty innermost [] and {}.
| if depth > MAX_JSON_DEPTH { | |
| return self.error("recursion limit exceeded"); | |
| } |
There was a problem hiding this comment.
Both array and object entry now check the shared MAX_NESTING_DEPTH limit before reading children. The regression accepts 128 containers and rejects 129, including empty [] and {} leaves.
| builder: &mut impl VariantBuilderExt, | ||
| depth: usize, | ||
| ) -> Result<(), ArrowError> { | ||
| self.offset += 1; |
There was a problem hiding this comment.
| self.offset += 1; | |
| self.check_depth(depth)?; | |
| self.offset += 1; |
| builder: &mut impl VariantBuilderExt, | ||
| depth: usize, | ||
| ) -> Result<(), ArrowError> { | ||
| self.offset += 1; |
There was a problem hiding this comment.
| self.offset += 1; | |
| self.check_depth(depth)?; | |
| self.offset += 1; |
| }? | ||
| } | ||
|
|
||
| fn ensure_root_end(&mut self, depth: usize) -> Result<(), ArrowError> { |
There was a problem hiding this comment.
| fn ensure_root_end(&mut self, depth: usize) -> Result<(), ArrowError> { | |
| /// Containers nest at most `MAX_NESTING_DEPTH` deep, the limit Variant validation enforces. | |
| fn check_depth(&self, depth: usize) -> Result<(), ArrowError> { | |
| if depth >= MAX_NESTING_DEPTH { | |
| return self.error("recursion limit exceeded"); | |
| } | |
| Ok(()) | |
| } | |
| fn ensure_root_end(&mut self, depth: usize) -> Result<(), ArrowError> { |
There was a problem hiding this comment.
Thanks for the detailed review! In b79870b0, the parser checks MAX_NESTING_DEPTH when entering a container, including empty containers and values appended within an existing builder. It uses lexical-core for finite float rounding, encodes integer -0 as zero, and preserves the sign of -0.0. The revision also consolidates the invalid-input/rollback tests, covers long escaped and UTF-8 strings, and documents when to override try_append_value. The existing decimal tests are unchanged; exact decimal handling remains in #11415.
The fork CI passed on this SHA. Could you take another look when you have a chance?
| #[test] | ||
| fn test_json_to_variant_rejects_non_finite_double() { | ||
| let mut builder = VariantBuilder::new(); | ||
| let error = builder.append_json("1e400").unwrap_err().to_string(); | ||
| assert!(error.contains("finite number"), "{error}"); | ||
| } | ||
|
|
There was a problem hiding this comment.
1e400 is valid grammar but out of range, so it's still a distinct case, just a row in the invalid table rather than its own test (suggested there).
| #[test] | |
| fn test_json_to_variant_rejects_non_finite_double() { | |
| let mut builder = VariantBuilder::new(); | |
| let error = builder.append_json("1e400").unwrap_err().to_string(); | |
| assert!(error.contains("finite number"), "{error}"); | |
| } |
There was a problem hiding this comment.
Agreed. 1e400 now has its own row in the invalid-input table, which checks both rejection and builder rollback.
| #[test] | ||
| fn test_json_to_variant_error_does_not_modify_builder() -> Result<(), ArrowError> { | ||
| for invalid in ["1x", "true false", "[]x", "{}x", "[1,]", "{\"a\":1,}"] { | ||
| let mut builder = VariantBuilder::new(); | ||
| assert!( | ||
| builder.append_json(invalid).is_err(), | ||
| "accepted {invalid:?}" | ||
| ); | ||
| builder.append_json("2")?; | ||
| let (metadata, value) = builder.finish(); | ||
| assert_eq!(Variant::try_new(&metadata, &value)?, Variant::Int8(2)); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
There was a problem hiding this comment.
With the atomicity check inside the invalid-table loop, every invalid input is checked this way, and these inputs are either already in the table or added as rows (1x, []x, {}x). This test can go.
| #[test] | |
| fn test_json_to_variant_error_does_not_modify_builder() -> Result<(), ArrowError> { | |
| for invalid in ["1x", "true false", "[]x", "{}x", "[1,]", "{\"a\":1,}"] { | |
| let mut builder = VariantBuilder::new(); | |
| assert!( | |
| builder.append_json(invalid).is_err(), | |
| "accepted {invalid:?}" | |
| ); | |
| builder.append_json("2")?; | |
| let (metadata, value) = builder.finish(); | |
| assert_eq!(Variant::try_new(&metadata, &value)?, Variant::Int8(2)); | |
| } | |
| Ok(()) | |
| } |
There was a problem hiding this comment.
Moved the rollback assertion into the invalid-input table. It now runs for every invalid case, including 1e400, trailing garbage, and raw control bytes in short and long strings.
| #[test] | ||
| fn test_json_to_variant_int64_boundaries() -> Result<(), ArrowError> { | ||
| for (json, expected) in [ | ||
| ("-9223372036854775808", Variant::Int64(i64::MIN)), | ||
| ("9223372036854775807", Variant::Int64(i64::MAX)), | ||
| ] { | ||
| JsonToVariantTest { json, expected }.run()?; | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
There was a problem hiding this comment.
This and test_json_to_variant_preserves_existing_number_kinds have the same shape. One table can cover both, and also negative overflow (-9223372036854775809, the checked_sub path in parse_number), which nothing tests now. The -0 row assumes the number-parsing suggestions above.
| #[test] | |
| fn test_json_to_variant_int64_boundaries() -> Result<(), ArrowError> { | |
| for (json, expected) in [ | |
| ("-9223372036854775808", Variant::Int64(i64::MIN)), | |
| ("9223372036854775807", Variant::Int64(i64::MAX)), | |
| ] { | |
| JsonToVariantTest { json, expected }.run()?; | |
| } | |
| Ok(()) | |
| } | |
| #[test] | |
| fn test_json_to_variant_number_boundaries() -> Result<(), ArrowError> { | |
| for (json, expected) in [ | |
| ("-9223372036854775808", Variant::Int64(i64::MIN)), | |
| ("9223372036854775807", Variant::Int64(i64::MAX)), | |
| // Integers past i64 fall back to Double, on both sides. | |
| ("9223372036854775808", Variant::Double(2_f64.powi(63))), | |
| ("-9223372036854775809", Variant::Double(-(2_f64.powi(63)))), | |
| ("-0", Variant::Int8(0)), | |
| ("1.23", Variant::Double(1.23)), | |
| ] { | |
| JsonToVariantTest { json, expected }.run()?; | |
| } | |
| Ok(()) | |
| } | |
There was a problem hiding this comment.
Combined these into one number-boundary table, including negative overflow and integer -0. The float-rounding test checks -0.0 by bits.
| fn test_json_parser_matches_serde_for_non_numeric_semantics() -> Result<(), ArrowError> { | ||
| let cases = [ | ||
| "null", | ||
| "true", | ||
| r#""plain""#, | ||
| r#""escaped\ntext\t\"quote\"""#, | ||
| r#""\uD834\uDD1E""#, | ||
| r#"[null,true,false,"text",["nested"]]"#, | ||
| r#"{"z":null,"a":[true,{"unicode":"\u2764"}]}"#, | ||
| r#"{"duplicate":"first","duplicate":"last"}"#, | ||
| ]; |
There was a problem hiding this comment.
Strings longer than 32 bytes take the memchr2 path in parse_string, and none of the cases here exercise it together with escapes or multibyte characters crossing the 32-byte point. Two generated rows cover that, plus the escaped key from test_json_to_variant_escaped_strings:
| fn test_json_parser_matches_serde_for_non_numeric_semantics() -> Result<(), ArrowError> { | |
| let cases = [ | |
| "null", | |
| "true", | |
| r#""plain""#, | |
| r#""escaped\ntext\t\"quote\"""#, | |
| r#""\uD834\uDD1E""#, | |
| r#"[null,true,false,"text",["nested"]]"#, | |
| r#"{"z":null,"a":[true,{"unicode":"\u2764"}]}"#, | |
| r#"{"duplicate":"first","duplicate":"last"}"#, | |
| ]; | |
| fn test_json_parser_matches_serde_for_non_numeric_semantics() -> Result<(), ArrowError> { | |
| // Strings longer than 32 bytes take the memchr path, then escapes switch to serde. | |
| let long_escaped = format!("\"{}\\n\\u00e9{}\"", "x".repeat(40), "y".repeat(40)); | |
| let long_multibyte = format!("\"{}é{}\"", "x".repeat(31), "😀".repeat(10)); | |
| let cases = [ | |
| "null", | |
| "true", | |
| r#""plain""#, | |
| r#""escaped\ntext\t\"quote\"""#, | |
| r#""\uD834\uDD1E""#, | |
| r#"[null,true,false,"text",["nested"]]"#, | |
| r#"{"z":null,"a":[true,{"unicode":"\u2764"}]}"#, | |
| r#"{"duplicate":"first","duplicate":"last"}"#, | |
| r#"{"line\nkey":"quote: \"; slash: \\; unicode: \u2764"}"#, | |
| &long_escaped, | |
| &long_multibyte, | |
| ]; |
There was a problem hiding this comment.
Folded the escaped key, long escaped string, and multibyte boundary cases into the existing serde comparison table.
| fn test_json_to_variant_limits_nesting_depth() { | ||
| let accepted = format!( | ||
| "{}0{}", | ||
| "[".repeat(MAX_JSON_DEPTH), | ||
| "]".repeat(MAX_JSON_DEPTH) | ||
| ); | ||
| let mut builder = VariantBuilder::new(); | ||
| builder.append_json(&accepted).unwrap(); | ||
|
|
||
| let rejected = format!( | ||
| "{}0{}", | ||
| "[".repeat(MAX_JSON_DEPTH + 1), | ||
| "]".repeat(MAX_JSON_DEPTH + 1) | ||
| ); | ||
| let mut builder = VariantBuilder::new(); | ||
| let error = builder.append_json(&rejected).unwrap_err().to_string(); | ||
| assert!(error.contains("recursion limit"), "{error}"); | ||
| } |
There was a problem hiding this comment.
With MAX_JSON_DEPTH replaced by MAX_NESTING_DEPTH (suggested at the top of the file), this test needs the new name. It's also a good place for the regression case from the depth comment above: an empty innermost [] or {} at the limit.
| fn test_json_to_variant_limits_nesting_depth() { | |
| let accepted = format!( | |
| "{}0{}", | |
| "[".repeat(MAX_JSON_DEPTH), | |
| "]".repeat(MAX_JSON_DEPTH) | |
| ); | |
| let mut builder = VariantBuilder::new(); | |
| builder.append_json(&accepted).unwrap(); | |
| let rejected = format!( | |
| "{}0{}", | |
| "[".repeat(MAX_JSON_DEPTH + 1), | |
| "]".repeat(MAX_JSON_DEPTH + 1) | |
| ); | |
| let mut builder = VariantBuilder::new(); | |
| let error = builder.append_json(&rejected).unwrap_err().to_string(); | |
| assert!(error.contains("recursion limit"), "{error}"); | |
| } | |
| fn test_json_to_variant_limits_nesting_depth() { | |
| let accepted = format!( | |
| "{}0{}", | |
| "[".repeat(MAX_NESTING_DEPTH), | |
| "]".repeat(MAX_NESTING_DEPTH) | |
| ); | |
| let mut builder = VariantBuilder::new(); | |
| builder.append_json(&accepted).unwrap(); | |
| let rejected = format!( | |
| "{}0{}", | |
| "[".repeat(MAX_NESTING_DEPTH + 1), | |
| "]".repeat(MAX_NESTING_DEPTH + 1) | |
| ); | |
| let mut builder = VariantBuilder::new(); | |
| let error = builder.append_json(&rejected).unwrap_err().to_string(); | |
| assert!(error.contains("recursion limit"), "{error}"); | |
| // An empty innermost container adds a nesting level without a nested value. | |
| for (inner, depth) in [("[]", MAX_NESTING_DEPTH), ("{}", MAX_NESTING_DEPTH)] { | |
| let ok = format!("{}{inner}{}", "[".repeat(depth - 1), "]".repeat(depth - 1)); | |
| let mut builder = VariantBuilder::new(); | |
| builder.append_json(&ok).unwrap(); | |
| let (metadata, value) = builder.finish(); | |
| Variant::try_new(&metadata, &value).unwrap(); | |
| let too_deep = format!("{}{inner}{}", "[".repeat(depth), "]".repeat(depth)); | |
| let mut builder = VariantBuilder::new(); | |
| let error = builder.append_json(&too_deep).unwrap_err().to_string(); | |
| assert!(error.contains("recursion limit"), "{inner}: {error}"); | |
| } | |
| } |
There was a problem hiding this comment.
Added boundary cases for scalar, empty array, and empty object leaves. The accepted values also pass Variant::try_new; a separate test covers appending inside an existing builder.
749ede8 to
b79870b
Compare
Why
Parse JSON into Variant builders without building a
serde_json::Valuetree on the common path. Keeping the original numeric lexeme also makes the separate exact-decimal follow-up (#11415) possible.Change
-0as zero, and use correctly rounded finitef64parsing for the remaining numbers.-0.0retains its sign. Exact-decimal encoding remains out of scope.Rebased on
8befa3cd8after #11106, #11403 and #11411. No stacked dependency is required for this PR.Validation
Embucket fork CI for
b79870b0passed, including Arrow and Parquet tests, Clippy, and PySpark integration.On
b79870b0, Rust 1.99.1: 619 unit tests and 82 doctests passed acrossparquet-variant,parquet-variant-jsonandparquet-variant-compute; 15 unit tests remain ignored. Clippy for the three crates' lib and test targets with-D warnings,cargo fmt --all -- --check, andgit diff --checkpassed.The local Criterion comparison against
8befa3cd8measured 9-48% lower parse times across eightjson_to_variantinputs (20 samples, 1 s warm-up and 1 s measurement). Separate paired probes:mainThe last case uses the buffered path and remains 6-9% slower. These are focused local measurements, not a general no-regression claim.
AI assistance was used for the review fixes, regression tests, and benchmark iterations. The author reviewed the exact published diff.