diff --git a/Cargo.lock b/Cargo.lock index 7b098aa8a98..fedbc730e60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2637,6 +2637,8 @@ dependencies = [ "opentelemetry-otlp", "opentelemetry_sdk", "parking_lot", + "parquet-variant", + "parquet-variant-compute", "tokio", "url", "vortex", @@ -7836,6 +7838,9 @@ dependencies = [ "num-integer", "num-traits", "object_store 0.13.2", + "parquet-variant", + "parquet-variant-compute", + "parquet-variant-json", "seq-macro", "simdutf8", "snap", @@ -11122,6 +11127,7 @@ dependencies = [ "bytes", "bzip2", "clap", + "flate2", "futures", "geo", "geo-traits", @@ -11141,6 +11147,8 @@ dependencies = [ "object_store 0.13.2", "parking_lot", "parquet 59.3.2", + "parquet-variant", + "parquet-variant-compute", "rand 0.10.4", "regex", "reqwest 0.13.5", diff --git a/Cargo.toml b/Cargo.toml index c052198fed4..cd49566c3b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -164,6 +164,7 @@ env_logger = "0.11" fastlanes = { version = "0.8.1", features = ["runtime"] } fearless_simd = "1.0.0" fearless_simd_macros = "0.1.0" +flate2 = "1.1" flatbuffers = "25.2.10" fsst-rs = "0.7.0" futures = { version = "0.3.31", default-features = false } diff --git a/bench-orchestrator/README.md b/bench-orchestrator/README.md index 5b69e5f4de5..f9bd6ceea0e 100644 --- a/bench-orchestrator/README.md +++ b/bench-orchestrator/README.md @@ -41,7 +41,7 @@ vx-bench run [options] **Arguments:** -- `benchmark`: Benchmark suite to run (`appian`, `tpch`, `tpcds`, `clickbench`, `fineweb`, `gh-archive`, `job`, `polarsignals`, `public-bi`, `statpopgen`, `tpch-nested`) +- `benchmark`: Benchmark suite to run (`appian`, `tpch`, `tpcds`, `clickbench`, `fineweb`, `gh-archive`, `job`, `jsonbench`, `polarsignals`, `public-bi`, `statpopgen`, `tpch-nested`) **Options:** diff --git a/bench-orchestrator/bench_orchestrator/config.py b/bench-orchestrator/bench_orchestrator/config.py index 77b62c9c9d7..aa9afa6f680 100644 --- a/bench-orchestrator/bench_orchestrator/config.py +++ b/bench-orchestrator/bench_orchestrator/config.py @@ -93,6 +93,7 @@ class Benchmark(Enum): FINEWEB = "fineweb" GHARCHIVE = "gh-archive" JOB = "job" + JSONBENCH = "jsonbench" POLARSIGNALS = "polarsignals" PUBLIC_BI = "public-bi" STATPOPGEN = "statpopgen" @@ -126,6 +127,18 @@ class Benchmark(Enum): } +# Engine/format targets a benchmark cannot run, beyond what `ENGINE_FORMATS` rules out. JSONBench +# stores a Variant column, which the Vortex DuckDB extension cannot export to DuckDB yet. +BENCHMARK_UNSUPPORTED_TARGETS: dict[Benchmark, frozenset[tuple[Engine, Format]]] = { + Benchmark.JSONBENCH: frozenset( + { + (Engine.DUCKDB, Format.VORTEX), + (Engine.DUCKDB, Format.VORTEX_COMPACT), + } + ), +} + + # Formats whose targets name an integration and a scan engine. Other formats (Parquet, DuckDB's own # format, Lance) are controls and comparisons, with neither axis. VORTEX_FORMATS: frozenset[Format] = frozenset({Format.VORTEX, Format.VORTEX_COMPACT, Format.VORTEX_SPATIAL_NATIVE}) @@ -195,6 +208,11 @@ def engines_for_benchmark(benchmark: Benchmark) -> frozenset[Engine]: return BENCHMARK_ENGINES.get(benchmark, frozenset(Engine)) +def benchmark_supports_target(benchmark: Benchmark, engine: Engine, fmt: Format) -> bool: + """Return whether `benchmark` can run on `engine` over `fmt`, given the engine supports both.""" + return (engine, fmt) not in BENCHMARK_UNSUPPORTED_TARGETS.get(benchmark, frozenset()) + + T = TypeVar("T") @@ -400,6 +418,11 @@ def resolve_axis_targets( if not target.is_supported(): warnings.append(f"Format {fmt.value} is not supported by engine {engine.value}") continue + if benchmark is not None and not benchmark_supports_target(benchmark, target.engine, target.format): + warnings.append( + f"Benchmark {benchmark.value} does not support format {fmt.value} on engine {engine.value}" + ) + continue targets.append(target) return _unique_preserve_order(targets), warnings @@ -424,6 +447,11 @@ def validate_targets( errors.extend(target.support_errors(benchmark)) if benchmark is not None and target.engine not in engines_for_benchmark(benchmark): errors.append(f"Benchmark {benchmark.value} does not support engine {target.engine.value}") + elif benchmark is not None and not benchmark_supports_target(benchmark, target.engine, target.format): + errors.append( + f"Benchmark {benchmark.value} does not support format {target.format.value} " + f"on engine {target.engine.value}" + ) if options.get("remote-data-dir") and any(target.format == Format.LANCE for target in normalized_targets): errors.append("Lance format is not supported for remote storage benchmarks.") diff --git a/bench-orchestrator/tests/test_config.py b/bench-orchestrator/tests/test_config.py index f73b8bffaf7..a271551ddf7 100644 --- a/bench-orchestrator/tests/test_config.py +++ b/bench-orchestrator/tests/test_config.py @@ -243,3 +243,34 @@ def test_validate_targets_rejects_v2_on_list_layouts() -> None: ) assert errors == ["Benchmark tpch-nested cannot run the v2 scan yet (list layout): duckdb:vortex [file, v2]"] + + +def test_resolve_axis_targets_skips_jsonbench_vortex_on_duckdb() -> None: + # The Vortex DuckDB extension cannot export JSONBench's Variant column yet. + targets, warnings = resolve_axis_targets( + [Engine.DATAFUSION, Engine.DUCKDB], + [Format.PARQUET, Format.VORTEX], + Benchmark.JSONBENCH, + ) + + assert targets == [ + BenchmarkTarget(engine=Engine.DATAFUSION, format=Format.PARQUET), + BenchmarkTarget(Engine.DATAFUSION, Format.VORTEX, Integration.FILE, ScanEngine.V2), + BenchmarkTarget(engine=Engine.DUCKDB, format=Format.PARQUET), + ] + assert warnings == ["Benchmark jsonbench does not support format vortex on engine duckdb"] + + +def test_validate_targets_rejects_jsonbench_vortex_on_duckdb() -> None: + errors = validate_targets( + [BenchmarkTarget(engine=Engine.DUCKDB, format=Format.VORTEX)], + {}, + Benchmark.JSONBENCH, + ) + + assert errors == ["Benchmark jsonbench does not support format vortex on engine duckdb"] + + +def test_jsonbench_runs_on_the_v2_scan() -> None: + # The split-wide sharing of decoded Variant storage is part of the V2 scan. + assert default_scan_engine(Benchmark.JSONBENCH) is ScanEngine.V2 diff --git a/benchmarks/datafusion-bench/Cargo.toml b/benchmarks/datafusion-bench/Cargo.toml index 1e6968db76a..e74e84bc255 100644 --- a/benchmarks/datafusion-bench/Cargo.toml +++ b/benchmarks/datafusion-bench/Cargo.toml @@ -41,6 +41,8 @@ opentelemetry.workspace = true opentelemetry-otlp.workspace = true opentelemetry_sdk.workspace = true parking_lot = { workspace = true } +parquet-variant = { workspace = true } +parquet-variant-compute = { workspace = true } tokio = { workspace = true, features = ["full"] } url = { workspace = true } vortex = { workspace = true, features = ["object_store", "files", "tokio"] } diff --git a/benchmarks/datafusion-bench/src/lib.rs b/benchmarks/datafusion-bench/src/lib.rs index 820c0a228cb..574f0e17e3d 100644 --- a/benchmarks/datafusion-bench/src/lib.rs +++ b/benchmarks/datafusion-bench/src/lib.rs @@ -3,6 +3,7 @@ pub mod metrics; pub mod tracer; +pub mod variant; use std::sync::Arc; @@ -66,7 +67,9 @@ pub fn get_session_context() -> SessionContext { file_formats.push(Arc::new(factory)); } - SessionContext::new_with_state(session_state_builder.build()) + let session = SessionContext::new_with_state(session_state_builder.build()); + variant::register_variant_functions(&session); + session } pub fn make_object_store( diff --git a/benchmarks/datafusion-bench/src/main.rs b/benchmarks/datafusion-bench/src/main.rs index d5d6d328513..575753a5093 100644 --- a/benchmarks/datafusion-bench/src/main.rs +++ b/benchmarks/datafusion-bench/src/main.rs @@ -151,7 +151,7 @@ async fn main() -> anyhow::Result<()> { let benchmark = create_benchmark(args.benchmark, &opts)?; let filtered_queries = filter_queries( - benchmark.queries()?, + benchmark.queries_for_engine(Engine::DataFusion)?, args.queries.as_ref(), args.exclude_queries.as_ref(), ); diff --git a/benchmarks/datafusion-bench/src/variant.rs b/benchmarks/datafusion-bench/src/variant.rs new file mode 100644 index 00000000000..0b0a21de015 --- /dev/null +++ b/benchmarks/datafusion-bench/src/variant.rs @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! A `try_variant_get(variant, path, type)` function for DataFusion. +//! +//! This is a stand-in for the function of the same name and signature in +//! [`datafusion-variant`](https://github.com/datafusion-contrib/datafusion-variant), which has no +//! release for the DataFusion and Arrow versions that Vortex builds against. Both evaluate with the +//! `variant_get` kernel of `parquet-variant-compute`. Replace this module with +//! `datafusion_variant::register_all` once the versions line up. + +use std::sync::Arc; + +use datafusion::arrow::array::ArrayRef; +use datafusion::arrow::datatypes::DataType; +use datafusion::arrow::datatypes::Field; +use datafusion::arrow::datatypes::FieldRef; +use datafusion::logical_expr::ColumnarValue; +use datafusion::logical_expr::ExpressionPlacement; +use datafusion::logical_expr::ReturnFieldArgs; +use datafusion::logical_expr::ScalarFunctionArgs; +use datafusion::logical_expr::ScalarUDF; +use datafusion::logical_expr::ScalarUDFImpl; +use datafusion::logical_expr::Signature; +use datafusion::logical_expr::Volatility; +use datafusion::prelude::SessionContext; +use datafusion_common::Result as DFResult; +use datafusion_common::ScalarValue; +use datafusion_common::exec_err; +use datafusion_common::plan_err; +use parquet_variant::VariantPath; +use parquet_variant_compute::GetOptions; +use parquet_variant_compute::variant_get; + +/// Registers the Variant functions with `ctx`. +pub fn register_variant_functions(ctx: &SessionContext) { + ctx.register_udf(ScalarUDF::new_from_impl(VariantGetUdf::new())); +} + +/// `try_variant_get(variant, path, type)`: the value at `path` of each Variant, cast to the SQL +/// type named `type`. +/// +/// `path` is `$.` and a dot-separated list of object fields, such as `'$.commit.collection'`. A +/// missing path or a value that cannot be cast yields null. Both `path` and `type` must be string +/// literals. +#[derive(Debug, PartialEq, Eq, Hash)] +struct VariantGetUdf { + signature: Signature, +} + +impl VariantGetUdf { + fn new() -> Self { + Self { + signature: Signature::any(3, Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for VariantGetUdf { + fn name(&self) -> &str { + "try_variant_get" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> DFResult { + plan_err!("try_variant_get derives its return type from its type argument") + } + + fn return_field_from_args(&self, args: ReturnFieldArgs) -> DFResult { + let Some(Some(type_name)) = args.scalar_arguments.get(2) else { + return plan_err!("the type argument of try_variant_get must be a literal"); + }; + let data_type = sql_type(string_literal("type", type_name)?)?; + Ok(Arc::new(Field::new(self.name(), data_type, true))) + } + + /// Extraction is cheap next to reading a whole Variant, so DataFusion moves it into a + /// projection above the scan, which a source that understands `try_variant_get` can absorb. + fn placement(&self, args: &[ExpressionPlacement]) -> ExpressionPlacement { + match args { + [ + ExpressionPlacement::Column, + ExpressionPlacement::Literal, + ExpressionPlacement::Literal, + ] => ExpressionPlacement::MoveTowardsLeafNodes, + _ => ExpressionPlacement::KeepInPlace, + } + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DFResult { + let [variant, path, _type] = args.args.as_slice() else { + return exec_err!("try_variant_get expects 3 arguments, got {}", args.args.len()); + }; + let ColumnarValue::Scalar(path) = path else { + return exec_err!("the path argument of try_variant_get must be a literal"); + }; + let Some(path) = string_literal("path", path)?.strip_prefix("$.") else { + return exec_err!("the path argument of try_variant_get must start with `$.`"); + }; + let path = VariantPath::try_from(path)?; + let options = GetOptions::new_with_path(path).with_as_type(Some(args.return_field)); + + let input: ArrayRef = variant.to_array(args.number_rows)?; + Ok(ColumnarValue::Array(variant_get(&input, options)?)) + } +} + +/// The value of the string literal `scalar`, which is the `argument` of `try_variant_get`. +fn string_literal<'a>(argument: &str, scalar: &'a ScalarValue) -> DFResult<&'a str> { + match scalar { + ScalarValue::Utf8(Some(value)) + | ScalarValue::Utf8View(Some(value)) + | ScalarValue::LargeUtf8(Some(value)) => Ok(value), + other => exec_err!( + "the {argument} argument of try_variant_get must be a non-null string literal, got {}", + other.data_type() + ), + } +} + +/// The Arrow type that the SQL type `name` maps to. +fn sql_type(name: &str) -> DFResult { + Ok(match name.to_ascii_uppercase().as_str() { + "VARCHAR" | "TEXT" | "STRING" => DataType::Utf8View, + "BIGINT" => DataType::Int64, + "INT" | "INTEGER" => DataType::Int32, + "DOUBLE" => DataType::Float64, + "BOOLEAN" => DataType::Boolean, + _ => return plan_err!("try_variant_get does not support the type {name}"), + }) +} diff --git a/benchmarks/duckdb-bench/src/main.rs b/benchmarks/duckdb-bench/src/main.rs index bac918790b3..f46bfd21b43 100644 --- a/benchmarks/duckdb-bench/src/main.rs +++ b/benchmarks/duckdb-bench/src/main.rs @@ -123,7 +123,7 @@ fn main() -> anyhow::Result<()> { let benchmark = create_benchmark(args.benchmark, &opts)?; let filtered_queries = filter_queries( - benchmark.queries()?, + benchmark.queries_for_engine(Engine::DuckDB)?, args.queries.as_ref(), args.exclude_queries.as_ref(), ); diff --git a/vortex-bench/Cargo.toml b/vortex-bench/Cargo.toml index e952d3178e4..61e0082f707 100644 --- a/vortex-bench/Cargo.toml +++ b/vortex-bench/Cargo.toml @@ -40,6 +40,7 @@ async-trait = { workspace = true } bytes = { workspace = true } bzip2 = { workspace = true } clap = { workspace = true, features = ["derive"] } +flate2 = { workspace = true } futures = { workspace = true } geo = { workspace = true } geo-traits = { workspace = true } @@ -57,7 +58,12 @@ noodles-bgzf = { workspace = true, features = ["async"] } noodles-vcf = { workspace = true, features = ["async"] } object_store = { workspace = true, features = ["aws"] } parking_lot = { workspace = true } -parquet = { workspace = true, features = ["async", "object_store"] } +parquet = { workspace = true, features = [ + "async", + "object_store", + "variant_experimental", +] } +parquet-variant-compute = { workspace = true } rand = { workspace = true } regex = { workspace = true } reqwest = { workspace = true, features = ["stream"] } @@ -88,5 +94,6 @@ wkb = { workspace = true } [dev-dependencies] insta = { workspace = true } +parquet-variant = { workspace = true } rstest = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } diff --git a/vortex-bench/sql/jsonbench.md b/vortex-bench/sql/jsonbench.md new file mode 100644 index 00000000000..71b81b234af --- /dev/null +++ b/vortex-bench/sql/jsonbench.md @@ -0,0 +1,148 @@ +# JSONBench benchmark + +[JSONBench](https://github.com/ClickHouse/JSONBench) is ClickHouse's benchmark for analytics +over semi-structured data: Bluesky firehose events, one JSON document per row. This suite +stores each document in a single Variant column, `data`, of the table `bluesky`, and runs +JSONBench's five queries. It is the main workload for the Vortex Variant type. + +The harness lives in [`src/jsonbench`](../src/jsonbench). + +## Data + +`data-gen` downloads the gzipped NDJSON source files and parses them into Parquet files with a +[Parquet Variant](https://github.com/apache/parquet-format/blob/master/VariantEncoding.md) +column. The Vortex files are converted from that Parquet, like every other suite, and hold the +column as a Vortex `Variant` in the Parquet Variant encoding. + +Two options select the dataset: + +- `--opt scale-factor=N`: the number of source files, each one million events. The default + is 1, and JSONBench's own sizes are 1, 10, 100, and 1000. +- `--opt shredding=none|partial|query-fields|inferred`: which fields are + [shredded](https://github.com/apache/parquet-format/blob/master/VariantShredding.md) into + typed columns. Fields that are not shredded stay in the binary Variant value. + +| Shredding | Typed fields | +| --- | --- | +| `none` | None | +| `partial` | `kind`, `did`, `time_us` | +| `query-fields` | The above plus `commit.collection`, `commit.operation` | +| `inferred` (default) | None in the Parquet file. The Vortex writer shreds what the documents have in common | + +Every option value has its own data directory, `data/jsonbench/m-`. The source +files are shared, in `data/jsonbench/json`. + +## Queries + +Variant access has no SQL syntax that both engines accept, so each engine has its own file in +[`jsonbench/`](./jsonbench). The queries are numbered from Q0 in file order, and return the +same rows on both engines. + +- [`datafusion.sql`](./jsonbench/datafusion.sql) calls `try_variant_get(data, '$.path', type)`. This + is the signature of [datafusion-variant](https://github.com/datafusion-contrib/datafusion-variant), + which has no release for the DataFusion and Arrow versions Vortex builds against. Until it + does, `datafusion-bench` registers its own function with that signature, on the same + `parquet-variant-compute` kernel. +- [`duckdb.sql`](./jsonbench/duckdb.sql) uses DuckDB's native `VARIANT` type, with field + access as `data.commit.collection::VARCHAR`. + +## Engines and formats + +| Engine | Parquet | Vortex | Vortex Compact | DuckDB | +| --- | --- | --- | --- | --- | +| DataFusion | yes | yes | yes | | +| DuckDB | yes | no | no | yes | + +DuckDB cannot read the Vortex files yet: the Vortex DuckDB extension has no export from a +Vortex Variant to a DuckDB `VARIANT`. The `duckdb` format needs a `duckdb` CLI with the +`VARIANT` type (1.5 or later) on `PATH`. + +## Performance + +DataFusion hoists each `try_variant_get` call into a projection above the scan, and the Vortex +scan absorbs it: `vortex-datafusion` converts the call to the Vortex `variant_get` +expression, in projections and in filters. Parquet has no such pushdown, so DataFusion reads +the whole Variant column and extracts from it. + +A shredded Variant is written as a struct layout of its core storage and its shredded child. +The struct is written like any other, so each shredded field is a column of its own, with its +own encoding and statistics. The struct layout reads the Variant as the pack of its columns, +so a scan that extracts a shredded path reads that column and nothing else: Q0 on +`query-fields` reads 0.5 MB of the 126 MB file, as dictionary codes over 15 strings. The +format, `vortex.variant`, is unstable. This suite enables it through an edition of its own, +and other writers do not use it. + +An unshredded Variant value is an opaque binary blob that the lightweight encodings cannot +compress. The default Vortex preset therefore compresses the binary storage of a Variant with +zstd, as Vortex Compact does, which keeps the unshredded file level with zstd Parquet. + +With `inferred`, the Parquet file is the unshredded one, and the Vortex writer chooses what +to shred. It samples the first chunk of the column, and shreds every object field, up to four +objects deep, that holds values of one type in each sampled row that has it: strings, +booleans, integers or doubles. A value moves into a typed column only if it has the type of +the column, and a row that does not fit keeps its value in the binary Variant, so the file +holds the same documents. Here that shreds every field the queries read, `time_us` as a +64-bit integer, without being told which. + +**Note**: the `inferred` results below were measured with the Arrow shredder of +`parquet-variant-compute` 59, which casts a value into a typed column when the cast succeeds. +The writer now shreds by exact type. They need to be measured again. + +Query time of Vortex relative to Parquet, on one million rows with DataFusion on four cores +and the V2 scan (lower is better): + +| Shredding | Q0 | Q1 | Q2 | Q3 | Q4 | Vortex file | Parquet file | +| --- | --- | --- | --- | --- | --- | --- | --- | +| `none` | 0.51 | 0.42 | 0.29 | 0.30 | 0.30 | 126.5 MB | 128.6 MB | +| `query-fields` | 0.08 | 0.25 | 0.13 | 0.10 | 0.10 | 126.6 MB | 118.6 MB | +| `inferred` | 0.05 | 0.10 | 0.04 | 0.03 | 0.02 | 164.6 MB | 128.6 MB | + +In absolute terms, the `inferred` Vortex file answers the five queries in 13, 68, 30, 21 and +21 ms, where the `none` Vortex file takes 173, 304, 255, 223 and 230 ms. + +The ratio holds as the dataset grows. With `inferred`, Vortex time relative to Parquet: + +| Rows | Q0 | Q1 | Q2 | Q3 | Q4 | Vortex file | Parquet file | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 1 million | 0.05 | 0.10 | 0.04 | 0.03 | 0.02 | 165 MB | 129 MB | +| 5 million | 0.03 | 0.08 | 0.03 | 0.01 | 0.02 | 782 MB | 614 MB | +| 20 million | 0.03 | 0.10 | 0.03 | 0.02 | 0.02 | 3.1 GB | 2.4 GB | + +The `inferred` file is larger because the default preset has no zstd for the shredded string +columns, which hold content hashes and record keys that the lightweight encodings barely +compress. Vortex Compact writes the same shredding in 134.4 MB, and answers the queries in 14, +70, 37, 33 and 30 ms. + +The suite runs on the V2 scan, which `vx-bench` selects for it. `datafusion-bench` defaults +to the V1 scan, so pass `--scan-v1 false` when running it directly. + +On `none`, a split decodes the storage of a Variant once, however many filters and +projections extract from it, and a string or an integer under object fields is read from the +encoded bytes in place: the names of the path are resolved against each distinct metadata +once, and every object is then scanned for a field id. Parquet goes through the `variant_get` +kernel of `parquet-variant-compute`, which builds a `Variant` over every row and every object +on the way down. About four fifths of the CPU time Vortex still spends on `none` is zstd +decompression of the values, which is what an unshredded Variant costs to read. Shredding is +the way past it, which is what `inferred` does. + +What is left: + +1. **Shredding on write is this suite's default, not the writer's.** `inferred` enables it + through the suite's unstable edition. The schema comes from the first chunk alone, and the + shredding runs on the writer's thread. +2. **Extractions the in-place reader does not cover.** A path through a list, a value that + needs a cast, and a target other than a string or a 64-bit integer go through the general + kernel, at Parquet's speed. +3. **Shredded paths the scan cannot prove complete.** The scan reads a shredded column alone + only when the writer recorded that no row left a value for it in the core storage. Where + some row did, as for a field that holds strings in some rows and numbers in others, the + scan reads the core storage as well. + +## Running locally + +```bash +vx-bench run jsonbench --engine datafusion --format parquet,vortex,vortex-compact +vx-bench run jsonbench --engine datafusion --format parquet,vortex --opt shredding=query-fields +vx-bench run jsonbench --engine datafusion --format parquet,vortex --opt shredding=none +vx-bench run jsonbench --engine duckdb --format parquet,duckdb +``` diff --git a/vortex-bench/sql/jsonbench/datafusion.sql b/vortex-bench/sql/jsonbench/datafusion.sql new file mode 100644 index 00000000000..3ddcd897d90 --- /dev/null +++ b/vortex-bench/sql/jsonbench/datafusion.sql @@ -0,0 +1,54 @@ +-- Q0: events per collection. +SELECT try_variant_get(data, '$.commit.collection', 'VARCHAR') AS event, + COUNT(*) AS count +FROM bluesky +GROUP BY event +ORDER BY count DESC, event ASC NULLS FIRST; + +-- Q1: events and distinct users per collection, for created commits. +SELECT try_variant_get(data, '$.commit.collection', 'VARCHAR') AS event, + COUNT(*) AS count, + COUNT(DISTINCT try_variant_get(data, '$.did', 'VARCHAR')) AS users +FROM bluesky +WHERE try_variant_get(data, '$.kind', 'VARCHAR') = 'commit' + AND try_variant_get(data, '$.commit.operation', 'VARCHAR') = 'create' +GROUP BY event +ORDER BY count DESC, event ASC NULLS FIRST; + +-- Q2: posts, reposts and likes per hour of the day. +SELECT try_variant_get(data, '$.commit.collection', 'VARCHAR') AS event, + EXTRACT(HOUR FROM to_timestamp_micros(try_variant_get(data, '$.time_us', 'BIGINT'))) AS hour_of_day, + COUNT(*) AS count +FROM bluesky +WHERE try_variant_get(data, '$.kind', 'VARCHAR') = 'commit' + AND try_variant_get(data, '$.commit.operation', 'VARCHAR') = 'create' + AND try_variant_get(data, '$.commit.collection', 'VARCHAR') IN ( + 'app.bsky.feed.post', 'app.bsky.feed.repost', 'app.bsky.feed.like' + ) +GROUP BY event, hour_of_day +ORDER BY hour_of_day ASC NULLS FIRST, event; + +-- Q3: the three users who posted first. +SELECT try_variant_get(data, '$.did', 'VARCHAR') AS user_id, + MIN(to_timestamp_micros(try_variant_get(data, '$.time_us', 'BIGINT'))) AS first_post_ts +FROM bluesky +WHERE try_variant_get(data, '$.kind', 'VARCHAR') = 'commit' + AND try_variant_get(data, '$.commit.operation', 'VARCHAR') = 'create' + AND try_variant_get(data, '$.commit.collection', 'VARCHAR') = 'app.bsky.feed.post' +GROUP BY user_id +ORDER BY first_post_ts ASC NULLS LAST, user_id ASC NULLS FIRST +LIMIT 3; + +-- Q4: the three users with the longest span between their first and last post, in milliseconds. +-- Each endpoint is divided before subtracting, to count millisecond boundaries as ClickHouse's +-- dateDiff does. +SELECT try_variant_get(data, '$.did', 'VARCHAR') AS user_id, + MAX(try_variant_get(data, '$.time_us', 'BIGINT')) / 1000 + - MIN(try_variant_get(data, '$.time_us', 'BIGINT')) / 1000 AS activity_span +FROM bluesky +WHERE try_variant_get(data, '$.kind', 'VARCHAR') = 'commit' + AND try_variant_get(data, '$.commit.operation', 'VARCHAR') = 'create' + AND try_variant_get(data, '$.commit.collection', 'VARCHAR') = 'app.bsky.feed.post' +GROUP BY user_id +ORDER BY activity_span DESC NULLS LAST, user_id ASC NULLS FIRST +LIMIT 3; diff --git a/vortex-bench/sql/jsonbench/duckdb.sql b/vortex-bench/sql/jsonbench/duckdb.sql new file mode 100644 index 00000000000..6403a73ff25 --- /dev/null +++ b/vortex-bench/sql/jsonbench/duckdb.sql @@ -0,0 +1,53 @@ +-- Q0: events per collection. +SELECT data.commit.collection::VARCHAR AS event, + COUNT(*) AS count +FROM bluesky +GROUP BY event +ORDER BY count DESC, event ASC NULLS FIRST; + +-- Q1: events and distinct users per collection, for created commits. +SELECT data.commit.collection::VARCHAR AS event, + COUNT(*) AS count, + COUNT(DISTINCT data.did::VARCHAR) AS users +FROM bluesky +WHERE data.kind::VARCHAR = 'commit' + AND data.commit.operation::VARCHAR = 'create' +GROUP BY event +ORDER BY count DESC, event ASC NULLS FIRST; + +-- Q2: posts, reposts and likes per hour of the day. +SELECT data.commit.collection::VARCHAR AS event, + EXTRACT(HOUR FROM make_timestamp(data.time_us::BIGINT)) AS hour_of_day, + COUNT(*) AS count +FROM bluesky +WHERE data.kind::VARCHAR = 'commit' + AND data.commit.operation::VARCHAR = 'create' + AND data.commit.collection::VARCHAR IN ( + 'app.bsky.feed.post', 'app.bsky.feed.repost', 'app.bsky.feed.like' + ) +GROUP BY event, hour_of_day +ORDER BY hour_of_day ASC NULLS FIRST, event; + +-- Q3: the three users who posted first. +SELECT data.did::VARCHAR AS user_id, + MIN(make_timestamp(data.time_us::BIGINT)) AS first_post_ts +FROM bluesky +WHERE data.kind::VARCHAR = 'commit' + AND data.commit.operation::VARCHAR = 'create' + AND data.commit.collection::VARCHAR = 'app.bsky.feed.post' +GROUP BY user_id +ORDER BY first_post_ts ASC NULLS LAST, user_id ASC NULLS FIRST +LIMIT 3; + +-- Q4: the three users with the longest span between their first and last post, in milliseconds. +-- Each endpoint is divided before subtracting, to count millisecond boundaries as ClickHouse's +-- dateDiff does. +SELECT data.did::VARCHAR AS user_id, + MAX(data.time_us::BIGINT) // 1000 - MIN(data.time_us::BIGINT) // 1000 AS activity_span +FROM bluesky +WHERE data.kind::VARCHAR = 'commit' + AND data.commit.operation::VARCHAR = 'create' + AND data.commit.collection::VARCHAR = 'app.bsky.feed.post' +GROUP BY user_id +ORDER BY activity_span DESC NULLS LAST, user_id ASC NULLS FIRST +LIMIT 3; diff --git a/vortex-bench/src/benchmark.rs b/vortex-bench/src/benchmark.rs index 47de30a5faf..451e462ec80 100644 --- a/vortex-bench/src/benchmark.rs +++ b/vortex-bench/src/benchmark.rs @@ -35,6 +35,12 @@ pub trait Benchmark: Send + Sync { /// Get all available queries for this benchmark fn queries(&self) -> anyhow::Result>; + /// The queries in `engine`'s SQL dialect, for benchmarks whose SQL is not portable across + /// engines. Default: [`Benchmark::queries`]. + fn queries_for_engine(&self, _engine: Engine) -> anyhow::Result> { + self.queries() + } + /// SQL an `engine` must run before this benchmark's queries (e.g. loading engine /// extensions). Runners replay these after every (re)open. Default: none. fn engine_init_sql(&self, _engine: Engine) -> Vec { diff --git a/vortex-bench/src/conversions.rs b/vortex-bench/src/conversions.rs index 6ab0e956be8..d97e2b2d6aa 100644 --- a/vortex-bench/src/conversions.rs +++ b/vortex-bench/src/conversions.rs @@ -52,7 +52,6 @@ use vortex::error::VortexResult; use vortex::error::vortex_err; use vortex::file::VortexWriteOptions; use vortex::file::WriteOptionsSessionExt; -use vortex::file::WriteStrategyBuilder; use vortex::layout::LayoutStrategy; use vortex::layout::layouts::chunked::writer::ChunkedLayoutStrategy; use vortex::layout::layouts::compressed::CompressingStrategy; @@ -76,6 +75,7 @@ use crate::utils::parquet::LOCAL_ROW_GROUP_ROWS; use crate::utils::parquet::has_current_layout; use crate::utils::parquet::is_zstd; use crate::utils::parquet::parquet_writer_properties; +use crate::write_strategy_builder; /// Memory budget per concurrent conversion stream in GB. This is somewhat arbitary. const MEMORY_PER_STREAM_GB: u64 = 4; @@ -324,7 +324,7 @@ fn write_options_for( return compaction.apply_options(SESSION.write_options()); } - let mut builder = WriteStrategyBuilder::from_session(&SESSION); + let mut builder = write_strategy_builder(); if matches!(compaction, CompactionStrategy::Compact) { builder = builder.with_btrblocks_builder( BtrBlocksCompressorBuilder::from_session(&SESSION).with_compact(), diff --git a/vortex-bench/src/datasets/mod.rs b/vortex-bench/src/datasets/mod.rs index ad844e231e9..4b76f0b1967 100644 --- a/vortex-bench/src/datasets/mod.rs +++ b/vortex-bench/src/datasets/mod.rs @@ -12,6 +12,7 @@ use vortex::array::ExecutionCtx; use vortex::error::vortex_panic; use crate::clickbench::Flavor; +use crate::jsonbench::Shredding; use crate::tpch_nested::Shape; pub mod data_downloads; @@ -94,6 +95,8 @@ pub enum BenchmarkDataset { GhArchive, #[serde(rename = "job")] Job, + #[serde(rename = "jsonbench")] + JsonBench { n_rows: usize, shredding: Shredding }, #[serde(rename = "vortex")] VortexQueries, } @@ -114,6 +117,7 @@ impl BenchmarkDataset { BenchmarkDataset::Fineweb => "fineweb", BenchmarkDataset::GhArchive => "gharchive", BenchmarkDataset::Job => "job", + BenchmarkDataset::JsonBench { .. } => "jsonbench", BenchmarkDataset::VortexQueries => "vortex", } } @@ -148,6 +152,9 @@ impl Display for BenchmarkDataset { BenchmarkDataset::Fineweb => write!(f, "fineweb"), BenchmarkDataset::GhArchive => write!(f, "gharchive"), BenchmarkDataset::Job => write!(f, "job"), + BenchmarkDataset::JsonBench { n_rows, shredding } => { + write!(f, "jsonbench(n_rows={n_rows}, shredding={shredding})") + } BenchmarkDataset::VortexQueries => write!(f, "vortex"), } } @@ -209,6 +216,7 @@ impl BenchmarkDataset { BenchmarkDataset::Fineweb => &["fineweb"], BenchmarkDataset::GhArchive => &["events"], BenchmarkDataset::Job => crate::job::TABLES, + BenchmarkDataset::JsonBench { .. } => &["bluesky"], // See VortexBenchmark::table_specs BenchmarkDataset::VortexQueries => &[], } diff --git a/vortex-bench/src/jsonbench/data.rs b/vortex-bench/src/jsonbench/data.rs new file mode 100644 index 00000000000..f24e166af03 --- /dev/null +++ b/vortex-bench/src/jsonbench/data.rs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Converts JSONBench's gzipped NDJSON source files to Parquet files with a Variant column. + +use std::fs::File; +use std::io::BufRead; +use std::io::BufReader; +use std::path::Path; +use std::sync::Arc; + +use arrow_array::ArrayRef; +use arrow_array::RecordBatch; +use arrow_array::StringArray; +use arrow_schema::DataType; +use arrow_schema::Schema; +use flate2::read::MultiGzDecoder; +use parquet::arrow::ArrowWriter; +use parquet_variant_compute::json_to_variant; +use parquet_variant_compute::shred_variant; +use serde::de::IgnoredAny; +use tracing::warn; + +use crate::utils::parquet::parquet_writer_properties; + +/// Documents parsed and shredded together. Each batch becomes one Parquet row group. +const ROWS_PER_BATCH: usize = 65_536; + +/// Name of the table's only column. +const COLUMN: &str = "data"; + +/// Converts the gzipped NDJSON file `json_gz` into a Parquet file at `parquet_path` with one +/// Variant column, shredded as `shredding` when given. +/// +/// Lines that are not valid JSON are skipped with a warning, as JSONBench's own loaders do. +pub(super) fn convert_json_to_parquet( + json_gz: &Path, + parquet_path: &Path, + shredding: Option<&DataType>, +) -> anyhow::Result<()> { + let reader = BufReader::new(MultiGzDecoder::new(File::open(json_gz)?)); + let mut writer: Option> = None; + let mut skipped = 0usize; + + let mut lines = Vec::with_capacity(ROWS_PER_BATCH); + let mut flush = |lines: &mut Vec| -> anyhow::Result<()> { + let batch = variant_batch(lines, shredding, &mut skipped)?; + lines.clear(); + let writer = match writer.as_mut() { + Some(writer) => writer, + None => { + let properties = parquet_writer_properties() + .set_max_row_group_row_count(Some(ROWS_PER_BATCH)) + .build(); + writer.insert(ArrowWriter::try_new( + File::create(parquet_path)?, + batch.schema(), + Some(properties), + )?) + } + }; + writer.write(&batch)?; + Ok(()) + }; + + for line in reader.lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + lines.push(line); + if lines.len() == ROWS_PER_BATCH { + flush(&mut lines)?; + } + } + if !lines.is_empty() { + flush(&mut lines)?; + } + + if skipped > 0 { + warn!( + "Skipped {skipped} invalid JSON documents in {}", + json_gz.display() + ); + } + writer + .ok_or_else(|| anyhow::anyhow!("{} holds no JSON documents", json_gz.display()))? + .close()?; + Ok(()) +} + +/// Parses `lines` into a single-column batch of Variant values. +fn variant_batch( + lines: &[String], + shredding: Option<&DataType>, + skipped: &mut usize, +) -> anyhow::Result { + let to_strings = |lines: &mut dyn Iterator| { + Arc::new(StringArray::from_iter_values(lines)) as ArrayRef + }; + + let strings = to_strings(&mut lines.iter().map(String::as_str)); + let variant = match json_to_variant(&strings) { + Ok(variant) => variant, + // One invalid document fails the whole batch, so drop the invalid ones and retry. + Err(_) => { + let is_json = |line: &&str| serde_json::from_str::(line).is_ok(); + let valid = to_strings(&mut lines.iter().map(String::as_str).filter(is_json)); + *skipped += lines.len() - valid.len(); + json_to_variant(&valid)? + } + }; + let variant = match shredding { + Some(shredding) => shred_variant(&variant, shredding)?, + None => variant, + }; + + let schema = Arc::new(Schema::new(vec![variant.field(COLUMN)])); + Ok(RecordBatch::try_new( + schema, + vec![Arc::new(variant.into_inner())], + )?) +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use arrow_array::cast::AsArray; + use arrow_schema::Field; + use flate2::Compression; + use flate2::write::GzEncoder; + use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; + use parquet_variant::VariantPath; + use parquet_variant_compute::GetOptions; + use parquet_variant_compute::variant_get; + use rstest::rstest; + + use super::*; + use crate::jsonbench::Shredding; + + #[rstest] + #[case::unshredded(Shredding::None)] + #[case::partial(Shredding::Partial)] + #[case::query_fields(Shredding::QueryFields)] + #[case::inferred(Shredding::Inferred)] + fn converts_ndjson_to_variant_parquet(#[case] shredding: Shredding) -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let json_gz = dir.path().join("events.json.gz"); + let parquet_path = dir.path().join("events.parquet"); + + let mut encoder = GzEncoder::new(File::create(&json_gz)?, Compression::default()); + encoder.write_all( + concat!( + r#"{"did":"a","kind":"commit","commit":{"collection":"post","operation":"create"}}"#, + "\n", + "not json\n", + "\n", + r#"{"did":"b","kind":"identity"}"#, + "\n", + ) + .as_bytes(), + )?; + encoder.finish()?; + + convert_json_to_parquet(&json_gz, &parquet_path, shredding.schema()?.as_ref())?; + + let reader = ParquetRecordBatchReaderBuilder::try_new(File::open(&parquet_path)?)?; + assert_eq!( + reader.schema().field(0).extension_type_name(), + Some("arrow.parquet.variant") + ); + let batches = reader.build()?.collect::, _>>()?; + assert_eq!(batches.len(), 1); + + // The invalid and empty lines are dropped, and shredding does not change the values. + let collection = variant_get( + batches[0].column(0), + GetOptions::new_with_path(VariantPath::try_from("commit.collection")?) + .with_as_type(Some(Arc::new(Field::new("", DataType::Utf8, true)))), + )?; + let collection = collection.as_string::().iter().collect::>(); + assert_eq!(collection, vec![Some("post"), None]); + Ok(()) + } +} diff --git a/vortex-bench/src/jsonbench/mod.rs b/vortex-bench/src/jsonbench/mod.rs new file mode 100644 index 00000000000..4d821b03107 --- /dev/null +++ b/vortex-bench/src/jsonbench/mod.rs @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [JSONBench](https://github.com/ClickHouse/JSONBench): analytics over semi-structured Bluesky +//! events, stored in a single Variant column. + +mod data; + +use std::fmt::Display; +use std::fs; +use std::path::PathBuf; +use std::str::FromStr; + +use arrow_schema::DataType; +use futures::StreamExt; +use futures::TryStreamExt; +use parquet_variant_compute::ShreddedSchemaBuilder; +use serde::Deserialize; +use serde::Serialize; +use tracing::info; +use url::Url; +use vortex::utils::parallelism::get_available_parallelism; + +use crate::Benchmark; +use crate::BenchmarkDataset; +use crate::Engine; +use crate::TableSpec; +use crate::data_dir; +use crate::datasets::data_downloads::download_many; +use crate::idempotent; +use crate::utils::file::resolve_data_url; +use crate::workspace_root; + +/// Each source file holds this many Bluesky events. +const ROWS_PER_FILE: usize = 1_000_000; + +/// JSONBench publishes 1,000 source files (one billion events). +const MAX_FILES: usize = 1000; + +/// URL of the `number`th (1-based) gzipped NDJSON source file. +fn source_url(number: usize) -> String { + format!("https://clickhouse-public-datasets.s3.amazonaws.com/bluesky/file_{number:04}.json.gz") +} + +/// Which fields of the Variant column are shredded into typed columns. +/// +/// Fields that are not shredded stay readable through the residual Variant value. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Shredding { + /// No shredding: every document is a single binary Variant value. + None, + /// The top-level `kind`, `did`, and `time_us` fields. + Partial, + /// Every field the queries read: `partial` plus `commit.collection` and `commit.operation`. + QueryFields, + /// Nothing is shredded in the Parquet file. The Vortex writer shreds the fields that it + /// finds the documents to have in common. + #[default] + Inferred, +} + +impl Shredding { + pub fn name(&self) -> &'static str { + match self { + Shredding::None => "none", + Shredding::Partial => "partial", + Shredding::QueryFields => "query-fields", + Shredding::Inferred => "inferred", + } + } + + /// The shredding schema of the Parquet file, or `None` when nothing is shredded in it. + fn schema(&self) -> anyhow::Result> { + if matches!(self, Shredding::None | Shredding::Inferred) { + return Ok(None); + } + let mut builder = ShreddedSchemaBuilder::new() + .with_path("kind", &DataType::Utf8)? + .with_path("did", &DataType::Utf8)? + .with_path("time_us", &DataType::Int64)?; + if *self == Shredding::QueryFields { + builder = builder + .with_path("commit.collection", &DataType::Utf8)? + .with_path("commit.operation", &DataType::Utf8)?; + } + Ok(Some(builder.build())) + } +} + +impl FromStr for Shredding { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s { + "none" => Ok(Shredding::None), + "partial" => Ok(Shredding::Partial), + "query-fields" => Ok(Shredding::QueryFields), + "inferred" => Ok(Shredding::Inferred), + _ => anyhow::bail!( + "Failed to parse {s}, valid shredding values are `none`, `partial`, \ + `query-fields`, and `inferred`" + ), + } + } +} + +impl Display for Shredding { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.name()) + } +} + +/// JSONBench over a single `bluesky` table whose only column, `data`, is a Variant. +pub struct JsonBenchBenchmark { + data_url: Url, + /// How many million-row source files the dataset holds. + files: usize, + shredding: Shredding, +} + +impl JsonBenchBenchmark { + /// Creates the benchmark over `files` million-row source files. + pub fn new( + files: usize, + shredding: Shredding, + remote_data_dir: Option, + ) -> anyhow::Result { + anyhow::ensure!( + (1..=MAX_FILES).contains(&files), + "jsonbench scale factor must be between 1 and {MAX_FILES} (millions of rows), got \ + {files}" + ); + let data_url = resolve_data_url( + remote_data_dir.as_deref(), + &format!("jsonbench/{files}m-{shredding}"), + )?; + Ok(Self { + data_url, + files, + shredding, + }) + } + + /// Where the `number`th source file is cached. All shredding layouts share the downloads. + fn source_path(number: usize) -> PathBuf { + data_dir() + .join("jsonbench") + .join("json") + .join(format!("file_{number:04}.json.gz")) + } + + fn parquet_path(&self, number: usize) -> anyhow::Result { + self.data_url + .join("parquet/")? + .join(&format!("bluesky_{number:04}.parquet"))? + .to_file_path() + .map_err(|_| anyhow::anyhow!("failed to convert data URL to filesystem path")) + } + + /// Loads `sql/jsonbench/.sql`, numbering its statements from Q0 in file order. + fn load_queries(engine_name: &str) -> anyhow::Result> { + // `;`-separated; a `;` must not appear in a comment, or it would split a statement in two. + let queries_file = workspace_root() + .join("vortex-bench") + .join("sql") + .join("jsonbench") + .join(engine_name) + .with_extension("sql"); + let contents = fs::read_to_string(queries_file)?; + Ok(contents + .split_terminator(';') + .map(str::trim) + .filter(|stmt| !stmt.is_empty()) + .map(str::to_string) + .enumerate() + .collect()) + } +} + +#[async_trait::async_trait] +impl Benchmark for JsonBenchBenchmark { + fn doc_path(&self) -> &'static str { + "vortex-bench/sql/jsonbench.md" + } + + /// The five JSONBench queries in DataFusion's dialect. + fn queries(&self) -> anyhow::Result> { + self.queries_for_engine(Engine::DataFusion) + } + + /// Variant access has no common SQL syntax, so each engine has its own query file. + fn queries_for_engine(&self, engine: Engine) -> anyhow::Result> { + match engine { + Engine::DataFusion => Self::load_queries("datafusion"), + Engine::DuckDB => Self::load_queries("duckdb"), + Engine::Vortex => anyhow::bail!("jsonbench has no queries for the {engine} engine"), + } + } + + async fn generate_base_data(&self) -> anyhow::Result<()> { + if self.data_url.scheme() != "file" { + return Ok(()); + } + + let missing = (1..=self.files) + .map(|number| Ok((number, self.parquet_path(number)?))) + .filter(|entry| !matches!(entry, Ok((_, path)) if path.exists())) + .collect::>>()?; + if missing.is_empty() { + return Ok(()); + } + + info!("Downloading {} JSONBench source files", missing.len()); + download_many( + missing + .iter() + .map(|(number, _)| (Self::source_path(*number), source_url(*number))), + ) + .await?; + + let shredding = self.shredding.schema()?; + // Parsing JSON is CPU bound, so convert one source file per core. + let concurrency = get_available_parallelism().unwrap_or(1); + futures::stream::iter(missing) + .map(|(number, parquet_path)| { + let shredding = shredding.clone(); + tokio::task::spawn_blocking(move || { + idempotent(&parquet_path, |tmp_path| { + info!("Converting JSONBench file {number} to Parquet Variant"); + data::convert_json_to_parquet( + &Self::source_path(number), + tmp_path, + shredding.as_ref(), + ) + }) + }) + }) + .buffer_unordered(concurrency) + .map(|joined| joined?) + .try_collect::>() + .await?; + + Ok(()) + } + + fn expected_row_counts(&self) -> Option> { + // Only the first source file has known counts: more files add collections. + (self.files == 1).then(|| vec![15, 13, 3, 3, 3]) + } + + fn dataset(&self) -> BenchmarkDataset { + BenchmarkDataset::JsonBench { + n_rows: self.files * ROWS_PER_FILE, + shredding: self.shredding, + } + } + + fn dataset_name(&self) -> &str { + "jsonbench" + } + + fn dataset_display(&self) -> String { + format!("jsonbench(sf={}, shredding={})", self.files, self.shredding) + } + + fn data_url(&self) -> &Url { + &self.data_url + } + + fn table_specs(&self) -> Vec { + vec![TableSpec::new("bluesky", None)] + } +} diff --git a/vortex-bench/src/lib.rs b/vortex-bench/src/lib.rs index e0da88ffb8e..f7f376cdacf 100644 --- a/vortex-bench/src/lib.rs +++ b/vortex-bench/src/lib.rs @@ -7,7 +7,10 @@ use std::clone::Clone; use std::fmt::Display; use std::str::FromStr; +use std::sync::Arc; use std::sync::LazyLock; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; use anyhow::bail; use appian::AppianBenchmark; @@ -19,6 +22,8 @@ use clickbench::Flavor; use fineweb::FinewebBenchmark; use itertools::Itertools; use job::JobBenchmark; +use jsonbench::JsonBenchBenchmark; +use jsonbench::Shredding; use polarsignals::PolarSignalsBenchmark; use public_bi::PBIDataset; use public_bi::PublicBiBenchmark; @@ -33,6 +38,7 @@ use tpch_nested::TpcHNestedBenchmark; pub use utils::file::*; pub use utils::logging::*; use vortex::compressor::BtrBlocksCompressorBuilder; +use vortex::encodings::parquet_variant::InferredShredding; use vortex::error::VortexExpect; use vortex::error::vortex_err; use vortex::file::VortexWriteOptions; @@ -52,6 +58,7 @@ pub mod display; pub mod downloadable_dataset; pub mod fineweb; pub mod job; +pub mod jsonbench; pub mod measurements; pub mod memory; pub mod output; @@ -134,6 +141,25 @@ pub fn enable_unstable_encodings(session: &VortexSession) { .vortex_expect("unstable edition is registered"); } +const BENCH_VARIANT_EDITION_FAMILY: EditionFamily = EditionFamily { + name: "bench-variant", + origin: "vortex-bench", + doc: "The unstable Variant layout, which the V2 scan reads, without the list layout, which \ +it cannot.", +}; + +/// The Variant layout from the unstable edition, on its own. +const UNSTABLE_BENCH_VARIANT: EditionId = EditionId::new("bench-variant", 2026, 11, 0); + +static UNSTABLE_BENCH_VARIANT_DECLARATION: EditionDeclaration = EditionDeclaration { + edition: Edition { + id: UNSTABLE_BENCH_VARIANT, + immutable: false, + min_library_version: None, + }, + added: &[EditionMember::layout(&"vortex.variant")], +}; + pub static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::default().with_tokio(); vortex_spatial::initialize(&session); @@ -146,6 +172,13 @@ pub static SESSION: LazyLock = LazyLock::new(|| { .vortex_expect("bench edition declaration is valid"); enable_unstable_encodings(&session); session + .editions() + .declare_family(&BENCH_VARIANT_EDITION_FAMILY) + .vortex_expect("bench Variant edition family is valid"); + session + .register_edition(&UNSTABLE_BENCH_VARIANT_DECLARATION) + .vortex_expect("bench Variant edition declaration is valid"); + session }); /// Enables [`UNSTABLE_BENCH`] on [`SESSION`], so it writes lists with the list layout. @@ -157,6 +190,35 @@ fn enable_unstable_bench_edition() { .vortex_expect("bench edition is registered"); } +/// Enables [`UNSTABLE_BENCH_VARIANT`] on [`SESSION`], so it writes a shredded Variant with the +/// Variant layout: a column for its core storage and one for each shredded field. +fn enable_unstable_bench_variant_edition() { + SESSION + .enable_edition(UNSTABLE_BENCH_VARIANT) + .vortex_expect("bench Variant edition is registered"); +} + +/// Whether [`write_strategy_builder`] shreds the Variants that are not shredded. +static SHRED_VARIANTS_ON_WRITE: AtomicBool = AtomicBool::new(false); + +/// Makes the Vortex writer shred an unshredded Variant by a schema it infers from the values. +fn enable_variant_shredding_on_write() { + SHRED_VARIANTS_ON_WRITE.store(true, Ordering::Relaxed); +} + +fn shreds_variants_on_write() -> bool { + SHRED_VARIANTS_ON_WRITE.load(Ordering::Relaxed) +} + +/// The write strategy of [`SESSION`], with what the benchmark being run has enabled. +pub fn write_strategy_builder() -> WriteStrategyBuilder { + let builder = WriteStrategyBuilder::from_session(&SESSION); + if !shreds_variants_on_write() { + return builder; + } + builder.with_variant_shredding(Arc::new(InferredShredding::default())) +} + #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)] pub struct Target { pub engine: Engine, @@ -331,12 +393,15 @@ impl CompactionStrategy { pub fn apply_options(&self, options: VortexWriteOptions) -> VortexWriteOptions { match self { CompactionStrategy::Compact => options.with_strategy( - WriteStrategyBuilder::from_session(&SESSION) + write_strategy_builder() .with_btrblocks_builder( BtrBlocksCompressorBuilder::from_session(&SESSION).with_compact(), ) .build(), ), + CompactionStrategy::Default if shreds_variants_on_write() => { + options.with_strategy(write_strategy_builder().build()) + } CompactionStrategy::Default => options, } } @@ -425,6 +490,8 @@ pub enum BenchmarkArg { GhArchive, #[clap(name = "job")] Job, + #[clap(name = "jsonbench")] + JsonBench, #[clap(name = "polarsignals")] PolarSignals, #[clap(name = "public-bi")] @@ -518,6 +585,17 @@ pub fn create_benchmark(b: BenchmarkArg, opts: &Opts) -> anyhow::Result { + enable_unstable_bench_variant_edition(); + let files = opts.get_as::(SCALE_FACTOR_KEY).unwrap_or(1); + let shredding = opts.get_as::("shredding").unwrap_or_default(); + if shredding == Shredding::Inferred { + enable_variant_shredding_on_write(); + } + let remote_data_dir = opts.get_as::(REMOTE_DATA_KEY); + let benchmark = JsonBenchBenchmark::new(files, shredding, remote_data_dir)?; + Ok(Box::new(benchmark) as _) + } BenchmarkArg::PolarSignals => { enable_unstable_bench_edition(); let scale_factor = opts.get_as::(SCALE_FACTOR_KEY).unwrap_or(1); diff --git a/vortex-bench/src/v3.rs b/vortex-bench/src/v3.rs index bc7e5a25a7b..f5a6ed501f8 100644 --- a/vortex-bench/src/v3.rs +++ b/vortex-bench/src/v3.rs @@ -287,6 +287,7 @@ fn canonical_tpc_scale_factor(scale_factor: &str) -> String { /// | `Job` | `job` | `None` | `None` | Static IMDB dataset; no scale factor. | /// | `PublicBi { name }` | `public-bi` | dataset name (e.g. `cms-provider`) | `None` | Sub-dataset name lives in `dataset_variant`. | /// | `SpatialBench { scale_factor }` | `spatialbench` | `None` | SF as string | Same canonicalization as TPC-H; no historical v2 records to merge with. | +/// | `JsonBench { n_rows, shredding }` | `jsonbench` | shredding name (`none`) | millions of rows as string (`"1"`) | New live-only suite. | /// | `VortexQueries` | `vortex` | `None` | `None` | Own microbenchmarks | pub fn benchmark_dataset_dims(d: &BenchmarkDataset) -> (String, Option, Option) { match d { @@ -336,6 +337,11 @@ pub fn benchmark_dataset_dims(d: &BenchmarkDataset) -> (String, Option, BenchmarkDataset::GhArchive => ("gharchive".to_string(), None, None), BenchmarkDataset::Appian => ("appian".to_string(), None, None), BenchmarkDataset::Job => ("job".to_string(), None, None), + BenchmarkDataset::JsonBench { n_rows, shredding } => ( + "jsonbench".to_string(), + Some(shredding.name().to_string()), + Some((n_rows / 1_000_000).to_string()), + ), BenchmarkDataset::VortexQueries => ("vortex".to_string(), None, None), } }