Skip to content

[Variant] Parse JSON directly into builders - #11409

Open
osipovartem wants to merge 11 commits into
apache:mainfrom
Embucket:upstream-variant-direct-json
Open

osipovartem wants to merge 11 commits into
apache:mainfrom
Embucket:upstream-variant-direct-json

Conversation

@osipovartem

@osipovartem osipovartem commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Why

Parse JSON into Variant builders without building a serde_json::Value tree on the common path. Keeping the original numeric lexeme also makes the separate exact-decimal follow-up (#11415) possible.

Change

  • Borrow unescaped strings and use fallible Variant builder appends. Check the complete root and use Variant's nesting limit, including empty containers at the boundary.
  • Keep the smallest signed integer encoding, treat integer -0 as zero, and use correctly rounded finite f64 parsing for the remaining numbers. -0.0 retains its sign. Exact-decimal encoding remains out of scope.
  • Builders with unique-field validation enabled now reject duplicate JSON keys, reporting the first repeated key. Default builders still keep the last value without encoding discarded payloads. For wide documents, preserve the legacy sorted object traversal. Dense lookups of wide unsorted dictionaries can build a lazy index without copying names.
  • Keep decimal-specific tests in the follow-up, and add coverage for rounding, nested depth, Unicode and escapes, duplicate and malformed input, and builder rollback.

Rebased on 8befa3cd8 after #11106, #11403 and #11411. No stacked dependency is required for this PR.

Validation

Embucket fork CI for b79870b0 passed, including Arrow and Parquet tests, Clippy, and PySpark integration.

On b79870b0, Rust 1.99.1: 619 unit tests and 82 doctests passed across parquet-variant, parquet-variant-json and parquet-variant-compute; 15 unit tests remain ignored. Clippy for the three crates' lib and test targets with -D warnings, cargo fmt --all -- --check, and git diff --check passed.

The local Criterion comparison against 8befa3cd8 measured 9-48% lower parse times across eight json_to_variant inputs (20 samples, 1 s warm-up and 1 s measurement). Separate paired probes:

Workload Apache main This revision
Read-only rebuild of 9 selected keys, 16 rows x 4,096 keys in reverse input order 44-45 us 43 us
Parse a wide object with a long nested numeric array, 64 rows 5.82-5.88 ms 6.21-6.32 ms

The 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.

@github-actions github-actions Bot added the parquet-variant parquet-variant* crates label Oct 6, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Oct 8, 2026
…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.
@alamb alamb added the performance Speed or memory optimizations label Oct 16, 2026
@osipovartem
osipovartem force-pushed the upstream-variant-direct-json branch 2 times, most recently from b30cd6c to 0ec2458 Compare October 23, 2026 23:40
@osipovartem
osipovartem marked this pull request as ready for review October 23, 2026 23:41

@sdf-jkl sdf-jkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for taking a while @osipovartem. Left some suggestions!

Comment thread parquet-variant-json/src/from_json.rs Outdated
Comment on lines +22 to +26
use parquet_variant::{ObjectFieldBuilder, Variant, VariantBuilderExt};
use serde_json::{Number, Value};
use std::borrow::Cow;

const MAX_JSON_DEPTH: usize = 128;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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;

Comment thread parquet-variant-json/src/from_json.rs Outdated
Comment on lines +168 to +171
if depth > MAX_JSON_DEPTH {
return self.error("recursion limit exceeded");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 128

Variant 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 {}.

Suggested change
if depth > MAX_JSON_DEPTH {
return self.error("recursion limit exceeded");
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread parquet-variant-json/src/from_json.rs Outdated
builder: &mut impl VariantBuilderExt,
depth: usize,
) -> Result<(), ArrowError> {
self.offset += 1;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.offset += 1;
self.check_depth(depth)?;
self.offset += 1;

Comment thread parquet-variant-json/src/from_json.rs Outdated
builder: &mut impl VariantBuilderExt,
depth: usize,
) -> Result<(), ArrowError> {
self.offset += 1;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.offset += 1;
self.check_depth(depth)?;
self.offset += 1;

}?
}

fn ensure_root_end(&mut self, depth: usize) -> Result<(), ArrowError> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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> {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment on lines +1097 to +1103
#[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}");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Suggested change
#[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}");
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. 1e400 now has its own row in the invalid-input table, which checks both rejection and builder rollback.

Comment on lines +1124 to +1138
#[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(())
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
#[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(())
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +591 to +601
#[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(())
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
#[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(())
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Combined these into one number-boundary table, including negative overflow and integer -0. The float-rounding test checks -0.0 by bits.

Comment on lines +1156 to +1166
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"}"#,
];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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,
];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Folded the escaped key, long escaped string, and multibyte boundary cases into the existing serde comparison table.

Comment thread parquet-variant-json/src/from_json.rs Outdated
Comment on lines +1105 to +1122
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}");
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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}");
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@osipovartem
osipovartem force-pushed the upstream-variant-direct-json branch from 749ede8 to b79870b Compare November 25, 2026 19:12
@osipovartem
osipovartem requested a review from sdf-jkl November 26, 2026 08:05

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

parquet-variant parquet-variant* crates performance Speed or memory optimizations

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants