From 0a08bd8e22337909dc4125f78c2f6af2677d09a7 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Mon, 16 Nov 2026 17:43:56 -0600 Subject: [PATCH 1/3] refactor(flow-php/arrow-ext): Parquet Rust code in a crate shared with flow_php - crate flow-parquet-engine, linked into both extensions - flow_php on arrow-* 60 - split, PIE archive and Nix follow the links - CI runs the Parquet adapter suites per extension lane - arrow-ext release build stripped --- .github/scripts/monorepo-split.sh | 2 +- .github/workflows/job-arrow-extension.yml | 12 +- .github/workflows/job-flow-php-extension.yml | 28 +- .github/workflows/test-arrow-extension.yml | 1 + .github/workflows/test-flow-php-extension.yml | 1 + .nix/pkgs/php-arrow-ext/package.nix | 10 +- .nix/pkgs/php-flow-php-ext/package.nix | 10 +- documentation/contributing/rust.md | 41 +- .../Unit/IO/ConfiguredParquetEngineTest.php | 19 + src/extension/arrow-ext/Cargo.lock | 18 +- src/extension/arrow-ext/Cargo.toml | 13 +- src/extension/arrow-ext/build.rs | 23 - .../arrow-ext/crates/flow-parquet-engine | 1 + src/extension/arrow-ext/src/alloc.rs | 57 +++ src/extension/arrow-ext/src/lib.rs | 41 +- src/extension/arrow-ext/src/parquet/mod.rs | 22 - src/extension/flow-php-ext/Cargo.lock | 397 ++++++++++++------ src/extension/flow-php-ext/Cargo.toml | 11 +- .../crates/flow-arrow-c/src/lib.rs | 119 +++--- .../crates/flow-column-kernels/Cargo.toml | 4 +- .../flow-php-ext/crates/flow-parquet-engine | 1 + src/extension/parquet-engine/Cargo.toml | 20 + src/extension/parquet-engine/build.rs | 24 ++ src/extension/parquet-engine/rustfmt.toml | 1 + .../parquet => parquet-engine/src}/batch.rs | 44 +- .../src}/canonical.rs | 6 +- .../parquet => parquet-engine/src}/cells.rs | 2 +- .../parquet => parquet-engine/src}/chunks.rs | 6 +- .../parquet => parquet-engine/src}/engine.rs | 23 +- .../parquet => parquet-engine/src}/error.rs | 0 .../src/exception.rs | 0 .../parquet => parquet-engine/src}/filter.rs | 6 +- .../parquet => parquet-engine/src}/footer.rs | 10 +- .../src/interfaces.rs | 23 + src/extension/parquet-engine/src/lib.rs | 33 ++ .../src}/lib_calls.rs | 0 .../parquet => parquet-engine/src}/library.rs | 114 +++-- .../parquet => parquet-engine/src}/options.rs | 2 +- .../{arrow-ext => parquet-engine}/src/php.rs | 45 +- .../parquet => parquet-engine/src}/read.rs | 118 +++--- .../src/render.rs | 4 +- .../parquet => parquet-engine/src}/sink.rs | 2 +- .../parquet => parquet-engine/src}/source.rs | 2 +- .../src/thrift.rs | 0 .../src/values.rs | 0 .../parquet => parquet-engine/src}/write.rs | 8 +- 46 files changed, 868 insertions(+), 456 deletions(-) create mode 120000 src/extension/arrow-ext/crates/flow-parquet-engine delete mode 100644 src/extension/arrow-ext/src/parquet/mod.rs create mode 120000 src/extension/flow-php-ext/crates/flow-parquet-engine create mode 100644 src/extension/parquet-engine/Cargo.toml create mode 100644 src/extension/parquet-engine/build.rs create mode 100644 src/extension/parquet-engine/rustfmt.toml rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/batch.rs (90%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/canonical.rs (99%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/cells.rs (99%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/chunks.rs (99%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/engine.rs (89%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/error.rs (100%) rename src/extension/{arrow-ext => parquet-engine}/src/exception.rs (100%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/filter.rs (99%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/footer.rs (96%) rename src/extension/{arrow-ext => parquet-engine}/src/interfaces.rs (91%) create mode 100644 src/extension/parquet-engine/src/lib.rs rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/lib_calls.rs (100%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/library.rs (93%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/options.rs (99%) rename src/extension/{arrow-ext => parquet-engine}/src/php.rs (92%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/read.rs (99%) rename src/extension/{arrow-ext => parquet-engine}/src/render.rs (98%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/sink.rs (94%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/source.rs (99%) rename src/extension/{arrow-ext => parquet-engine}/src/thrift.rs (100%) rename src/extension/{arrow-ext => parquet-engine}/src/values.rs (100%) rename src/extension/{arrow-ext/src/parquet => parquet-engine/src}/write.rs (97%) diff --git a/.github/scripts/monorepo-split.sh b/.github/scripts/monorepo-split.sh index f863c60703..22ac19b7d1 100644 --- a/.github/scripts/monorepo-split.sh +++ b/.github/scripts/monorepo-split.sh @@ -27,7 +27,7 @@ while true; do fi find "$build" -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} + - cp -a "${local_path}/." "$build/" + cp -aL "${local_path}/." "$build/" git -C "$build" add --all changes="$(git -C "$build" status --porcelain)" diff --git a/.github/workflows/job-arrow-extension.yml b/.github/workflows/job-arrow-extension.yml index 7802129fc7..99629545cb 100644 --- a/.github/workflows/job-arrow-extension.yml +++ b/.github/workflows/job-arrow-extension.yml @@ -59,12 +59,12 @@ jobs: - name: Test arrow crate working-directory: src/extension/arrow-ext env: *rust-env - run: cargo test --locked --features arrow-validate + run: cargo test --workspace --locked --features arrow-validate - name: Lint arrow crate working-directory: src/extension/arrow-ext env: *rust-env - run: cargo fmt --check && cargo clippy --locked --all-targets -- -D warnings + run: cargo fmt --all --check && cargo clippy --workspace --locked --all-targets -- -D warnings - name: Install Composer Dependencies uses: ./.github/actions/composer-install @@ -90,6 +90,12 @@ jobs: - name: Run Parquet Integration Tests with Arrow run: just test --testsuite=lib-parquet-integration ${{ (matrix.php == '8.3' && runner.os == 'Linux') && '--coverage-clover=./var/phpunit/coverage/clover/coverage.xml' || '' }} + - name: Run Parquet Adapter Unit Tests with Arrow + run: just test --testsuite=adapter-parquet-unit + + - name: Run Parquet Adapter Integration Tests with Arrow + run: just test --testsuite=adapter-parquet-integration + - name: Upload to Codecov if: ${{ !cancelled() && matrix.php == '8.3' && runner.os == 'Linux' }} uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 @@ -137,7 +143,7 @@ jobs: - name: Prepare local package for PIE installation run: | # git archive applies export-subst like GitHub release archives, so the build resolves its version from .git_archival.txt - git archive HEAD src/extension/arrow-ext | tar -x -C "$RUNNER_TEMP" + git archive HEAD src/extension/arrow-ext src/extension/parquet-engine | tar -x -C "$RUNNER_TEMP" cd "$RUNNER_TEMP/src/extension/arrow-ext" jq '. + {"version": "0.0.9999"}' composer.json > composer.tmp.json mv composer.tmp.json composer.json diff --git a/.github/workflows/job-flow-php-extension.yml b/.github/workflows/job-flow-php-extension.yml index b04b22d44f..5063757c8a 100644 --- a/.github/workflows/job-flow-php-extension.yml +++ b/.github/workflows/job-flow-php-extension.yml @@ -72,6 +72,12 @@ jobs: env: *rust-env run: cargo fmt --all --check && cargo clippy --workspace --locked --all-targets -- -D warnings + - name: Check both extensions lock the same flow-parquet-engine dependencies + working-directory: src/extension + run: | + tree() { (cd "$1" && cargo tree --locked -p flow-parquet-engine --prefix none -e normal --target all | sed 's/ (.*)//' | sort -u); } + diff <(tree arrow-ext) <(tree flow-php-ext) + - name: Install Composer Dependencies uses: ./.github/actions/composer-install with: @@ -105,6 +111,26 @@ jobs: - name: Run CSV Adapter Integration Tests with Flow PHP Extension run: just test --testsuite=adapter-csv-integration + - name: Run Parquet Adapter Unit Tests with Flow PHP Extension + run: just test --testsuite=adapter-parquet-unit + + - name: Run Parquet Adapter Integration Tests with Flow PHP Extension + run: just test --testsuite=adapter-parquet-integration + + - name: Install arrow extension next to flow_php + working-directory: src/extension/arrow-ext + run: | + EXT_DIR=$(php -r 'echo ini_get("extension_dir");') + sudo cp ext/modules/arrow.so "$EXT_DIR/" + echo "extension=arrow.so" | sudo tee -a "$(php -r 'echo php_ini_loaded_file();')" + php -m | grep -x arrow + + - name: Run Parquet Adapter Unit Tests with both extensions + run: just test --testsuite=adapter-parquet-unit + + - name: Run Parquet Adapter Integration Tests with both extensions + run: just test --testsuite=adapter-parquet-integration + - name: Upload to Codecov if: ${{ !cancelled() && matrix.php == '8.3' && runner.os == 'Linux' }} uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 @@ -152,7 +178,7 @@ jobs: - name: Prepare local package for PIE installation run: | # git archive applies export-subst like GitHub release archives, so the build resolves its version from .git_archival.txt - git archive HEAD src/extension/flow-php-ext | tar -x -C "$RUNNER_TEMP" + git archive HEAD src/extension/flow-php-ext src/extension/parquet-engine | tar -x -C "$RUNNER_TEMP" cd "$RUNNER_TEMP/src/extension/flow-php-ext" jq '. + {"version": "0.0.9999"}' composer.json > composer.tmp.json mv composer.tmp.json composer.json diff --git a/.github/workflows/test-arrow-extension.yml b/.github/workflows/test-arrow-extension.yml index ffa2d0d1ea..1719fe212c 100644 --- a/.github/workflows/test-arrow-extension.yml +++ b/.github/workflows/test-arrow-extension.yml @@ -4,6 +4,7 @@ on: pull_request: paths: - 'src/extension/arrow-ext/**' + - 'src/extension/parquet-engine/**' - '.github/workflows/test-arrow-extension.yml' - '.github/workflows/job-arrow-extension.yml' - '.github/actions/setup-php-env/**' diff --git a/.github/workflows/test-flow-php-extension.yml b/.github/workflows/test-flow-php-extension.yml index a1f6a03c10..ca2fef3139 100644 --- a/.github/workflows/test-flow-php-extension.yml +++ b/.github/workflows/test-flow-php-extension.yml @@ -6,6 +6,7 @@ on: - 'src/extension/flow-php-ext/**' # the flow-php-ext build and PHPT tests load arrow-ext - 'src/extension/arrow-ext/**' + - 'src/extension/parquet-engine/**' - '.github/workflows/test-flow-php-extension.yml' - '.github/workflows/job-flow-php-extension.yml' - '.github/actions/setup-php-env/**' diff --git a/.nix/pkgs/php-arrow-ext/package.nix b/.nix/pkgs/php-arrow-ext/package.nix index 6825e86ce1..87a2d89d1d 100644 --- a/.nix/pkgs/php-arrow-ext/package.nix +++ b/.nix/pkgs/php-arrow-ext/package.nix @@ -9,12 +9,15 @@ }: let + extensions = ../../../src/extension; extSrc = builtins.path { - path = ../../../src/extension/arrow-ext; + path = extensions; name = "arrow-ext-src"; filter = path: type: - let baseName = baseNameOf path; - in !( + let + baseName = baseNameOf path; + folder = builtins.head (lib.splitString "/" (lib.removePrefix "${toString extensions}/" (toString path))); + in (folder == "arrow-ext" || folder == "parquet-engine") && !( baseName == "target" || baseName == "vendor" || baseName == "ext" || @@ -29,6 +32,7 @@ let version = arrow-ext-version; src = extSrc; + sourceRoot = "arrow-ext-src/arrow-ext"; cargoLock.lockFile = ../../../src/extension/arrow-ext/Cargo.lock; diff --git a/.nix/pkgs/php-flow-php-ext/package.nix b/.nix/pkgs/php-flow-php-ext/package.nix index 2f4e3112f1..5bad206f88 100644 --- a/.nix/pkgs/php-flow-php-ext/package.nix +++ b/.nix/pkgs/php-flow-php-ext/package.nix @@ -9,12 +9,15 @@ }: let + extensions = ../../../src/extension; extSrc = builtins.path { - path = ../../../src/extension/flow-php-ext; + path = extensions; name = "flow-php-ext-src"; filter = path: type: - let baseName = baseNameOf path; - in !( + let + baseName = baseNameOf path; + folder = builtins.head (lib.splitString "/" (lib.removePrefix "${toString extensions}/" (toString path))); + in (folder == "flow-php-ext" || folder == "parquet-engine") && !( baseName == "target" || baseName == "vendor" || baseName == "ext" || @@ -29,6 +32,7 @@ let version = flow-php-ext-version; src = extSrc; + sourceRoot = "flow-php-ext-src/flow-php-ext"; cargoLock.lockFile = ../../../src/extension/flow-php-ext/Cargo.lock; diff --git a/documentation/contributing/rust.md b/documentation/contributing/rust.md index 51bdee6a9f..d75370a7d2 100644 --- a/documentation/contributing/rust.md +++ b/documentation/contributing/rust.md @@ -43,16 +43,11 @@ them set to `true`, the `shell.nix` assertion fails, because a prebuilt extensio src/extension/arrow-ext/ ├── Cargo.toml # Rust dependencies and build config ├── Makefile # Build orchestration +├── build.rs # Extension and library versions +├── crates/flow-parquet-engine -> ../../parquet-engine # The shared Parquet crate, built with feature arrow-names ├── src/ # Rust source code -│ ├── lib.rs # Extension entry point, module registration -│ ├── interfaces.rs # Flow\Parquet\{ParquetEngine, ParquetFileReader, ParquetFileWriter}, registered at MINIT -│ ├── parquet/ # RustParquetEngine, readers, writer, canonical Arrow types, Arrow C Data batches -│ ├── thrift.rs # Footer bytes as the PHP ThriftModel objects -│ ├── render.rs # Parquet refusals as the Flow\Parquet exceptions -│ ├── php.rs # PHP engine helpers (class entries, hashtables, calls) -│ ├── values.rs # PHP values through the engine's C date API -│ ├── alloc.rs # Counting global allocator -│ └── exception.rs # Exception mapping +│ ├── lib.rs # Extension entry point: registers the crate's classes, RINIT/RSHUTDOWN +│ └── alloc.rs # Counting global allocator ├── php/ # PHP stubs for static analysis (used when extension is not loaded) │ └── Flow/ │ ├── Arrow/ @@ -103,6 +98,7 @@ src/extension/flow-php-ext/ │ ├── flow-json-records/ # JSON lines / array framing and member-to-column mapping │ ├── flow-arrow-c/ # Batches across the Arrow C Data Interface, imported bytes counted │ ├── flow-csv-tokenizer/ # CSV records and fields as php_fgetcsv() produces them +│ ├── flow-parquet-engine -> ../../parquet-engine # The shared Parquet crate, built with feature flow-php-names │ └── flow-numeric-string/ # PHP's is_numeric() grammar ├── php/ # PHP stubs for static analysis │ └── Flow/ @@ -110,6 +106,33 @@ src/extension/flow-php-ext/ │ └── phpt/ # PHPT test files └── ext/ └── config.m4 # PIE compatibility + +src/extension/parquet-engine/ # Crate flow-parquet-engine: the Parquet code of both extensions +├── Cargo.toml # Features arrow-names and flow-php-names: the PHP class names, exactly one enabled +├── build.rs # The php84/php85 cfgs +└── src/ + ├── lib.rs # Module declarations + ├── engine.rs # RustParquetEngine + ├── library.rs # Readers, footer, writer and columns reader as the flow-php/parquet classes + ├── batch.rs # Arrow C Data batches (RustBatchReader, RustParquetBatch, RustArrowSchema) + ├── read.rs # ParquetReader: decodes only the row groups and byte ranges a read plan selects + ├── filter.rs # The row filter the arrow-rs push decoder runs + ├── write.rs # ParquetWriter: canonical arrays cast to the writer schema and written by arrow-rs + ├── canonical.rs # Casts between the arrow-rs Parquet types and the canonical arrays + ├── cells.rs # The flow-php/parquet per-cell values over the canonical arrays + ├── chunks.rs # The column chunks a filter reads, sliced from the footer's thrift bytes + ├── footer.rs # The footer, read and decoded once + ├── options.rs # The arrays of SchemaConverter::toExtension() and OptionsConverter::toExtension() + ├── source.rs # Parquet bytes from a SourceStream + ├── sink.rs # Parquet bytes to a DestinationStream + ├── lib_calls.rs # The flow-php/parquet converters called by name + ├── interfaces.rs # Flow\Parquet\{ParquetEngine, ParquetFileReader, ParquetFileWriter}, found or registered at MINIT + ├── thrift.rs # Footer bytes as the PHP ThriftModel objects + ├── error.rs # Parquet refusals as data + ├── render.rs # Parquet refusals as the Flow\Parquet exceptions + ├── php.rs # PHP engine helpers and the request-scoped cache (thread local) + ├── values.rs # PHP values through the engine's C date API + └── exception.rs # Exception mapping ``` ## Commands diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php index 66f8a9f86c..33f9b28717 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php @@ -10,8 +10,10 @@ use Flow\ETL\Foundation\Exception\InvalidArgumentException; use Flow\ETL\Tests\FlowTestCase; use Flow\Parquet\Engine\PhpParquetEngine; +use Flow\Parquet\Engine\RustParquetEngine; use Flow\Parquet\Option; use Flow\Parquet\Options; +use PHPUnit\Framework\Attributes\RequiresPhpExtension; use function array_filter; use function extension_loaded; @@ -33,6 +35,23 @@ public function test_an_engine_round_trips_without_secrecy(): void ); } + #[RequiresPhpExtension('arrow')] + public function test_an_arrow_engine_round_trips(): void + { + $engine = new RustParquetEngine(Options::default()->set(Option::PAGE_SIZE_BYTES, 7)); + $description = (new ConfiguredParquetEngine($engine))->describe(); + + static::assertNotNull($description); + static::assertSame(RustParquetEngine::class, $description->data['engine']); + static::assertSame( + $engine->normalize(), + (new Rebuild()) + ->of($description->normalize(), ConfiguredParquetEngine::class) + ->engine() + ->normalize(), + ); + } + public function test_an_engine_without_a_normal_form_does_not_describe(): void { static::assertNull((new ConfiguredParquetEngine(new RefusingParquetEngine()))->describe()); diff --git a/src/extension/arrow-ext/Cargo.lock b/src/extension/arrow-ext/Cargo.lock index e8ebe283fd..f6f33d9b70 100644 --- a/src/extension/arrow-ext/Cargo.lock +++ b/src/extension/arrow-ext/Cargo.lock @@ -78,12 +78,9 @@ name = "arrow" version = "0.0.0" dependencies = [ "arrow-array", - "arrow-buffer", "arrow-schema", - "bytes", "ext-php-rs", - "ext-php-rs-build", - "parquet", + "flow-parquet-engine", ] [[package]] @@ -678,6 +675,19 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "flow-parquet-engine" +version = "0.0.0" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", + "bytes", + "ext-php-rs", + "ext-php-rs-build", + "parquet", +] + [[package]] name = "foldhash" version = "0.1.5" diff --git a/src/extension/arrow-ext/Cargo.toml b/src/extension/arrow-ext/Cargo.toml index f6d23a3567..ee2995dd5a 100644 --- a/src/extension/arrow-ext/Cargo.toml +++ b/src/extension/arrow-ext/Cargo.toml @@ -12,11 +12,14 @@ arrow-validate = ["arrow-array/force_validate"] [dependencies] ext-php-rs = "0.16" -parquet = { version = "60", default-features = false, features = ["arrow", "arrow_canonical_extension_types", "snap", "flate2", "flate2-zlib-rs", "zstd", "lz4", "brotli", "simdutf8"] } arrow-array = { version = "60", features = ["ffi"] } -arrow-buffer = "60" +flow-parquet-engine = { path = "crates/flow-parquet-engine", features = ["arrow-names"] } + +[dev-dependencies] arrow-schema = { version = "60", features = ["canonical_extension_types"] } -bytes = "1" -[build-dependencies] -ext-php-rs-build = "0.1" +[profile.release] +strip = true + +[workspace] +members = ["crates/*"] diff --git a/src/extension/arrow-ext/build.rs b/src/extension/arrow-ext/build.rs index c8ce01e82c..35d97ded5b 100644 --- a/src/extension/arrow-ext/build.rs +++ b/src/extension/arrow-ext/build.rs @@ -12,29 +12,6 @@ fn main() { println!("cargo:rustc-env=ARROW_LIB_VERSION={arrow_version}"); println!("cargo:rustc-env=PARQUET_LIB_VERSION={parquet_version}"); - - emit_php_version_cfg(); -} - -/// The `php84`/`php85` cfgs ext-php-rs sets for itself, for the same PHP (`PHP` first, then `PATH`): the extension -/// binary is bound to the PHP minor it is built against, so version gates are compile-time. -fn emit_php_version_cfg() { - use ext_php_rs_build::{ - emit_check_cfg, emit_php_cfg_flags, emit_rerun_if_env_changed, find_php, ApiVersion, PHPInfo, - }; - - emit_rerun_if_env_changed(); - emit_check_cfg(); - - let php = find_php().expect("cannot find the php executable"); - let info = PHPInfo::get(&php).expect("cannot read php -i"); - let version: ApiVersion = info - .zend_version() - .expect("cannot read the Zend API version") - .try_into() - .expect("unsupported Zend API version"); - - emit_php_cfg_flags(version); } fn extension_version(env_name: &str) -> String { diff --git a/src/extension/arrow-ext/crates/flow-parquet-engine b/src/extension/arrow-ext/crates/flow-parquet-engine new file mode 120000 index 0000000000..9a5ac8b719 --- /dev/null +++ b/src/extension/arrow-ext/crates/flow-parquet-engine @@ -0,0 +1 @@ +../../parquet-engine \ No newline at end of file diff --git a/src/extension/arrow-ext/src/alloc.rs b/src/extension/arrow-ext/src/alloc.rs index 8a76e47bcc..c2dfa11453 100644 --- a/src/extension/arrow-ext/src/alloc.rs +++ b/src/extension/arrow-ext/src/alloc.rs @@ -80,3 +80,60 @@ pub fn allocated_bytes() -> i64 { pub fn allocated_bytes() -> i64 { ALLOCATED.load(Ordering::Relaxed) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::ffi::{from_ffi, to_ffi}; + use arrow_array::types::Int64Type; + use arrow_array::{Array, ArrayRef, Int64Array, ListArray, StructArray}; + use arrow_schema::{DataType, Field, Fields}; + + use crate::alloc::allocated_bytes; + + fn batch() -> StructArray { + let ids: ArrayRef = Arc::new(Int64Array::from_iter((0..1000).map(|i| (i % 7 != 0).then_some(i)))); + let lists: ArrayRef = Arc::new(ListArray::from_iter_primitive::( + (0..1000).map(|i| Some(vec![Some(i), None, Some(i * 2)])), + )); + + StructArray::new( + Fields::from(vec![ + Field::new("id", DataType::Int64, true), + Field::new("list", lists.data_type().clone(), true), + ]), + vec![ids, lists], + None, + ) + } + + #[test] + fn an_exported_batch_dropped_unimported_frees_everything() { + let baseline = allocated_bytes(); + + { + let exported = to_ffi(&batch().to_data()).unwrap(); + assert!(allocated_bytes() > baseline); + drop(exported); + } + + assert_eq!(allocated_bytes(), baseline); + } + + #[test] + fn an_exported_batch_imported_then_dropped_frees_everything() { + let baseline = allocated_bytes(); + + { + let (array, schema) = to_ffi(&batch().to_data()).unwrap(); + let imported = StructArray::from(unsafe { from_ffi(array, &schema) }.unwrap()); + assert_eq!(imported.len(), 1000); + assert_eq!(imported, batch()); + drop(schema); + drop(imported); + } + + assert_eq!(allocated_bytes(), baseline); + } +} diff --git a/src/extension/arrow-ext/src/lib.rs b/src/extension/arrow-ext/src/lib.rs index b741f798b7..f3083c7a7a 100644 --- a/src/extension/arrow-ext/src/lib.rs +++ b/src/extension/arrow-ext/src/lib.rs @@ -1,15 +1,9 @@ mod alloc; -mod exception; -mod interfaces; -mod parquet; -mod php; -mod render; -mod thrift; -mod values; use ext_php_rs::prelude::*; use ext_php_rs::zend::ModuleEntry; use ext_php_rs::{info_table_end, info_table_row, info_table_start}; +use flow_parquet_engine::{batch, engine, interfaces, library, php}; #[php_function] #[php(name = "Flow\\Arrow\\allocated_bytes")] @@ -42,6 +36,18 @@ pub unsafe extern "C" fn module_startup(_type: i32, _module_number: i32) -> i32 0 } +pub extern "C" fn request_startup(_type: i32, _module_number: i32) -> i32 { + php::request_startup(); + + 0 +} + +pub extern "C" fn request_shutdown(_type: i32, _module_number: i32) -> i32 { + php::request_shutdown(); + + 0 +} + #[php_module] #[php(startup = "module_startup")] pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { @@ -49,16 +55,15 @@ pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { .version(env!("ARROW_VERSION")) .info_function(php_module_info) .constant(("FLOW_ARROW_ABI", FLOW_ARROW_ABI, &[])) - .globals(&php::GLOBALS) - .request_startup_function(php::request_startup) - .request_shutdown_function(php::request_shutdown) + .request_startup_function(request_startup) + .request_shutdown_function(request_shutdown) .function(wrap_function!(allocated_bytes)) - .class::() - .class::() - .class::() - .class::() - .class::() - .class::() - .class::() - .class::() + .class::() + .class::() + .class::() + .class::() + .class::() + .class::() + .class::() + .class::() } diff --git a/src/extension/arrow-ext/src/parquet/mod.rs b/src/extension/arrow-ext/src/parquet/mod.rs deleted file mode 100644 index 2d090f889c..0000000000 --- a/src/extension/arrow-ext/src/parquet/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Parquet in arrow: one reader, one cast table and one writer over Flow filesystem streams, surfaced as the -//! `flow-php/parquet` lib's values (`library`) and as Arrow C Data struct batches (`batch`). - -pub mod batch; -pub mod canonical; -pub mod cells; -pub mod chunks; -pub mod engine; -pub mod error; -pub mod filter; -pub mod footer; -pub mod lib_calls; -#[allow( - non_snake_case, - reason = "PHP takes a parameter name from its Rust identifier: the contracts' are camelCase" -)] -pub mod library; -pub mod options; -pub mod read; -pub mod sink; -pub mod source; -pub mod write; diff --git a/src/extension/flow-php-ext/Cargo.lock b/src/extension/flow-php-ext/Cargo.lock index f3f731ddfa..81bf01a467 100644 --- a/src/extension/flow-php-ext/Cargo.lock +++ b/src/extension/flow-php-ext/Cargo.lock @@ -43,11 +43,26 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "android_system_properties" -version = "0.1.6" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ "libc", ] @@ -60,9 +75,9 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" [[package]] name = "arrow-arith" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2961626677665b2195eb59242af4c7befe7b8737ca2050295389362380104e" +checksum = "2303ebedb1071f4f72d71171e383859a9a285c94d99e4892685a96fca9890720" dependencies = [ "arrow-array", "arrow-buffer", @@ -74,9 +89,9 @@ dependencies = [ [[package]] name = "arrow-array" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e5f6adeffdf587d7a31db5d2266189624b526730cd3627f9ff9fedae97ad584" +checksum = "51dff6e4b9f158864a0aeb6a131ad53858ecbae7a2fc8989307b9b3c6b2f122e" dependencies = [ "ahash", "arrow-buffer", @@ -93,9 +108,9 @@ dependencies = [ [[package]] name = "arrow-buffer" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "097d193003ce7995d5d087089069ec2a6e0187faf5a6f8c9f38af2645d987182" +checksum = "c7235b863533e9db3ab86905b4521251de11226275b436ff3cb2d0010558d1c5" dependencies = [ "bytes", "half", @@ -103,11 +118,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arrow-cmp" +version = "60.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73a0e9adb28d95739fabcdae637261a2c14e618caf58ba1b88857120f9ee2687" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", +] + [[package]] name = "arrow-data" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba2f832eaeca24b8f26143dba750e42ee4ab51cf7d65e701ca9607cfda9f358" +checksum = "5aa06d5e22786c4966ffc4d2f171d0cb65d95f6bdea108a14e8c335e9faa437f" dependencies = [ "arrow-buffer", "arrow-schema", @@ -116,14 +142,29 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arrow-ipc" +version = "60.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86c523472d22e31f984df7a44fc36e6323d3c9b05ffe53d267ee4c3aa7c128d2" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "arrow-select", + "flatbuffers", +] + [[package]] name = "arrow-ord" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c900759f3bd8354fd4196bc4403eee846894dc2adf66b4225472006a0bf18c5" +checksum = "5a7ac2c6a9cdc782fa9548d3763461eaec8c93347e297fddbaa44807e70a3698" dependencies = [ "arrow-array", "arrow-buffer", + "arrow-cmp", "arrow-data", "arrow-schema", "arrow-select", @@ -131,9 +172,9 @@ dependencies = [ [[package]] name = "arrow-schema" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10fab8d4563491417ba801fab29d205104d20d4bdf37bda6cd1cf425cff598cd" +checksum = "f85a9a58cd03560526b0066487574aacb9008e413504fa0ee23d61141e96c338" dependencies = [ "bitflags", "serde_core", @@ -142,13 +183,14 @@ dependencies = [ [[package]] name = "arrow-select" -version = "59.3.0" +version = "60.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc58569193c2525915f3cc6310edba3792f1200f65d6e9ed330aa33e691493b8" +checksum = "ba3482b7d03bf4a3bf0b195f08a7f2b071595ccd54897e35b975ac63d3104977" dependencies = [ "ahash", "arrow-array", "arrow-buffer", + "arrow-cmp", "arrow-data", "arrow-schema", "num-traits", @@ -156,9 +198,9 @@ dependencies = [ [[package]] name = "autocfg" -version = "1.5.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "base64" @@ -166,6 +208,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -186,15 +234,15 @@ dependencies = [ "quote", "regex", "rustc-hash", - "shlex", + "shlex 2.0.1", "syn 3.0.6", ] [[package]] name = "bitflags" -version = "2.13.0" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" [[package]] name = "block-buffer" @@ -206,11 +254,32 @@ dependencies = [ "zeroize", ] +[[package]] +name = "brotli" +version = "9.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" [[package]] name = "bytecount" @@ -220,9 +289,9 @@ checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" [[package]] name = "bytes" -version = "1.12.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "bzip2" @@ -267,14 +336,14 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.66" +version = "1.2.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" +checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 1.3.0", ] [[package]] @@ -300,9 +369,9 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chrono" -version = "0.4.45" +version = "0.4.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" dependencies = [ "iana-time-zone", "num-traits", @@ -515,9 +584,9 @@ dependencies = [ [[package]] name = "either" -version = "1.16.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "equivalent" @@ -600,6 +669,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" +dependencies = [ + "bitflags", + "rustc_version", +] + [[package]] name = "flate2" version = "1.1.9" @@ -675,6 +754,19 @@ dependencies = [ name = "flow-numeric-string" version = "0.1.0" +[[package]] +name = "flow-parquet-engine" +version = "0.0.0" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", + "bytes", + "ext-php-rs", + "ext-php-rs-build", + "parquet", +] + [[package]] name = "flow_php" version = "0.0.0" @@ -695,6 +787,7 @@ dependencies = [ "flow-csv-tokenizer", "flow-json-records", "flow-numeric-string", + "flow-parquet-engine", "memchr", "serde", "serde_json", @@ -715,30 +808,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - [[package]] name = "getrandom" version = "0.2.17" @@ -884,9 +953,9 @@ dependencies = [ [[package]] name = "inventory" -version = "0.3.24" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" +checksum = "009ae045c87e7082cb72dab0ccd01ae075dd00141ddc108f43a0ea150a9e7227" dependencies = [ "rustversion", ] @@ -902,9 +971,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" [[package]] name = "jobserver" @@ -918,12 +987,11 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.103" +version = "0.3.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" dependencies = [ - "cfg-if", - "futures-util", + "once_cell", "wasm-bindgen", ] @@ -935,9 +1003,9 @@ checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c" [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -972,9 +1040,18 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lz4_flex" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +dependencies = [ + "twox-hash", +] [[package]] name = "lzma-rust2" @@ -987,9 +1064,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.2" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] name = "minimal-lexical" @@ -1073,9 +1150,9 @@ checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "num-integer" -version = "0.1.47" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" dependencies = [ "num-traits", ] @@ -1118,7 +1195,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", ] [[package]] @@ -1162,6 +1239,37 @@ dependencies = [ "windows-link", ] +[[package]] +name = "parquet" +version = "60.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8af83d2940bc0510f9aef86d865f56fdc6095f87ab115ac885a80b7c5226d3ba" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-ipc", + "arrow-schema", + "arrow-select", + "base64 0.23.1", + "brotli", + "bytes", + "chrono", + "flate2", + "half", + "hashbrown", + "lz4_flex", + "num-bigint", + "num-integer", + "num-traits", + "seq-macro", + "simdutf8", + "snap", + "twox-hash", + "zstd", +] + [[package]] name = "pbkdf2" version = "0.13.0" @@ -1187,17 +1295,11 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] name = "powerfmt" @@ -1233,9 +1335,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.46" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] @@ -1296,6 +1398,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.4" @@ -1373,14 +1484,20 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.28" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" dependencies = [ "serde", "serde_core", ] +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.228" @@ -1408,14 +1525,14 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", ] [[package]] name = "serde_json" -version = "1.0.150" +version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ "itoa", "memchr", @@ -1446,6 +1563,12 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -1454,9 +1577,15 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "simd-adler32" -version = "0.3.9" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" + +[[package]] +name = "simdutf8" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "skeptic" @@ -1476,16 +1605,16 @@ dependencies = [ ] [[package]] -name = "slab" -version = "0.4.12" +name = "smallvec" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] -name = "smallvec" -version = "1.15.2" +name = "snap" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" [[package]] name = "strsim" @@ -1495,9 +1624,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" -version = "2.0.118" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", @@ -1554,7 +1683,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", ] [[package]] @@ -1597,6 +1726,12 @@ dependencies = [ "crunchy", ] +[[package]] +name = "twox-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" + [[package]] name = "typed-path" version = "0.13.0" @@ -1623,9 +1758,9 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-segmentation" -version = "1.13.3" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "ureq" @@ -1633,7 +1768,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" dependencies = [ - "base64", + "base64 0.22.1", "der", "flate2", "log", @@ -1651,7 +1786,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c" dependencies = [ - "base64", + "base64 0.22.1", "http", "httparse", "log", @@ -1693,18 +1828,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.4+wasi-0.2.12" +version = "1.0.2+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.126" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" dependencies = [ "cfg-if", "once_cell", @@ -1715,9 +1850,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.126" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -1725,22 +1860,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.126" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.126" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" dependencies = [ "unicode-ident", ] @@ -1784,7 +1919,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", ] [[package]] @@ -1795,7 +1930,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", ] [[package]] @@ -1833,9 +1968,9 @@ dependencies = [ [[package]] name = "wit-bindgen" -version = "0.57.1" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" [[package]] name = "xxhash-rust" @@ -1845,22 +1980,22 @@ checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" [[package]] name = "zerocopy" -version = "0.8.59" +version = "0.8.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +checksum = "f2578b716f8a7a858b7f02d5bd870c14bf4ddbbcf3a4c05414ba6503640505e3" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.59" +version = "0.8.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +checksum = "7e6cc098ea4d3bd6246687de65af3f920c430e236bee1e3bf2e441463f08a02f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.117", ] [[package]] @@ -1900,9 +2035,9 @@ dependencies = [ [[package]] name = "zlib-rs" -version = "0.6.5" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5431d5661c32445236631278f27946e444ddafe4684cac70b185272d4f9c52d5" +checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513" [[package]] name = "zmij" @@ -1924,27 +2059,27 @@ dependencies = [ [[package]] name = "zstd" -version = "0.14.3" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" +checksum = "057cfd910cfac363a0ada849592624b4c9ff2e10bef504c3433810d78ed96f93" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "8.2.0" +version = "8.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" +checksum = "bdd44c6a7284e91f3717755b24315a302edd9153a01f753c3cba3d765e8eafac" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.2+zstd.1.5.7" +version = "2.1.1+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +checksum = "aeec9eaf2dffbbd09201e23bd0ffcbaa33bb8e9266a10734fd7ed90a85eca078" dependencies = [ "cc", "pkg-config", diff --git a/src/extension/flow-php-ext/Cargo.toml b/src/extension/flow-php-ext/Cargo.toml index f28edc75c3..7a61beed92 100644 --- a/src/extension/flow-php-ext/Cargo.toml +++ b/src/extension/flow-php-ext/Cargo.toml @@ -16,13 +16,14 @@ arrow-array.workspace = true arrow-buffer.workspace = true arrow-data.workspace = true arrow-schema.workspace = true -arrow-select = "59" +arrow-select = "60" bytes = "1" ext-php-rs = "0.16" flow-arrow-c = { path = "crates/flow-arrow-c" } flow-batch-frame = { path = "crates/flow-batch-frame" } flow-column-kernels = { path = "crates/flow-column-kernels" } flow-column-text = { path = "crates/flow-column-text" } +flow-parquet-engine = { path = "crates/flow-parquet-engine", features = ["flow-php-names"] } flow-csv-tokenizer = { path = "crates/flow-csv-tokenizer" } flow-json-records = { path = "crates/flow-json-records" } flow-numeric-string = { path = "crates/flow-numeric-string" } @@ -40,10 +41,10 @@ strip = true members = ["crates/*"] [workspace.dependencies] -arrow-array = { version = "59", features = ["ffi"] } -arrow-buffer = "59" -arrow-data = "59" -arrow-schema = { version = "59", features = ["canonical_extension_types"] } +arrow-array = { version = "60", features = ["ffi"] } +arrow-buffer = "60" +arrow-data = "60" +arrow-schema = { version = "60", features = ["canonical_extension_types"] } memchr = "2" serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["raw_value", "unbounded_depth"] } diff --git a/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs b/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs index 53b2710167..ae210dc058 100644 --- a/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs +++ b/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs @@ -1,6 +1,6 @@ //! Batches across the Arrow C Data Interface; imported buffers count in [`imported_bytes`] while they live. -use std::ffi::{CStr, CString}; +use std::ffi::{c_char, CStr, CString}; use std::sync::atomic::{AtomicI64, Ordering}; use arrow_array::ffi::{from_ffi_and_data_type, to_ffi, FFI_ArrowArray, FFI_ArrowSchema}; @@ -48,15 +48,44 @@ pub struct Expected { children: Vec<(CString, CString)>, } +// The spec's leading C Data Interface fields: arrow-rs 60 hides them, its accessors panic on a null format. +#[repr(C)] +struct SchemaHead { + format: *const c_char, + name: *const c_char, + metadata: *const c_char, + flags: i64, + n_children: i64, +} + +#[repr(C)] +struct ArrayHead { + length: i64, + null_count: i64, + offset: i64, + n_buffers: i64, + n_children: i64, +} + +fn schema_head(schema: &FFI_ArrowSchema) -> &SchemaHead { + unsafe { &*(schema as *const FFI_ArrowSchema).cast::() } +} + +fn array_head(array: &FFI_ArrowArray) -> &ArrayHead { + unsafe { &*(array as *const FFI_ArrowArray).cast::() } +} + /// The struct schema `schema`, its children named and typed as `columns` (name, stored type) are. pub fn check(schema: &FFI_ArrowSchema, columns: &[(&[u8], DataType)]) -> Result { - if schema.format.is_null() || unsafe { CStr::from_ptr(schema.format) }.to_bytes() != b"+s" { + let head = schema_head(schema); + + if head.format.is_null() || unsafe { CStr::from_ptr(head.format) }.to_bytes() != b"+s" { return Err(Refusal::NotStruct); } - if schema.n_children != columns.len() as i64 { + if head.n_children != columns.len() as i64 { return Err(Refusal::Count { - children: schema.n_children, + children: head.n_children, columns: columns.len(), }); } @@ -78,9 +107,11 @@ pub fn check(schema: &FFI_ArrowSchema, columns: &[(&[u8], DataType)]) -> Result< return Err(Refusal::Type { column, child: field }); } + let child_head = schema_head(child); + children.push(( - unsafe { CStr::from_ptr(child.name) }.to_owned(), - unsafe { CStr::from_ptr(child.format) }.to_owned(), + unsafe { CStr::from_ptr(child_head.name) }.to_owned(), + unsafe { CStr::from_ptr(child_head.format) }.to_owned(), )); fields.push(field); } @@ -94,26 +125,30 @@ pub fn check(schema: &FFI_ArrowSchema, columns: &[(&[u8], DataType)]) -> Result< /// Refuses a struct schema whose children are not `expected`'s by count, name or format: the per-batch guard, with no /// `Field` built. pub fn same_children(schema: &FFI_ArrowSchema, expected: &Expected) -> Result<(), Refusal> { - if schema.format.is_null() || unsafe { CStr::from_ptr(schema.format) }.to_bytes() != b"+s" { + let head = schema_head(schema); + + if head.format.is_null() || unsafe { CStr::from_ptr(head.format) }.to_bytes() != b"+s" { return Err(Refusal::NotStruct); } - if schema.n_children != expected.children.len() as i64 { + if head.n_children != expected.children.len() as i64 { return Err(Refusal::Count { - children: schema.n_children, + children: head.n_children, columns: expected.children.len(), }); } for (column, (child, (name, format))) in schema.children().zip(&expected.children).enumerate() { - if unsafe { CStr::from_ptr(child.name) } != name.as_c_str() { + let child_head = schema_head(child); + + if unsafe { CStr::from_ptr(child_head.name) } != name.as_c_str() { return Err(Refusal::Name { - child: String::from_utf8_lossy(unsafe { CStr::from_ptr(child.name) }.to_bytes()).into_owned(), + child: String::from_utf8_lossy(unsafe { CStr::from_ptr(child_head.name) }.to_bytes()).into_owned(), column, }); } - if unsafe { CStr::from_ptr(child.format) } != format.as_c_str() { + if unsafe { CStr::from_ptr(child_head.format) } != format.as_c_str() { return Err(Refusal::Type { column, child: Field::try_from(child).map_err(Refusal::Schema)?, @@ -136,11 +171,11 @@ unsafe extern "C" fn counted_release(array: *mut FFI_ArrowArray) { let Some(array) = (unsafe { array.as_mut() }) else { return; }; - let Counted { inner, bytes } = *unsafe { Box::from_raw(array.private_data.cast::()) }; + let Counted { inner, bytes } = *unsafe { Box::from_raw(array.private_data().cast::()) }; IMPORTED.fetch_sub(bytes, Ordering::Relaxed); drop(inner); - array.release = None; + unsafe { array.set_release(None) }; } /// Moves `source` behind the counting forwarder once `schema` passed [`same_children`]; an early refusal takes nothing. @@ -151,34 +186,28 @@ pub fn take( ) -> Result<(usize, Vec), Refusal> { same_children(schema, expected)?; - if source.release.is_none() { + if source.is_released() { return Err(Refusal::Released); } - if source.n_children != schema.n_children || source.length < 0 { + let (source_head, head) = (array_head(source), schema_head(schema)); + + if source_head.n_children != head.n_children || source_head.length < 0 { return Err(Refusal::Length { - children: source.n_children, - schema: schema.n_children, + children: source_head.n_children, + schema: head.n_children, }); } let moved = unsafe { std::ptr::read(source) }; - source.release = None; + unsafe { source.set_release(None) }; let counted = Box::into_raw(Box::new(Counted { inner: moved, bytes: 0 })); - let inner = unsafe { &(*counted).inner }; - let forward = FFI_ArrowArray { - length: inner.length, - null_count: inner.null_count, - offset: inner.offset, - n_buffers: inner.n_buffers, - n_children: inner.n_children, - buffers: inner.buffers, - children: inner.children, - dictionary: inner.dictionary, - release: Some(counted_release), - private_data: counted.cast(), - }; + let mut forward = unsafe { std::ptr::read(&(*counted).inner) }; + unsafe { + forward.set_release(Some(counted_release)); + forward.set_private_data(counted.cast()); + } let data = unsafe { from_ffi_and_data_type(forward, expected.data_type.clone()) } .and_then(|data| data.validate().map(|()| data)) @@ -228,8 +257,8 @@ mod tests { /// The producer: arrow-rs's export, wrapped so its release counts how often it ran. unsafe extern "C" fn counting_release(array: *mut FFI_ArrowArray) { let array = unsafe { &mut *array }; - drop(unsafe { Box::from_raw(array.private_data.cast::()) }); - array.release = None; + drop(unsafe { Box::from_raw(array.private_data().cast::()) }); + unsafe { array.set_release(None) }; RELEASES.fetch_add(1, Ordering::SeqCst); } @@ -256,19 +285,11 @@ mod tests { let batch = StructArray::new(fields, columns().into_iter().map(|(_, array)| array).collect(), None); let (inner, schema) = to_ffi(&batch.to_data()).unwrap(); let inner = Box::into_raw(Box::new(inner)); - let exported = unsafe { &*inner }; - let array = FFI_ArrowArray { - length: exported.length, - null_count: exported.null_count, - offset: exported.offset, - n_buffers: exported.n_buffers, - n_children: exported.n_children, - buffers: exported.buffers, - children: exported.children, - dictionary: exported.dictionary, - release: Some(counting_release), - private_data: inner.cast::(), - }; + let mut array = unsafe { std::ptr::read(inner) }; + unsafe { + array.set_release(Some(counting_release)); + array.set_private_data(inner.cast::()); + } (array, schema) } @@ -296,7 +317,7 @@ mod tests { let (rows, arrays) = take(&schema, &mut array, &expected()).unwrap(); - assert!(array.release.is_none()); + assert!(array.release().is_none()); assert_eq!(rows, 1000); assert_eq!(arrays.len(), 2); assert_eq!(arrays[0].as_ref(), columns()[0].1.as_ref()); @@ -335,7 +356,7 @@ mod tests { assert!(refusal(&take(&schema, &mut array, &expected).unwrap_err())); assert_eq!(imported(), 0); - assert!(array.release.is_some()); + assert!(array.release().is_some()); assert_eq!(RELEASES.load(Ordering::SeqCst), releases); drop(array); diff --git a/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml b/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml index 9f09cf113f..f7536e9edb 100644 --- a/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml +++ b/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml @@ -9,8 +9,8 @@ publish = false [dependencies] arrow-array.workspace = true arrow-buffer.workspace = true -arrow-arith = "59" -arrow-ord = "59" +arrow-arith = "60" +arrow-ord = "60" arrow-schema.workspace = true memchr.workspace = true xxhash-rust.workspace = true diff --git a/src/extension/flow-php-ext/crates/flow-parquet-engine b/src/extension/flow-php-ext/crates/flow-parquet-engine new file mode 120000 index 0000000000..9a5ac8b719 --- /dev/null +++ b/src/extension/flow-php-ext/crates/flow-parquet-engine @@ -0,0 +1 @@ +../../parquet-engine \ No newline at end of file diff --git a/src/extension/parquet-engine/Cargo.toml b/src/extension/parquet-engine/Cargo.toml new file mode 100644 index 0000000000..b422503ca0 --- /dev/null +++ b/src/extension/parquet-engine/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "flow-parquet-engine" +edition = "2021" +publish = false + +[features] +# the PHP class names of the extension that builds the crate: exactly one is enabled +arrow-names = [] +flow-php-names = [] + +[dependencies] +ext-php-rs = "0.16" +arrow-array = { version = "60", features = ["ffi"] } +arrow-buffer = "60" +arrow-schema = { version = "60", features = ["canonical_extension_types"] } +bytes = "1" +parquet = { version = "60", default-features = false, features = ["arrow", "arrow_canonical_extension_types", "snap", "flate2", "flate2-zlib-rs", "zstd", "lz4", "brotli", "simdutf8"] } + +[build-dependencies] +ext-php-rs-build = "0.1" diff --git a/src/extension/parquet-engine/build.rs b/src/extension/parquet-engine/build.rs new file mode 100644 index 0000000000..9a0e2073fd --- /dev/null +++ b/src/extension/parquet-engine/build.rs @@ -0,0 +1,24 @@ +fn main() { + emit_php_version_cfg(); +} + +/// The `php84`/`php85` cfgs ext-php-rs sets for itself, for the same PHP (`PHP` first, then `PATH`): the extension +/// binary is bound to the PHP minor it is built against, so version gates are compile-time. +fn emit_php_version_cfg() { + use ext_php_rs_build::{ + emit_check_cfg, emit_php_cfg_flags, emit_rerun_if_env_changed, find_php, ApiVersion, PHPInfo, + }; + + emit_rerun_if_env_changed(); + emit_check_cfg(); + + let php = find_php().expect("cannot find the php executable"); + let info = PHPInfo::get(&php).expect("cannot read php -i"); + let version: ApiVersion = info + .zend_version() + .expect("cannot read the Zend API version") + .try_into() + .expect("unsupported Zend API version"); + + emit_php_cfg_flags(version); +} diff --git a/src/extension/parquet-engine/rustfmt.toml b/src/extension/parquet-engine/rustfmt.toml new file mode 100644 index 0000000000..7530651796 --- /dev/null +++ b/src/extension/parquet-engine/rustfmt.toml @@ -0,0 +1 @@ +max_width = 120 diff --git a/src/extension/arrow-ext/src/parquet/batch.rs b/src/extension/parquet-engine/src/batch.rs similarity index 90% rename from src/extension/arrow-ext/src/parquet/batch.rs rename to src/extension/parquet-engine/src/batch.rs index 8dcc6110ab..5ee5894937 100644 --- a/src/extension/arrow-ext/src/parquet/batch.rs +++ b/src/extension/parquet-engine/src/batch.rs @@ -12,12 +12,12 @@ use ext_php_rs::prelude::*; use ext_php_rs::types::{ZendObject, Zval}; use ext_php_rs::zend::ClassEntry; -use crate::parquet::error::Error; -use crate::parquet::library::{batch_size, read_plan, RustParquetFileReader, INVALID_ARGUMENT}; -use crate::parquet::read::ParquetReader; -use crate::parquet::source::PhpStream; +use crate::error::Error; +use crate::library::{batch_size, read_plan, RustParquetFileReader, INVALID_ARGUMENT}; use crate::php::{call_handle_transparent, ce_method_ref}; +use crate::read::ParquetReader; use crate::render::{exception, parquet_exception, Side}; +use crate::source::PhpStream; /// Child field metadata: the arrow type of the file column the canonical child was read from. pub const SOURCE_TYPE: &str = "parquet.source_type"; @@ -119,7 +119,8 @@ impl RustBatchReader { } /// At most `$batchSize` rows as one struct batch, null after the last. - pub fn next(&mut self) -> PhpResult> { + #[php(name = "next")] + pub fn next_batch(&mut self) -> PhpResult> { let Some(reader) = self.reader.as_mut() else { return Ok(None); }; @@ -260,13 +261,11 @@ unsafe fn check(schema: *const FFI_ArrowSchema, array: *const FFI_ArrowArray) -> mod tests { use std::sync::Arc; - use arrow_array::ffi::{from_ffi, to_ffi}; + use arrow_array::ffi::to_ffi; use arrow_array::types::Int64Type; use arrow_array::{Array, ArrayRef, Int64Array, ListArray, StructArray}; use arrow_schema::{DataType, Field, Fields}; - use crate::alloc::allocated_bytes; - fn batch() -> StructArray { let ids: ArrayRef = Arc::new(Int64Array::from_iter((0..1000).map(|i| (i % 7 != 0).then_some(i)))); let lists: ArrayRef = Arc::new(ListArray::from_iter_primitive::( @@ -283,35 +282,6 @@ mod tests { ) } - #[test] - fn an_exported_batch_dropped_unimported_frees_everything() { - let baseline = allocated_bytes(); - - { - let exported = to_ffi(&batch().to_data()).unwrap(); - assert!(allocated_bytes() > baseline); - drop(exported); - } - - assert_eq!(allocated_bytes(), baseline); - } - - #[test] - fn an_exported_batch_imported_then_dropped_frees_everything() { - let baseline = allocated_bytes(); - - { - let (array, schema) = to_ffi(&batch().to_data()).unwrap(); - let imported = StructArray::from(unsafe { from_ffi(array, &schema) }.unwrap()); - assert_eq!(imported.len(), 1000); - assert_eq!(imported, batch()); - drop(schema); - drop(imported); - } - - assert_eq!(allocated_bytes(), baseline); - } - fn refusal(mutate: impl FnOnce(*mut super::SchemaHead, *mut super::ArrayHead)) -> Result<(), String> { let (mut array, mut schema) = to_ffi(&batch().to_data()).unwrap(); let schema_ptr = &mut schema as *mut arrow_array::ffi::FFI_ArrowSchema; diff --git a/src/extension/arrow-ext/src/parquet/canonical.rs b/src/extension/parquet-engine/src/canonical.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/canonical.rs rename to src/extension/parquet-engine/src/canonical.rs index b528017d53..4797f64060 100644 --- a/src/extension/arrow-ext/src/parquet/canonical.rs +++ b/src/extension/parquet-engine/src/canonical.rs @@ -18,8 +18,8 @@ use arrow_array::{ use arrow_buffer::{OffsetBuffer, ScalarBuffer}; use arrow_schema::{DataType, Field, FieldRef, Fields, TimeUnit}; -use crate::parquet::cells::{unsigned, UNSIGNED_EXPECTED}; -use crate::parquet::error::{parent_row, Error}; +use crate::cells::{unsigned, UNSIGNED_EXPECTED}; +use crate::error::{parent_row, Error}; const UTC: &str = "UTC"; @@ -639,7 +639,7 @@ mod tests { use arrow_schema::{DataType, Field, Fields, TimeUnit}; use super::{canonical, canonical_type, to_parquet}; - use crate::parquet::error::Error; + use crate::error::Error; fn read(array: ArrayRef) -> ArrayRef { let field = Field::new("column", array.data_type().clone(), true); diff --git a/src/extension/arrow-ext/src/parquet/cells.rs b/src/extension/parquet-engine/src/cells.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/cells.rs rename to src/extension/parquet-engine/src/cells.rs index 8477af2f76..1a6d7ad8a9 100644 --- a/src/extension/arrow-ext/src/parquet/cells.rs +++ b/src/extension/parquet-engine/src/cells.rs @@ -18,8 +18,8 @@ use ext_php_rs::exception::PhpException; use ext_php_rs::types::{ZendHashTable, ZendObject, Zval}; use ext_php_rs::zend::{ClassEntry, Function}; +use crate::error::Error; use crate::exception::ext_exception; -use crate::parquet::error::Error; use crate::php::{ call_handle_transparent, ce_method_ref, find_class, ht_for_each, ht_get, ht_insert, ht_insert_long, read_property, zval_long, zval_str, diff --git a/src/extension/arrow-ext/src/parquet/chunks.rs b/src/extension/parquet-engine/src/chunks.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/chunks.rs rename to src/extension/parquet-engine/src/chunks.rs index c16c830449..0019aec60c 100644 --- a/src/extension/arrow-ext/src/parquet/chunks.rs +++ b/src/extension/parquet-engine/src/chunks.rs @@ -3,7 +3,7 @@ use std::ops::Range; -use crate::parquet::error::Error; +use crate::error::Error; use crate::thrift::{elements as list, fields, Field, Malformed}; const FILE_ROW_GROUPS: i16 = 4; @@ -163,8 +163,8 @@ mod tests { use parquet::file::properties::WriterProperties; use super::{chunk_spans, refuse_encrypted}; - use crate::parquet::error::Error; - use crate::parquet::footer::Footer; + use crate::error::Error; + use crate::footer::Footer; use crate::thrift::{elements, fields}; /// `id` Int64 and `name` Utf8 in two row groups of 2 rows. diff --git a/src/extension/arrow-ext/src/parquet/engine.rs b/src/extension/parquet-engine/src/engine.rs similarity index 89% rename from src/extension/arrow-ext/src/parquet/engine.rs rename to src/extension/parquet-engine/src/engine.rs index bef525db69..c6c67de8e0 100644 --- a/src/extension/arrow-ext/src/parquet/engine.rs +++ b/src/extension/parquet-engine/src/engine.rs @@ -8,18 +8,29 @@ use ext_php_rs::types::{ZendHashTable, Zval}; use crate::exception::ext_exception; use crate::interfaces::parquet_engine_ce; -use crate::parquet::lib_calls::{ +use crate::lib_calls::{ call_static, OPTIONS_DEFAULT, OPTIONS_FROM_ARRAY, OPTIONS_TO_ENGINE, OPTIONS_TO_EXTENSION, SCHEMA_TO_EXTENSION, }; -use crate::parquet::library::{RustParquetFileReader, RustParquetFileWriter}; +use crate::library::{RustParquetFileReader, RustParquetFileWriter}; use crate::php::{call_method, ht_get, ht_insert, IterableArg}; use crate::render::{exception, INVALID_ARGUMENT}; #[php_class] -#[php( - name = "Flow\\Parquet\\Engine\\RustParquetEngine", - flags = ClassFlags::Final, - implements(ce = parquet_engine_ce, stub = "Flow\\Parquet\\ParquetEngine") +#[cfg_attr( + feature = "arrow-names", + php( + name = "Flow\\Parquet\\Engine\\RustParquetEngine", + flags = ClassFlags::Final, + implements(ce = parquet_engine_ce, stub = "Flow\\Parquet\\ParquetEngine") + ) +)] +#[cfg_attr( + feature = "flow-php-names", + php( + name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetEngine", + flags = ClassFlags::Final, + implements(ce = parquet_engine_ce, stub = "Flow\\Parquet\\ParquetEngine") + ) )] pub struct RustParquetEngine { int96_as_datetime: bool, diff --git a/src/extension/arrow-ext/src/parquet/error.rs b/src/extension/parquet-engine/src/error.rs similarity index 100% rename from src/extension/arrow-ext/src/parquet/error.rs rename to src/extension/parquet-engine/src/error.rs diff --git a/src/extension/arrow-ext/src/exception.rs b/src/extension/parquet-engine/src/exception.rs similarity index 100% rename from src/extension/arrow-ext/src/exception.rs rename to src/extension/parquet-engine/src/exception.rs diff --git a/src/extension/arrow-ext/src/parquet/filter.rs b/src/extension/parquet-engine/src/filter.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/filter.rs rename to src/extension/parquet-engine/src/filter.rs index ed589620e9..ae9e9ba9f1 100644 --- a/src/extension/arrow-ext/src/parquet/filter.rs +++ b/src/extension/parquet-engine/src/filter.rs @@ -19,8 +19,8 @@ use parquet::arrow::ProjectionMask; use parquet::basic::{ConvertedType, LogicalType, Type}; use parquet::schema::types::{ColumnDescriptor, SchemaDescriptor}; -use crate::parquet::error::Error; -use crate::parquet::read::{struct_child, struct_field}; +use crate::error::Error; +use crate::read::{struct_child, struct_field}; /// A PHP value as the converter's array holds it. #[derive(Debug, Clone, PartialEq)] @@ -681,7 +681,7 @@ mod tests { use parquet::schema::types::SchemaDescriptor; use super::{Interval, PlanPredicate, Raw, Scalar}; - use crate::parquet::error::Error; + use crate::error::Error; const SCHEMA: &str = "message schema { optional int64 i; diff --git a/src/extension/arrow-ext/src/parquet/footer.rs b/src/extension/parquet-engine/src/footer.rs similarity index 96% rename from src/extension/arrow-ext/src/parquet/footer.rs rename to src/extension/parquet-engine/src/footer.rs index d12275889b..e9905f826c 100644 --- a/src/extension/arrow-ext/src/parquet/footer.rs +++ b/src/extension/parquet-engine/src/footer.rs @@ -7,8 +7,8 @@ use bytes::{Bytes, BytesMut}; use parquet::file::metadata::{ParquetMetaData, ParquetMetaDataReader}; use parquet::file::reader::ChunkReader; -use crate::parquet::chunks::refuse_encrypted; -use crate::parquet::error::Error; +use crate::chunks::refuse_encrypted; +use crate::error::Error; /// What the first read takes from the end of the file: the whole footer of every file it is shorter than. const TAIL: u64 = 64 * 1024; @@ -101,9 +101,9 @@ mod tests { use parquet::file::reader::{ChunkReader, Length}; use super::Footer; - use crate::parquet::error::Error; - use crate::parquet::source::fake::Counting; - use crate::parquet::source::{exact, WindowedRead}; + use crate::error::Error; + use crate::source::fake::Counting; + use crate::source::{exact, WindowedRead}; struct Source(Arc); diff --git a/src/extension/arrow-ext/src/interfaces.rs b/src/extension/parquet-engine/src/interfaces.rs similarity index 91% rename from src/extension/arrow-ext/src/interfaces.rs rename to src/extension/parquet-engine/src/interfaces.rs index 35e9718913..a652f5d36f 100644 --- a/src/extension/arrow-ext/src/interfaces.rs +++ b/src/extension/parquet-engine/src/interfaces.rs @@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicPtr, Ordering}; use ext_php_rs::args::{Arg, ArgInfoTables}; use ext_php_rs::builders::{ClassBuilder, FunctionBuilder}; use ext_php_rs::error::Result; +use ext_php_rs::ffi::{ext_php_rs_compiler_globals, zend_hash_str_find_ptr_lc}; use ext_php_rs::flags::{ClassFlags, DataType, MethodFlags}; use ext_php_rs::zend::ClassEntry; @@ -75,6 +76,17 @@ pub fn parquet_file_writer_ce() -> &'static ClassEntry { load(&PARQUET_FILE_WRITER_CE, "Flow\\Parquet\\ParquetFileWriter") } +// MINIT runs before EG(class_table) exists, so the lookup reads CG(class_table), as ensure_class_name_free does +fn registered(name: &str) -> Option<&'static mut ClassEntry> { + let table = unsafe { ext_php_rs_compiler_globals().as_ref() }?.class_table; + + if table.is_null() { + return None; + } + + unsafe { (zend_hash_str_find_ptr_lc(table, name.as_ptr().cast(), name.len()) as *mut ClassEntry).as_mut() } +} + fn method(name: &str, args: Vec>, returns: DataType) -> FunctionBuilder<'static> { args.into_iter() .fold(FunctionBuilder::new_abstract(name), FunctionBuilder::arg) @@ -89,10 +101,17 @@ fn nullable_method(name: &str, args: Vec>, returns: DataType) -> Fu /// package files declare them in that order, and 051 reflects both sides. fn interface( name: &str, + slot: &AtomicPtr, store: fn(&'static mut ClassEntry, ArgInfoTables), methods: Vec>, static_methods: Vec>, ) -> Result<()> { + if let Some(ce) = registered(name) { + slot.store(ce, Ordering::Release); + + return Ok(()); + } + let class = static_methods.into_iter().fold( ClassBuilder::new(name).flags(ClassFlags::Interface).registration(store), |class, method| { @@ -114,6 +133,7 @@ fn interface( pub fn register() -> Result<()> { interface( "Flow\\Parquet\\ParquetFile\\Footer", + &FOOTER_CE, store_footer, vec![ method("metadata", vec![], METADATA), @@ -130,6 +150,7 @@ pub fn register() -> Result<()> { )?; interface( "Flow\\Parquet\\ParquetFileReader", + &PARQUET_FILE_READER_CE, store_parquet_file_reader, vec![ method("close", vec![], DataType::Void), @@ -157,6 +178,7 @@ pub fn register() -> Result<()> { )?; interface( "Flow\\Parquet\\ParquetFileWriter", + &PARQUET_FILE_WRITER_CE, store_parquet_file_writer, vec![ method("close", vec![], DataType::Void), @@ -177,6 +199,7 @@ pub fn register() -> Result<()> { )?; interface( "Flow\\Parquet\\ParquetEngine", + &PARQUET_ENGINE_CE, store_parquet_engine, vec![ nullable_method("normalize", vec![], DataType::Array), diff --git a/src/extension/parquet-engine/src/lib.rs b/src/extension/parquet-engine/src/lib.rs new file mode 100644 index 0000000000..0a33996aed --- /dev/null +++ b/src/extension/parquet-engine/src/lib.rs @@ -0,0 +1,33 @@ +//! Parquet over Flow filesystem streams: one reader, one cast table and one writer, surfaced as the +//! `flow-php/parquet` lib's values (`library`) and as Arrow C Data struct batches (`batch`). + +#[cfg(all(feature = "arrow-names", feature = "flow-php-names"))] +compile_error!("flow-parquet-engine: enable exactly one of the features arrow-names, flow-php-names"); +#[cfg(not(any(feature = "arrow-names", feature = "flow-php-names")))] +compile_error!("flow-parquet-engine: enable exactly one of the features arrow-names, flow-php-names"); + +pub mod batch; +pub mod canonical; +pub mod cells; +pub mod chunks; +pub mod engine; +pub mod error; +pub mod exception; +pub mod filter; +pub mod footer; +pub mod interfaces; +pub mod lib_calls; +#[allow( + non_snake_case, + reason = "PHP takes a parameter name from its Rust identifier: the contracts' are camelCase" +)] +pub mod library; +pub mod options; +pub mod php; +pub mod read; +pub mod render; +pub mod sink; +pub mod source; +pub mod thrift; +pub mod values; +pub mod write; diff --git a/src/extension/arrow-ext/src/parquet/lib_calls.rs b/src/extension/parquet-engine/src/lib_calls.rs similarity index 100% rename from src/extension/arrow-ext/src/parquet/lib_calls.rs rename to src/extension/parquet-engine/src/lib_calls.rs diff --git a/src/extension/arrow-ext/src/parquet/library.rs b/src/extension/parquet-engine/src/library.rs similarity index 93% rename from src/extension/arrow-ext/src/parquet/library.rs rename to src/extension/parquet-engine/src/library.rs index 5307a5f3da..c78596742e 100644 --- a/src/extension/arrow-ext/src/parquet/library.rs +++ b/src/extension/parquet-engine/src/library.rs @@ -17,28 +17,28 @@ use parquet::arrow::ArrowSchemaConverter; use parquet::basic::Type as PhysicalType; use parquet::file::metadata::ParquetMetaData; +use crate::batch; +use crate::cells::{Checked, Classes, ReadCell, Refusal, Scalar, Times, Validated, WriteColumn}; +use crate::chunks::chunk_spans; +use crate::error::Error; +use crate::filter::Raw; +use crate::footer::Footer; use crate::interfaces::{footer_ce, parquet_file_reader_ce, parquet_file_writer_ce}; -use crate::parquet::batch; -use crate::parquet::cells::{Checked, Classes, ReadCell, Refusal, Scalar, Times, Validated, WriteColumn}; -use crate::parquet::chunks::chunk_spans; -use crate::parquet::error::Error; -use crate::parquet::filter::Raw; -use crate::parquet::footer::Footer; -use crate::parquet::lib_calls::{ +use crate::lib_calls::{ call_static, METADATA_FROM_THRIFT, READ_PLAN_TO_EXTENSION, ROW_GROUP_CHUNKS_DECODED, ROW_GROUP_CHUNKS_FROM_THRIFT, SCHEMA_FROM_THRIFT, }; -use crate::parquet::options; -use crate::parquet::read::{ParquetReader, ReadPlan}; -use crate::parquet::sink::PhpSink; -use crate::parquet::source::{PhpSource, PhpStream}; -use crate::parquet::write::ParquetWriter; +use crate::options; use crate::php::{ call_handle, call_method, ce_method_ref, expect_object, find_class, for_each_value, ht_for_each, ht_get, ht_insert, ht_insert_long, read_property, zval_array, zval_long, zval_str, IterableArg, }; +use crate::read::{ParquetReader, ReadPlan}; use crate::render::{exception, parquet_exception, Side}; +use crate::sink::PhpSink; +use crate::source::{PhpSource, PhpStream}; use crate::thrift; +use crate::write::ParquetWriter; const FILE_META_DATA: &str = "Flow\\Parquet\\ThriftModel\\FileMetaData"; /// `FileMetaData::$schema`'s field id. @@ -218,12 +218,17 @@ pub fn batch_size(value: i64) -> PhpResult { }) } -/// `ParquetFileReader::footer()`'s return, typed `Flow\Parquet\Engine\RustParquetFooter`: the class registers before -/// the reader, so the covariant return type is checked. +#[cfg(feature = "arrow-names")] +const FOOTER_CLASS: &str = "Flow\\Parquet\\Engine\\RustParquetFooter"; +#[cfg(feature = "flow-php-names")] +const FOOTER_CLASS: &str = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFooter"; + +/// `ParquetFileReader::footer()`'s return, typed as the footer class of the extension that registers it: the class +/// registers before the reader, so the covariant return type is checked. pub struct FooterObject(Zval); impl IntoZval for FooterObject { - const TYPE: DataType = DataType::object("Flow\\Parquet\\Engine\\RustParquetFooter"); + const TYPE: DataType = DataType::object(FOOTER_CLASS); const NULLABLE: bool = false; fn set_zval(self, zv: &mut Zval, _persistent: bool) -> ZvalResult<()> { @@ -234,10 +239,21 @@ impl IntoZval for FooterObject { } #[php_class] -#[php( - name = "Flow\\Parquet\\Engine\\RustParquetFileReader", - flags = ClassFlags::Final, - implements(ce = parquet_file_reader_ce, stub = "Flow\\Parquet\\ParquetFileReader") +#[cfg_attr( + feature = "arrow-names", + php( + name = "Flow\\Parquet\\Engine\\RustParquetFileReader", + flags = ClassFlags::Final, + implements(ce = parquet_file_reader_ce, stub = "Flow\\Parquet\\ParquetFileReader") + ) +)] +#[cfg_attr( + feature = "flow-php-names", + php( + name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFileReader", + flags = ClassFlags::Final, + implements(ce = parquet_file_reader_ce, stub = "Flow\\Parquet\\ParquetFileReader") + ) )] pub struct RustParquetFileReader { stream: Arc, @@ -391,10 +407,21 @@ impl RustParquetFileReader { } #[php_class] -#[php( - name = "Flow\\Parquet\\Engine\\RustParquetFooter", - flags = ClassFlags::Final, - implements(ce = footer_ce, stub = "Flow\\Parquet\\ParquetFile\\Footer") +#[cfg_attr( + feature = "arrow-names", + php( + name = "Flow\\Parquet\\Engine\\RustParquetFooter", + flags = ClassFlags::Final, + implements(ce = footer_ce, stub = "Flow\\Parquet\\ParquetFile\\Footer") + ) +)] +#[cfg_attr( + feature = "flow-php-names", + php( + name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFooter", + flags = ClassFlags::Final, + implements(ce = footer_ce, stub = "Flow\\Parquet\\ParquetFile\\Footer") + ) )] pub struct RustParquetFooter { /// The stream the footer was read from, named in refusals. @@ -600,10 +627,21 @@ impl IntoZval for Chunk { } #[php_class] -#[php( - name = "Flow\\Arrow\\Parquet\\RustColumnsReader", - flags = ClassFlags::Final, - implements(ce = ce::iterator, stub = "\\Iterator") +#[cfg_attr( + feature = "arrow-names", + php( + name = "Flow\\Arrow\\Parquet\\RustColumnsReader", + flags = ClassFlags::Final, + implements(ce = ce::iterator, stub = "\\Iterator") + ) +)] +#[cfg_attr( + feature = "flow-php-names", + php( + name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpColumnsReader", + flags = ClassFlags::Final, + implements(ce = ce::iterator, stub = "\\Iterator") + ) )] pub struct RustColumnsReader { reader: Option, @@ -790,7 +828,8 @@ impl RustColumnsReader { Ok(self.current.is_some().then_some(self.key)) } - pub fn next(&mut self) -> PhpResult<()> { + #[php(name = "next")] + pub fn advance(&mut self) -> PhpResult<()> { self.start()?; if self.current.is_none() { @@ -842,10 +881,21 @@ fn codec(compression: &Zval) -> PhpResult<&'static str> { } #[php_class] -#[php( - name = "Flow\\Parquet\\Engine\\RustParquetFileWriter", - flags = ClassFlags::Final, - implements(ce = parquet_file_writer_ce, stub = "Flow\\Parquet\\ParquetFileWriter") +#[cfg_attr( + feature = "arrow-names", + php( + name = "Flow\\Parquet\\Engine\\RustParquetFileWriter", + flags = ClassFlags::Final, + implements(ce = parquet_file_writer_ce, stub = "Flow\\Parquet\\ParquetFileWriter") + ) +)] +#[cfg_attr( + feature = "flow-php-names", + php( + name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFileWriter", + flags = ClassFlags::Final, + implements(ce = parquet_file_writer_ce, stub = "Flow\\Parquet\\ParquetFileWriter") + ) )] pub struct RustParquetFileWriter { writer: Option, diff --git a/src/extension/arrow-ext/src/parquet/options.rs b/src/extension/parquet-engine/src/options.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/options.rs rename to src/extension/parquet-engine/src/options.rs index 33233e9249..9bd1a69706 100644 --- a/src/extension/arrow-ext/src/parquet/options.rs +++ b/src/extension/parquet-engine/src/options.rs @@ -14,7 +14,7 @@ use parquet::basic::{BrotliLevel, Compression, Encoding, GzipLevel, Type as Phys use parquet::file::properties::{EnabledStatistics, WriterProperties, WriterVersion, DEFAULT_WRITE_BATCH_SIZE}; use parquet::schema::types::{ColumnPath, SchemaDescriptor}; -use crate::parquet::error::Error; +use crate::error::Error; use crate::php::ht_for_each; /// Field metadata key of a Utf8 field written with the ENUM logical type, which no arrow data type carries. diff --git a/src/extension/arrow-ext/src/php.rs b/src/extension/parquet-engine/src/php.rs similarity index 92% rename from src/extension/arrow-ext/src/php.rs rename to src/extension/parquet-engine/src/php.rs index 6c3adaa318..4fa780111a 100644 --- a/src/extension/arrow-ext/src/php.rs +++ b/src/extension/parquet-engine/src/php.rs @@ -1,6 +1,7 @@ //! PHP-engine plumbing: class-entry/slot lookups, hashtable helpers, calls, and the request-scoped cache of datetime //! handles, timezones and thrift specs. +use std::cell::UnsafeCell; use std::collections::HashMap; use std::rc::Rc; @@ -14,7 +15,7 @@ use ext_php_rs::ffi::{ use ext_php_rs::flags::DataType; use ext_php_rs::prelude::PhpResult; use ext_php_rs::types::{ZendHashTable, ZendObject, ZendStr, Zval}; -use ext_php_rs::zend::{ce, ClassEntry, ExecutorGlobals, Function, ModuleGlobal, ModuleGlobals}; +use ext_php_rs::zend::{ce, ClassEntry, ExecutorGlobals, Function}; use crate::exception::ext_exception; use crate::thrift::Specs; @@ -381,41 +382,43 @@ pub fn timezone(name: &[u8]) -> Result { ) } -/// Per-request state: the `Ctx` cache lives in module globals (per thread on ZTS), is built lazily and is dropped in -/// RSHUTDOWN, while the executor still runs; objects freed after RSHUTDOWN never touch it. +/// Per-request state: the `Ctx` cache lives in a thread local (one per thread, as module globals are on ZTS), is built +/// lazily and is dropped in RSHUTDOWN, while the executor still runs; objects freed after RSHUTDOWN never touch it. #[derive(Default)] pub struct ArrowGlobals { ctx: Option, closed: bool, } -impl ModuleGlobal for ArrowGlobals {} - -pub static GLOBALS: ModuleGlobals = ModuleGlobals::new(); - -pub extern "C" fn request_startup(_type: i32, _module_number: i32) -> i32 { - unsafe { GLOBALS.get_mut() }.closed = false; - - 0 +thread_local! { + static GLOBALS: UnsafeCell = UnsafeCell::new(ArrowGlobals::default()); } -pub extern "C" fn request_shutdown(_type: i32, _module_number: i32) -> i32 { - let globals = unsafe { GLOBALS.get_mut() }; - globals.ctx = None; - globals.closed = true; +/// Called from the RINIT of the extension that registers the crate's classes. +pub fn request_startup() { + GLOBALS.with(|globals| unsafe { &mut *globals.get() }.closed = false); +} - 0 +/// Called from the RSHUTDOWN of the extension that registers the crate's classes. +pub fn request_shutdown() { + GLOBALS.with(|globals| { + let globals = unsafe { &mut *globals.get() }; + globals.ctx = None; + globals.closed = true; + }); } /// The only access to `Ctx`; `f` must not call PHP code, which would alias the `&mut Ctx`. pub fn with_ctx(f: impl FnOnce(&mut Ctx) -> PhpResult) -> PhpResult { - let globals = unsafe { GLOBALS.get_mut() }; + GLOBALS.with(|globals| { + let globals = unsafe { &mut *globals.get() }; - if globals.closed { - return Err(ext_exception("arrow used after request shutdown")); - } + if globals.closed { + return Err(ext_exception("arrow used after request shutdown")); + } - f(globals.ctx.get_or_insert_with(Ctx::default)) + f(globals.ctx.get_or_insert_with(Ctx::default)) + }) } /// An `iterable` argument kept as its zval. ext-php-rs's `Iterable` opens a `zend_object_iterator` for a `Traversable` diff --git a/src/extension/arrow-ext/src/parquet/read.rs b/src/extension/parquet-engine/src/read.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/read.rs rename to src/extension/parquet-engine/src/read.rs index 2e7253522a..e4821e920e 100644 --- a/src/extension/arrow-ext/src/parquet/read.rs +++ b/src/extension/parquet-engine/src/read.rs @@ -22,10 +22,10 @@ use parquet::file::page_index::index_reader::decode_offset_index; use parquet::schema::types::{ColumnDescriptor, SchemaDescriptor}; use parquet::DecodeResult; -use crate::parquet::canonical::{canonical, canonical_type}; -use crate::parquet::error::Error; -use crate::parquet::filter::{PlanPredicate, Raw}; -use crate::parquet::source::{exact, ReadAt}; +use crate::canonical::{canonical, canonical_type}; +use crate::error::Error; +use crate::filter::{PlanPredicate, Raw}; +use crate::source::{exact, ReadAt}; /// The row groups holding a selected row, each with its row-group-local selection - `None` when every row of the /// group is selected - the row filter evaluated on the selected rows, and the rows returned at most, counted after it. @@ -328,52 +328,6 @@ impl ParquetReader { &self.fields } - pub fn next(&mut self) -> Option), Error>> { - let batch = loop { - match self.group.as_mut().and_then(Iterator::next) { - Some(Ok(batch)) => break batch, - Some(Err(error)) => return Some(Err(error.into())), - None => {} - } - - let Some(decoder) = self.decoder.as_mut() else { - match self.start_run() { - Ok(true) => continue, - Ok(false) => return None, - Err(error) => return Some(Err(error)), - } - }; - - match decoder.try_next_reader() { - Ok(DecodeResult::NeedsData(ranges)) => { - if let Err(error) = read_coalesced(self.source.as_ref(), ranges) - .and_then(|(ranges, bytes)| Ok(decoder.push_ranges(ranges, bytes)?)) - { - return Some(Err(error)); - } - } - Ok(DecodeResult::Data(reader)) => { - // pushed reads are coalesced, which PushBuffers never releases on its own - decoder.clear_all_ranges(); - self.group = Some(reader); - } - Ok(DecodeResult::Finished) => self.finish_run(), - Err(error) => return Some(Err(error.into())), - } - }; - - self.returned += batch.num_rows(); - - Some( - self.fields - .iter() - .zip(&self.positions) - .map(|(field, (root, children))| canonical(field, &child(batch.column(*root), children)?)) - .collect::, _>>() - .map(|columns| (batch.num_rows(), columns)), - ) - } - fn start_run(&mut self) -> Result { let remaining_limit = self.limit.map(|limit| limit.saturating_sub(self.returned)); @@ -435,6 +389,56 @@ impl ParquetReader { } } +impl Iterator for ParquetReader { + type Item = Result<(usize, Vec), Error>; + + fn next(&mut self) -> Option { + let batch = loop { + match self.group.as_mut().and_then(Iterator::next) { + Some(Ok(batch)) => break batch, + Some(Err(error)) => return Some(Err(error.into())), + None => {} + } + + let Some(decoder) = self.decoder.as_mut() else { + match self.start_run() { + Ok(true) => continue, + Ok(false) => return None, + Err(error) => return Some(Err(error)), + } + }; + + match decoder.try_next_reader() { + Ok(DecodeResult::NeedsData(ranges)) => { + if let Err(error) = read_coalesced(self.source.as_ref(), ranges) + .and_then(|(ranges, bytes)| Ok(decoder.push_ranges(ranges, bytes)?)) + { + return Some(Err(error)); + } + } + Ok(DecodeResult::Data(reader)) => { + // pushed reads are coalesced, which PushBuffers never releases on its own + decoder.clear_all_ranges(); + self.group = Some(reader); + } + Ok(DecodeResult::Finished) => self.finish_run(), + Err(error) => return Some(Err(error.into())), + } + }; + + self.returned += batch.num_rows(); + + Some( + self.fields + .iter() + .zip(&self.positions) + .map(|(field, (root, children))| canonical(field, &child(batch.column(*root), children)?)) + .collect::, _>>() + .map(|columns| (batch.num_rows(), columns)), + ) + } +} + fn runs(selections: Vec, proven: Vec) -> VecDeque<(Vec, bool)> { let mut runs: VecDeque<(Vec, bool)> = VecDeque::new(); @@ -769,10 +773,10 @@ mod tests { canonical_hint, coalesced, groups_with_unmatched_rows, runs, unsupported_codec, ParquetReader, Projected, ReadPlan, }; - use crate::parquet::error::Error; - use crate::parquet::filter::Raw; - use crate::parquet::footer::Footer; - use crate::parquet::source::fake::Counting; + use crate::error::Error; + use crate::filter::Raw; + use crate::footer::Footer; + use crate::source::fake::Counting; /// Three row groups of 100 rows. fn three_groups() -> ParquetMetaData { @@ -1385,7 +1389,7 @@ mod tests { ParquetReader::open(Arc::clone(&source), footer.meta(), &["b".to_string()], plan, 1_024).unwrap(); let mut values = Vec::new(); - while let Some(batch) = reader.next() { + for batch in reader.by_ref() { values.extend( batch.unwrap().1[0] .as_primitive::() @@ -1502,7 +1506,7 @@ mod tests { fn drained(mut reader: ParquetReader) -> usize { let mut rows = 0; - while let Some(batch) = reader.next() { + for batch in reader.by_ref() { rows += batch.unwrap().0; } @@ -1624,7 +1628,7 @@ mod tests { fn strings(mut reader: ParquetReader) -> Vec { let mut values = Vec::new(); - while let Some(batch) = reader.next() { + for batch in reader.by_ref() { let (_, arrays) = batch.unwrap(); values.extend( arrays[0] diff --git a/src/extension/arrow-ext/src/render.rs b/src/extension/parquet-engine/src/render.rs similarity index 98% rename from src/extension/arrow-ext/src/render.rs rename to src/extension/parquet-engine/src/render.rs index 9752c79e0e..9893b3d8fd 100644 --- a/src/extension/arrow-ext/src/render.rs +++ b/src/extension/parquet-engine/src/render.rs @@ -2,9 +2,9 @@ use ext_php_rs::exception::PhpException; -use crate::parquet::error::Error; -use crate::parquet::source::PhpStream; +use crate::error::Error; use crate::php::{find_class, transparent_exception}; +use crate::source::PhpStream; pub const RUNTIME: &str = "Flow\\Parquet\\Exception\\RuntimeException"; const VALIDATION: &str = "Flow\\Parquet\\Exception\\ValidationException"; diff --git a/src/extension/arrow-ext/src/parquet/sink.rs b/src/extension/parquet-engine/src/sink.rs similarity index 94% rename from src/extension/arrow-ext/src/parquet/sink.rs rename to src/extension/parquet-engine/src/sink.rs index 647b7ce0dc..1fc28f8f05 100644 --- a/src/extension/arrow-ext/src/parquet/sink.rs +++ b/src/extension/parquet-engine/src/sink.rs @@ -3,8 +3,8 @@ use std::io::{self, Write}; use std::sync::Arc; -use crate::parquet::source::PhpStream; use crate::php::zval_str; +use crate::source::PhpStream; pub struct PhpSink { stream: Arc, diff --git a/src/extension/arrow-ext/src/parquet/source.rs b/src/extension/parquet-engine/src/source.rs similarity index 99% rename from src/extension/arrow-ext/src/parquet/source.rs rename to src/extension/parquet-engine/src/source.rs index cfdcae6020..29fe9b26a2 100644 --- a/src/extension/arrow-ext/src/parquet/source.rs +++ b/src/extension/parquet-engine/src/source.rs @@ -16,7 +16,7 @@ use ext_php_rs::zend::ClassEntry; use parquet::errors::ParquetError; use parquet::file::reader::{ChunkReader, Length}; -use crate::parquet::error::Error; +use crate::error::Error; use crate::php::{call_handle_catching, call_method, ce_method_ref, expect_object, zval_long}; use crate::render::{exception, RUNTIME}; diff --git a/src/extension/arrow-ext/src/thrift.rs b/src/extension/parquet-engine/src/thrift.rs similarity index 100% rename from src/extension/arrow-ext/src/thrift.rs rename to src/extension/parquet-engine/src/thrift.rs diff --git a/src/extension/arrow-ext/src/values.rs b/src/extension/parquet-engine/src/values.rs similarity index 100% rename from src/extension/arrow-ext/src/values.rs rename to src/extension/parquet-engine/src/values.rs diff --git a/src/extension/arrow-ext/src/parquet/write.rs b/src/extension/parquet-engine/src/write.rs similarity index 97% rename from src/extension/arrow-ext/src/parquet/write.rs rename to src/extension/parquet-engine/src/write.rs index f8909a59a8..0dc705e120 100644 --- a/src/extension/arrow-ext/src/parquet/write.rs +++ b/src/extension/parquet-engine/src/write.rs @@ -11,10 +11,10 @@ use parquet::errors::ParquetError; use parquet::file::properties::WriterProperties; use parquet::schema::types::{BasicTypeInfo, SchemaDescriptor, Type}; -use crate::parquet::canonical::to_parquet; -use crate::parquet::error::Error; -use crate::parquet::options::ENUM_METADATA_KEY; -use crate::parquet::sink::PhpSink; +use crate::canonical::to_parquet; +use crate::error::Error; +use crate::options::ENUM_METADATA_KEY; +use crate::sink::PhpSink; pub struct ParquetWriter { writer: ArrowWriter, From 9101f26418aa11b4d8bd708753c32c961696f5b2 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Mon, 16 Nov 2026 18:26:34 -0600 Subject: [PATCH 2/3] feat(flow-php/flow-php-ext): Parquet engine of its own, counted by the memory limit - FlowPhpParquetEngine, the adapter default with flow_php - no Arrow C hop between the extensions - ETL without flow_php reads and writes on the PHP engine - arrow-ext without the batch classes, FLOW_ARROW_ABI 3 - redundant variable warnings in ExternalSort --- .github/workflows/job-flow-php-extension.yml | 2 +- documentation/components/adapters/parquet.md | 25 +- .../components/extensions/arrow-ext.md | 17 +- .../components/extensions/flow-php-ext.md | 33 +- documentation/contributing/rust.md | 10 +- documentation/installation/docker.md | 12 +- .../packages/etl-adapter-parquet.md | 7 +- documentation/upgrading.md | 24 + .../Parquet/IO/ConfiguredParquetEngine.php | 10 +- .../Parquet/IO/Extractor/ParquetExtractor.php | 15 +- .../IO/Extractor/ParquetSourceFile.php | 5 +- .../IO/Loader/ParquetFileWriterFactory.php | 21 +- .../Parquet/IO/Loader/ParquetLoader.php | 21 +- .../Tests/Context/ParquetFilesContext.php | 11 +- .../IO/Extractor/ParquetSplitReadTest.php | 10 +- .../Parquet/Tests/Integration/ParquetTest.php | 6 +- .../Unit/IO/ConfiguredParquetEngineTest.php | 36 ++ .../IO/Extractor/ParquetSourceFileTest.php | 13 +- .../Extractor/RustParquetOpenSourceTest.php | 17 +- .../Loader/ParquetFileWriterFactoryTest.php | 29 +- .../Unit/IO/Loader/ParquetLoaderTest.php | 22 +- .../IO/Loader/RustParquetFileWriterTest.php | 13 +- .../Flow/ETL/Kernels/Sort/ExternalSort.php | 4 +- .../Flow/Arrow/Parquet/RustBatchReader.php | 60 --- .../php/Flow/Arrow/RustArrowSchema.php | 32 -- .../php/Flow/Arrow/RustParquetBatch.php | 45 -- .../Parquet/Engine/RustParquetFileWriter.php | 9 - src/extension/arrow-ext/src/lib.rs | 7 +- .../tests/phpt/001_extension_loaded.phpt | 17 +- .../phpt/050_parquet_batch_roundtrip.phpt | 96 ---- .../054_abi_matches_flow_php_parquet.phpt | 2 +- ...allocated_bytes_follow_a_parquet_read.phpt | 8 +- src/extension/flow-php-ext/Cargo.lock | 9 - src/extension/flow-php-ext/Cargo.toml | 1 - src/extension/flow-php-ext/Makefile | 8 +- .../crates/flow-arrow-c/Cargo.toml | 11 - .../crates/flow-arrow-c/src/lib.rs | 455 ------------------ .../IO/Engine/FlowPhpColumnsReader.php | 63 +++ .../IO/Engine/FlowPhpParquetEngine.php | 75 +++ .../IO/Engine/FlowPhpParquetFileReader.php | 63 +++ .../IO/Engine/FlowPhpParquetFileWriter.php | 84 ++++ .../IO/Engine/FlowPhpParquetFooter.php | 67 +++ .../IO/Extractor/RustParquetOpenSource.php | 4 +- .../IO/Loader/RustParquetFileWriter.php | 8 +- .../ETL/Values/Column/RustColumnsBatch.php | 46 -- src/extension/flow-php-ext/src/arrow_c.rs | 159 ------ src/extension/flow-php-ext/src/backend.rs | 16 +- src/extension/flow-php-ext/src/globals.rs | 2 + src/extension/flow-php-ext/src/lib.rs | 12 +- src/extension/flow-php-ext/src/parquet/etl.rs | 159 +++--- src/extension/flow-php-ext/src/parquet/mod.rs | 2 +- .../tests/phpt/001_extension_loaded.phpt | 10 +- .../tests/phpt/068_parquet_read_parity.phpt | 1 - .../tests/phpt/069_parquet_offset_limit.phpt | 7 +- .../phpt/070_parquet_write_roundtrip.phpt | 9 +- .../tests/phpt/071_parquet_no_leaks.phpt | 7 +- .../phpt/072_parquet_allocations_counted.phpt | 32 +- .../phpt/089_parquet_arrow_c_no_leaks.phpt | 103 ---- .../090_parquet_schema_refused_at_open.phpt | 13 +- ...091_parquet_canonical_layout_contract.phpt | 7 +- .../097_parquet_uint64_numeric_string.phpt | 7 +- .../phpt/109_parquet_skipped_rows_parity.phpt | 8 +- .../110_parquet_batch_boundaries_parity.phpt | 8 +- .../123_allocated_bytes_count_arrow_once.phpt | 57 --- .../flow-php-ext/tests/phpt/bootstrap.php | 4 +- src/extension/parquet-engine/src/batch.rs | 333 ------------- src/extension/parquet-engine/src/engine.rs | 2 +- src/extension/parquet-engine/src/lib.rs | 3 +- src/extension/parquet-engine/src/library.rs | 64 ++- .../Engine/Arrow/ReadPlanConverter.php | 3 +- .../Flow/Parquet/Engine/ArrowExtension.php | 2 +- 71 files changed, 782 insertions(+), 1781 deletions(-) delete mode 100644 src/extension/arrow-ext/php/Flow/Arrow/Parquet/RustBatchReader.php delete mode 100644 src/extension/arrow-ext/php/Flow/Arrow/RustArrowSchema.php delete mode 100644 src/extension/arrow-ext/php/Flow/Arrow/RustParquetBatch.php delete mode 100644 src/extension/arrow-ext/tests/phpt/050_parquet_batch_roundtrip.phpt delete mode 100644 src/extension/flow-php-ext/crates/flow-arrow-c/Cargo.toml delete mode 100644 src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs create mode 100644 src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpColumnsReader.php create mode 100644 src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetEngine.php create mode 100644 src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileReader.php create mode 100644 src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileWriter.php create mode 100644 src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFooter.php delete mode 100644 src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustColumnsBatch.php delete mode 100644 src/extension/flow-php-ext/src/arrow_c.rs delete mode 100644 src/extension/flow-php-ext/tests/phpt/089_parquet_arrow_c_no_leaks.phpt delete mode 100644 src/extension/flow-php-ext/tests/phpt/123_allocated_bytes_count_arrow_once.phpt delete mode 100644 src/extension/parquet-engine/src/batch.rs diff --git a/.github/workflows/job-flow-php-extension.yml b/.github/workflows/job-flow-php-extension.yml index 5063757c8a..5bbf1d412d 100644 --- a/.github/workflows/job-flow-php-extension.yml +++ b/.github/workflows/job-flow-php-extension.yml @@ -87,7 +87,7 @@ jobs: - name: Run PHPT tests working-directory: src/extension/flow-php-ext env: *rust-env - run: make test ARROW_SO=../arrow-ext/ext/modules/arrow.so + run: make test - name: Install extension and verify working-directory: src/extension/flow-php-ext diff --git a/documentation/components/adapters/parquet.md b/documentation/components/adapters/parquet.md index c20f9b2a90..b4a1bedc1c 100644 --- a/documentation/components/adapters/parquet.md +++ b/documentation/components/adapters/parquet.md @@ -14,34 +14,35 @@ For the installation instructions, read the [installation page](/documentation/i ## Engines -Without `engine:`, `AdaptiveParquetEngine` opens the file. The loaded extensions, arrow-ext and -[`flow_php`](/documentation/components/extensions/flow-php-ext.md), decide the lane: +Without `engine:`, the loaded extension decides the engine: -| arrow-ext | `flow_php` | Engine | Batches | -|-----------|------------|---------------------|----------------------------------------------------------------------| -| no | no | `PhpParquetEngine` | PHP columns | -| yes | no | `RustParquetEngine` | PHP columns built from the values of arrow-ext | -| no | yes | `PhpParquetEngine` | native columns built from the values of the PHP engine | -| yes | yes | `RustParquetEngine` | batches of arrow-ext directly into native columns, and back on write | +| [`flow_php`](/documentation/components/extensions/flow-php-ext.md) | Engine | Batches | Counted by the memory limit | +|--------------------------------------------------------------------|------------------------|--------------------------------------------------|-----------------------------| +| yes | `FlowPhpParquetEngine` | native columns, read and written in `flow_php` | yes | +| no | `PhpParquetEngine` | PHP columns | yes | -`RustParquetEngine` needs little-endian byte order. Native columns come from the -[column backend](/documentation/components/core/column-backend.md). An explicit engine is always used. -`PhpParquetEngine` does not use arrow-ext: +arrow-ext does not change the default. `FlowPhpParquetEngine` needs little-endian byte order, and other files are read +by `PhpParquetEngine`. Native columns come from the [column backend](/documentation/components/core/column-backend.md). +An explicit engine is always used: ```php read(from_parquet(__DIR__ . '/orders.parquet', engine: new PhpParquetEngine())) + ->read(from_parquet(__DIR__ . '/orders.parquet', engine: new FlowPhpParquetEngine())) ->write(to_parquet(__DIR__ . '/copy.parquet', engine: new PhpParquetEngine())) ->run(); ``` +`engine: new RustParquetEngine()` selects arrow-ext. ETL then builds its columns from PHP values, and a memory limit +does not count the bytes that arrow-ext holds. + Flow `float` columns are written as Parquet `DOUBLE`. ## Schema diff --git a/documentation/components/extensions/arrow-ext.md b/documentation/components/extensions/arrow-ext.md index 969abf29e1..5e864ac823 100644 --- a/documentation/components/extensions/arrow-ext.md +++ b/documentation/components/extensions/arrow-ext.md @@ -38,7 +38,6 @@ The Arrow Rust crates have more I/O features. This extension can add them in the - Nested types: LIST, STRUCT, MAP (arbitrarily nested) - Compression codecs: UNCOMPRESSED, SNAPPY, GZIP, ZSTD, LZ4_RAW, BROTLI - Column projection, offset and limit, from one read of the footer -- Batches that go to other extensions through the [Arrow C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html) ## Requirements @@ -87,7 +86,6 @@ $writer = new Writer(); ```php writeBatch([['id' => 1, 'name' => 'a']]); // an array or any Traversable of rows $writer->writeColumns(['id' => [2, 3], 'name' => ['b', null]]); $writer->close(); // footer, then the stream closed - -$batches = new RustBatchReader($file, ['id', 'name'], 1_000, $plan); // batch size, rows to read -$batches->schema(); // Flow\Arrow\RustArrowSchema -$batches->next(); // Flow\Arrow\RustParquetBatch, null after the last ``` Refusals are the same `Flow\Parquet\Exception\*` that the PHP engine throws. An exception from the stream comes out unchanged. -### Arrow C Data Interface - -`RustParquetBatch` (`RustBatchReader::next()`) carries one struct array: `arrowSchemaAddress()` (`FFI_ArrowSchema*`) and -`arrowArrayAddress()` (`FFI_ArrowArray*`). The consumer is another extension. It reads the schema by reference and -moves the array out. `RustParquetFileWriter::writeArrowBatch()` takes the same pair from a final internal class of -any extension that has both methods. The children of the array match the writer columns by name. Userland code cannot -make either class: the classes are final, and their constructors throw. - ### Native memory ```php ignore @@ -147,7 +133,8 @@ make either class: the classes are final, and their constructors throw. \Flow\Arrow\allocated_bytes(); // int, the bytes the extension holds outside PHP's memory manager in this process ``` -`flow_php` adds these bytes to `RustBackend::allocatedBytes()`, so a memory limit counts them. +A memory limit of Flow ETL does not count these bytes. Flow ETL reads and writes Parquet with the engine of +[`flow_php`](/documentation/components/extensions/flow-php-ext.md), whose bytes the limit counts. ## Development diff --git a/documentation/components/extensions/flow-php-ext.md b/documentation/components/extensions/flow-php-ext.md index 72d27e1c6f..600ff57014 100644 --- a/documentation/components/extensions/flow-php-ext.md +++ b/documentation/components/extensions/flow-php-ext.md @@ -9,8 +9,7 @@ package: flow-php/flow-php-ext [TOC] This extension is the native column backend of Flow. It uses [ext-php-rs](https://github.com/extphprs/ext-php-rs) -to read and write CSV and JSON natively in Rust. It reads and writes Parquet through the -[arrow extension](/documentation/components/extensions/arrow-ext.md). The pure-PHP implementations in `flow-php/etl` +to read and write CSV, JSON and Parquet natively in Rust. The pure-PHP implementations in `flow-php/etl` are the canonical reference for the behaviour, and they work without the extension. The extension only makes Flow faster. @@ -121,17 +120,16 @@ natively with the flags `JSON_THROW_ON_ERROR`, `JSON_UNESCAPED_SLASHES`, `JSON_U ## Parquet -When this extension and the [arrow extension](/documentation/components/extensions/arrow-ext.md) are both loaded, -`from_parquet()` and `to_parquet()` without an `engine:` read and write native columns. arrow-ext reads and writes the -file. Its batches go into `RustColumn`s (and back) through the Arrow C Data Interface. There is no copy and no PHP -value for each cell. +This extension has its own Parquet engine, `Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine`. Without an +`engine:`, `from_parquet()` and `to_parquet()` use it, and the batches are native columns. The memory limit of a run +counts the bytes of the engine, because one allocator holds them. No other extension is needed. -| loaded | `from_parquet()` / `to_parquet()` | -|-----------------|-----------------------------------------------------------------------------| -| flow_php, arrow | native columns through the Arrow C Data Interface | -| arrow | `RustParquetEngine` (arrow-ext), PHP values | -| flow_php | `PhpParquetEngine`, and `RustBackend` adopts the values into native columns | -| neither | `PhpParquetEngine` | +| loaded | `from_parquet()` / `to_parquet()` | +|-----------------|----------------------------------------| +| flow_php | `FlowPhpParquetEngine`, native columns | +| flow_php, arrow | `FlowPhpParquetEngine`, native columns | +| arrow | `PhpParquetEngine`, PHP values | +| neither | `PhpParquetEngine`, PHP values | ```php ../../parquet-engine # The shared Parquet crate, built with feature flow-php-names │ └── flow-numeric-string/ # PHP's is_numeric() grammar @@ -112,9 +110,8 @@ src/extension/parquet-engine/ # Crate flow-parquet-engine: the Parquet code of ├── build.rs # The php84/php85 cfgs └── src/ ├── lib.rs # Module declarations - ├── engine.rs # RustParquetEngine + ├── engine.rs # RustParquetEngine (arrow-names) or FlowPhpParquetEngine (flow-php-names) ├── library.rs # Readers, footer, writer and columns reader as the flow-php/parquet classes - ├── batch.rs # Arrow C Data batches (RustBatchReader, RustParquetBatch, RustArrowSchema) ├── read.rs # ParquetReader: decodes only the row groups and byte ranges a read plan selects ├── filter.rs # The row filter the arrow-rs push decoder runs ├── write.rs # ParquetWriter: canonical arrays cast to the writer schema and written by arrow-rs @@ -182,9 +179,6 @@ The two PHPT runners use the same shell loop: - The runner obeys `--SKIPIF--` blocks and reports the number of skipped tests. - The runner compares the output exactly. It accepts `--EXPECTF--`, but it does not expand `%s`. -`flow-php-ext` also takes `ARROW_SO=`, which loads arrow-ext first. The Parquet ETL phpts then run and do not -skip: `make test ARROW_SO=../arrow-ext/ext/modules/arrow.so`. - ## Rebuilding after a source change `.nix/pkgs/php-arrow-ext` and `.nix/pkgs/php-flow-php-ext` build their extension from the local repository source. diff --git a/documentation/installation/docker.md b/documentation/installation/docker.md index 086788641d..467bc20147 100644 --- a/documentation/installation/docker.md +++ b/documentation/installation/docker.md @@ -73,12 +73,12 @@ The image has PHP 8.5 and the extensions that the Flow adapters need: `bcmath`, `pdo_pgsql`, `pdo_sqlite`, `pgsql`, and the `brotli`, `lz4`, `snappy`, `zstd` codecs. It also has four extensions that Flow detects and uses automatically: -| Extension | Package | Effect of the loaded extension | -|------------|-------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `flow_php` | [flow-php/flow-php-ext](/documentation/components/extensions/flow-php-ext.md) | `AdaptiveBackend` picks `RustBackend` ([Column Backend](/documentation/components/core/column-backend.md)). CSV and JSON are read and written in Rust. With `arrow`, Parquet batches go between the extensions without PHP values | -| `arrow` | [flow-php/arrow-ext](/documentation/components/extensions/arrow-ext.md) | `AdaptiveParquetEngine` picks the `RustParquetEngine` of arrow-ext, so Parquet files are decoded and encoded in Rust | -| `pg_query` | [flow-php/pg-query-ext](/documentation/components/extensions/pg-query-ext.md) | `Flow\PostgreSql\Parser` becomes usable: SQL parsing, normalization and AST manipulation | -| `protobuf` | `pecl/protobuf` | `Flow\PostgreSql\Parser` decodes the parse tree in C instead of pure PHP. Measured ~69x faster end to end | +| Extension | Package | Effect of the loaded extension | +|------------|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `flow_php` | [flow-php/flow-php-ext](/documentation/components/extensions/flow-php-ext.md) | `AdaptiveBackend` picks `RustBackend` ([Column Backend](/documentation/components/core/column-backend.md)). CSV, JSON and Parquet are read and written in Rust, and the memory limit of a run counts the Parquet bytes | +| `arrow` | [flow-php/arrow-ext](/documentation/components/extensions/arrow-ext.md) | `AdaptiveParquetEngine` picks the `RustParquetEngine` of arrow-ext for `flow-php/parquet` used directly. ETL uses it only with an explicit `engine:` | +| `pg_query` | [flow-php/pg-query-ext](/documentation/components/extensions/pg-query-ext.md) | `Flow\PostgreSql\Parser` becomes usable: SQL parsing, normalization and AST manipulation | +| `protobuf` | `pecl/protobuf` | `Flow\PostgreSql\Parser` decodes the parse tree in C instead of pure PHP. Measured ~69x faster end to end | `pdo_pgsql` and `pgsql` link libpq 18 from the PGDG repository. This matches the PostgreSQL 18 grammar of `pg_query`. PHP 8.5 also always compiles in `lexbor`, `uri` and Zend OPcache. diff --git a/documentation/installation/packages/etl-adapter-parquet.md b/documentation/installation/packages/etl-adapter-parquet.md index 4d4cd847f9..1116176c99 100644 --- a/documentation/installation/packages/etl-adapter-parquet.md +++ b/documentation/installation/packages/etl-adapter-parquet.md @@ -23,8 +23,9 @@ composer require flow-php/etl-adapter-parquet:~--FLOW_PHP_VERSION-- ## Optional Extensions -- [arrow-ext](/documentation/installation/packages/arrow-ext.md): parquet files are decoded and encoded in Rust. -- [flow_php](/documentation/installation/packages/flow-php-ext.md): if arrow-ext is also loaded, batches go between - the extensions without PHP values. +- [flow_php](/documentation/installation/packages/flow-php-ext.md): Parquet files are read and written in Rust, and the + memory limit of a run counts their bytes. No other extension is needed. +- [arrow-ext](/documentation/installation/packages/arrow-ext.md): for `flow-php/parquet` used directly, or as an explicit + `engine: new RustParquetEngine()`. A memory limit does not count its bytes. The adapter conflicts with `ext-arrow <0.45` and `ext-flow_php <0.45`. diff --git a/documentation/upgrading.md b/documentation/upgrading.md index 21d9c074f8..b7d066734a 100644 --- a/documentation/upgrading.md +++ b/documentation/upgrading.md @@ -269,6 +269,30 @@ Symfony bundle. | `MemoryLimit::default()` with `memory_limit = -1`: 1 GiB | 4 GiB (`MemoryLimit::WITHOUT_MEMORY_LIMIT_GB = 4`) | | `ExternalSort::reduce(list, KWayMerge, int, ?int)` | `reduce(list>, KWayMerge, int, ?int)`, removes no run | +### 22) `flow-php/etl-adapter-parquet` and `flow-php/flow-php-ext` - with `flow_php`, Parquet has its own engine + +With `flow_php`, the memory limit of a run counts the Parquet bytes. With `arrow` alone, ETL reads and writes on the +PHP engine. + +| Before | After | +|----------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| no `engine:` is `AdaptiveParquetEngine`: `RustParquetEngine` when `arrow` is loaded | `FlowPhpParquetEngine` when `flow_php` is loaded, else `PhpParquetEngine` | +| `arrow` alone: ETL reads and writes on `RustParquetEngine` | `PhpParquetEngine`. Pass `engine: new RustParquetEngine()` to keep `arrow`. A memory limit does not count its bytes | +| both loaded, `engine: new RustParquetEngine()`: batches into native columns through the Arrow C data interface | PHP values from `arrow`, adopted by the backend | +| `RustParquetOpenSource::__construct(RustParquetFileReader $file)` | `__construct(FlowPhpParquetFileReader $file)` | +| `RustParquetFileWriter::__construct(Flow\Parquet\Engine\RustParquetFileWriter $writer, ...)` | `__construct(FlowPhpParquetFileWriter $writer, ...)` | +| `Flow\ETL\Values\Column\RustColumnsBatch` | removed | +| a worker of an extension engine needs the codec extensions | it needs that extension (`flow_php` or `arrow`) and no codec extension | + +### 23) `flow-php/arrow-ext` - the Arrow C data classes are removed + +| Before | After | +|---------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `Flow\Arrow\Parquet\RustBatchReader`, `Flow\Arrow\RustParquetBatch`, `Flow\Arrow\RustArrowSchema` | removed. ETL reads through the `flow_php` engine. `flow-php/parquet` reads with `readColumns()` / `readStoredColumns()` | +| `RustParquetFileWriter::writeArrowBatch()` | removed. Use `writeColumns()` / `writeStoredColumns()` | +| `RustBackend::allocatedBytes()` adds `Flow\Arrow\allocated_bytes()` | it counts the bytes of `flow_php` only, which hold the Parquet bytes of the `flow_php` engine. `Flow\Arrow\allocated_bytes()` stays for the bytes of `arrow` | +| `FLOW_ARROW_ABI` 2 | 3: build `arrow` from the release of `flow-php/parquet` | + --- ## Upgrading from 0.46.x to 0.47.x diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/ConfiguredParquetEngine.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/ConfiguredParquetEngine.php index 0abc41c87f..3081af3cbb 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/ConfiguredParquetEngine.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/ConfiguredParquetEngine.php @@ -18,6 +18,7 @@ use function Flow\Types\DSL\type_array; use function Flow\Types\DSL\type_string; use function is_a; +use function is_string; /** * A parquet engine as its class plus the configuration it normalizes to. @@ -30,7 +31,7 @@ public const array EXTENSIONS = ['bcmath', 'json', 'zlib']; /** - * The codec extensions a file may need: a worker loads the ones the parent reads with. + * The codec extensions a file may need with a PHP engine: a worker loads the ones the parent reads with. */ public const array CODECS = ['brotli', 'lz4', 'snappy', 'zstd']; @@ -53,6 +54,7 @@ public static function fromDescription(#[SensitiveParameter] array $data, Rebuil public function describe(): ?Description { $configuration = $this->engine->normalize(); + $module = (new ReflectionClass($this->engine))->getExtensionName(); return ( $configuration === null @@ -62,7 +64,11 @@ public function describe(): ?Description ['engine' => $this->engine::class, 'configuration' => $configuration], extensions: [ ...self::EXTENSIONS, - ...array_values(array_filter(self::CODECS, extension_loaded(...))), + ...( + is_string($module) + ? [$module] + : array_values(array_filter(self::CODECS, extension_loaded(...))) + ), ], ) ); diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetExtractor.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetExtractor.php index 730bc93b08..8257ac626d 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetExtractor.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetExtractor.php @@ -4,11 +4,13 @@ namespace Flow\ETL\Adapter\Parquet\IO\Extractor; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; use Flow\ETL\Adapter\Parquet\IO\Extractor\Pushdown\FilterTranslator; use Flow\ETL\Adapter\Parquet\Values\Schema\SchemaConverter; use Flow\ETL\Foundation\Exception\CorruptedRecordException; use Flow\ETL\Foundation\Exception\InferredSchemaException; use Flow\ETL\Foundation\Exception\InvalidArgumentException; +use Flow\ETL\Foundation\FlowPhpExtension; use Flow\ETL\Functions\ReferencedColumns; use Flow\ETL\Functions\ScalarFunction; use Flow\ETL\IO\Extractor; @@ -36,7 +38,7 @@ use Flow\Filesystem\Local\NativeLocalFilesystem; use Flow\Filesystem\Path; use Flow\Parquet\Binary\ByteOrder; -use Flow\Parquet\Engine\AdaptiveParquetEngine; +use Flow\Parquet\Engine\PhpParquetEngine; use Flow\Parquet\Options; use Flow\Parquet\ParquetEngine; use Generator; @@ -395,11 +397,18 @@ private function opener(): ParquetSourceFileOpener } /** - * The engine every file of this extractor is opened with: the one passed, else an adaptive one built once. + * The engine every file of this extractor is opened with: the one passed, else the flow_php engine, else the PHP + * engine, built once. */ private function engineInUse(): ParquetEngine { - return $this->openedWith ??= $this->engine ?? new AdaptiveParquetEngine($this->byteOrder, $this->options); + return $this->openedWith ??= + $this->engine + ?? ( + FlowPhpExtension::detect()->available() && $this->byteOrder === ByteOrder::LITTLE_ENDIAN + ? new FlowPhpParquetEngine($this->options) + : new PhpParquetEngine($this->byteOrder, $this->options) + ); } public function withSchema(Schema $schema): static diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetSourceFile.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetSourceFile.php index f5f3075d44..f27b28322c 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetSourceFile.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Extractor/ParquetSourceFile.php @@ -4,6 +4,7 @@ namespace Flow\ETL\Adapter\Parquet\IO\Extractor; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileReader; use Flow\ETL\Adapter\Parquet\Values\Schema\SchemaConverter; use Flow\ETL\Foundation\FlowPhpExtension; use Flow\ETL\IO\Extractor\File\ByteUnit; @@ -12,7 +13,6 @@ use Flow\ETL\IO\Extractor\Statistics; use Flow\ETL\Values\Cardinality; use Flow\ETL\Values\Schema; -use Flow\Parquet\Engine\RustParquetFileReader; use Flow\Parquet\ParquetFile; use Flow\Parquet\ParquetFile\Schema as ParquetSchema; use Flow\Parquet\ParquetFile\Schema\Column; @@ -61,7 +61,8 @@ public function open(): ParquetOpenSource { $reader = $this->file->reader(); - return ($this->extension ?? FlowPhpExtension::detect())->available() && $reader instanceof RustParquetFileReader + return ($this->extension ?? FlowPhpExtension::detect())->available() + && $reader instanceof FlowPhpParquetFileReader ? new RustParquetOpenSource($reader) : new PhpParquetOpenSource($this->file); } diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetFileWriterFactory.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetFileWriterFactory.php index c61a193b24..0f0c4fde4f 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetFileWriterFactory.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetFileWriterFactory.php @@ -4,6 +4,8 @@ namespace Flow\ETL\Adapter\Parquet\IO\Loader; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileWriter; use Flow\ETL\Adapter\Parquet\Values\Schema\SchemaConverter; use Flow\ETL\Foundation\FlowPhpExtension; use Flow\ETL\IO\Loader\File\FileWriter; @@ -12,8 +14,7 @@ use Flow\ETL\Values\Schema; use Flow\Filesystem\DestinationStream; use Flow\Parquet\Binary\ByteOrder; -use Flow\Parquet\Engine\AdaptiveParquetEngine; -use Flow\Parquet\Engine\RustParquetFileWriter as ArrowRustParquetFileWriter; +use Flow\Parquet\Engine\PhpParquetEngine; use Flow\Parquet\Options; use Flow\Parquet\ParquetEngine; use Flow\Parquet\ParquetFile\Compressions; @@ -49,15 +50,15 @@ public function writer(DestinationStream $stream, Schema $schema, Backend $backe $conformance = $this->conformance ??= new ParquetSchemaConformance($parquetSchema); // detected before the engine opens a writer, so a skewed flow_php is refused with nothing opened $native = ($this->extension ?? FlowPhpExtension::detect())->available(); - // the engine decides the lane: a writer it opens on arrow-ext takes the native columns when flow_php is loaded - $file = ($this->engine ?? new AdaptiveParquetEngine(ByteOrder::LITTLE_ENDIAN, $this->options))->openForWrite( - $stream, - $parquetSchema, - $this->compressions, - $this->options, - ); + // a writer of the flow_php engine takes the native columns + $file = ($this->engine + ?? ( + $native + ? new FlowPhpParquetEngine($this->options) + : new PhpParquetEngine(ByteOrder::LITTLE_ENDIAN, $this->options) + ))->openForWrite($stream, $parquetSchema, $this->compressions, $this->options); - return $native && $file instanceof ArrowRustParquetFileWriter + return $file instanceof FlowPhpParquetFileWriter ? new RustParquetFileWriter($file, $conformance, $backend) : new ParquetFileWriter($file, $conformance, $backend); } diff --git a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetLoader.php b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetLoader.php index 6ed77f4762..a6f7bb72fe 100644 --- a/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetLoader.php +++ b/src/adapter/etl-adapter-parquet/src/Flow/ETL/Adapter/Parquet/IO/Loader/ParquetLoader.php @@ -10,6 +10,7 @@ use Flow\ETL\Foundation\Describe\Description; use Flow\ETL\Foundation\Describe\Rebuild; use Flow\ETL\Foundation\Exception\InvalidArgumentException; +use Flow\ETL\Foundation\FlowPhpExtension; use Flow\ETL\Foundation\Progress; use Flow\ETL\IO\Filesystem\SaveMode; use Flow\ETL\IO\Loader\Closure; @@ -32,12 +33,14 @@ use Flow\Parquet\Options; use Flow\Parquet\ParquetEngine; use Flow\Parquet\ParquetFile\Compressions; +use ReflectionClass; use SensitiveParameter; use function extension_loaded; use function Flow\Types\DSL\type_array; use function Flow\Types\DSL\type_enum; use function Flow\Types\DSL\type_string; +use function is_string; final class ParquetLoader implements Closure, Discardable, FileLoader { @@ -112,6 +115,14 @@ public static function fromDescription(#[SensitiveParameter] array $data, Rebuil public function describe(): ?Description { + $codecs = match ($this->compressions) { + Compressions::BROTLI => ['brotli'], + Compressions::LZ4, Compressions::LZ4_RAW => ['lz4'], + Compressions::ZSTD => ['zstd'], + Compressions::SNAPPY => extension_loaded('snappy') ? ['snappy'] : [], + default => [], + }; + return Description::compose( self::class, [ @@ -127,12 +138,10 @@ public function describe(): ?Description ], extensions: [ ...ConfiguredParquetEngine::EXTENSIONS, - ...match ($this->compressions) { - Compressions::BROTLI => ['brotli'], - Compressions::LZ4, Compressions::LZ4_RAW => ['lz4'], - Compressions::ZSTD => ['zstd'], - Compressions::SNAPPY => extension_loaded('snappy') ? ['snappy'] : [], - default => [], + ...match (true) { + $this->engine === null => FlowPhpExtension::detect()->available() ? ['flow_php'] : $codecs, + is_string((new ReflectionClass($this->engine))->getExtensionName()) => [], + default => $codecs, }, ], ); diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Context/ParquetFilesContext.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Context/ParquetFilesContext.php index c004535f51..bbde7ed426 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Context/ParquetFilesContext.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Context/ParquetFilesContext.php @@ -4,6 +4,7 @@ namespace Flow\ETL\Adapter\Parquet\Tests\Context; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; use Flow\ETL\Adapter\Parquet\IO\Extractor\ParquetSourceFileOpener; use Flow\ETL\Adapter\Parquet\IO\Loader\ParquetFileWriter; use Flow\ETL\Adapter\Parquet\IO\Loader\ParquetSchemaConformance; @@ -20,10 +21,7 @@ use Flow\ETL\Values\Rows; use Flow\ETL\Values\Schema as FlowSchema; use Flow\Filesystem\Filesystem; -use Flow\Parquet\Engine\Arrow\OptionsConverter; -use Flow\Parquet\Engine\Arrow\SchemaConverter as ArrowSchemaConverter; use Flow\Parquet\Engine\PhpParquetEngine; -use Flow\Parquet\Engine\RustParquetFileWriter as ArrowRustParquetFileWriter; use Flow\Parquet\Filter\Binding\BoundFilter; use Flow\Parquet\Filter\Filter as ParquetFilter; use Flow\Parquet\Option; @@ -275,12 +273,11 @@ public static function nativeWriter(Filesystem $filesystem, string $uri, FlowSch $parquetSchema = (new SchemaConverter())->toParquetSchema($schema); return new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + (new FlowPhpParquetEngine())->openForWrite( $filesystem->writeTo(path($uri)), - ArrowSchemaConverter::toExtension($parquetSchema), + $parquetSchema, Compressions::SNAPPY, - OptionsConverter::toExtension(Options::default()), - Options::default()->getInt(Option::ARROW_WRITE_BATCH_SIZE), + Options::default(), ), new ParquetSchemaConformance($parquetSchema), new PhpBackend(), diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/IO/Extractor/ParquetSplitReadTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/IO/Extractor/ParquetSplitReadTest.php index d793e715ee..1207468df3 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/IO/Extractor/ParquetSplitReadTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/IO/Extractor/ParquetSplitReadTest.php @@ -6,6 +6,7 @@ use Flow\ETL\Adapter\Parquet\Tests\Context\ParquetFilesContext; use Flow\ETL\Adapter\Parquet\Tests\Double\RecordingParquetEngine; +use Flow\ETL\Foundation\FlowPhpExtension; use Flow\ETL\Tests\Context\DescribeRoundTrip; use Flow\ETL\Tests\Context\ExtractedRows; use Flow\ETL\Tests\Context\ReaderRoundTrip; @@ -69,12 +70,9 @@ public function test_a_memory_filesystem_does_not_describe(): void public function test_the_reader_declares_its_engines_extensions(): void { $root = ReaderRoundTrip::scratch('parquet-extensions'); - $expected = [ - 'bcmath', - 'json', - 'zlib', - ...array_filter(['brotli', 'lz4', 'snappy', 'zstd'], extension_loaded(...)), - ]; + $expected = FlowPhpExtension::detect()->available() + ? ['bcmath', 'flow_php', 'json', 'zlib'] + : ['bcmath', 'json', 'zlib', ...array_filter(['brotli', 'lz4', 'snappy', 'zstd'], extension_loaded(...))]; sort($expected); static::assertSame( diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/ParquetTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/ParquetTest.php index 7b7ab1a117..f5435b4ab8 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/ParquetTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Integration/ParquetTest.php @@ -428,7 +428,11 @@ public function test_arrow_refuses_a_string_that_is_not_valid_utf8(): void data_frame() ->read(from_rows(array_to_rows([['name' => "\xff\xfe"]], schema(str_schema('name'))))) - ->write(to_parquet(path('memory://var/invalid.parquet'), filesystem: memory_filesystem())) + ->write(to_parquet( + path('memory://var/invalid.parquet'), + filesystem: memory_filesystem(), + engine: new RustParquetEngine(), + )) ->run(); } diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php index 33f9b28717..a807c3ca89 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/ConfiguredParquetEngineTest.php @@ -5,6 +5,7 @@ namespace Flow\ETL\Adapter\Parquet\Tests\Unit\IO; use Flow\ETL\Adapter\Parquet\IO\ConfiguredParquetEngine; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; use Flow\ETL\Adapter\Parquet\Tests\Double\RefusingParquetEngine; use Flow\ETL\Foundation\Describe\Rebuild; use Flow\ETL\Foundation\Exception\InvalidArgumentException; @@ -52,6 +53,41 @@ public function test_an_arrow_engine_round_trips(): void ); } + #[RequiresPhpExtension('flow_php')] + public function test_a_flow_php_engine_round_trips(): void + { + $engine = new FlowPhpParquetEngine(Options::default()->set(Option::PAGE_SIZE_BYTES, 7)); + $description = (new ConfiguredParquetEngine($engine))->describe(); + + static::assertNotNull($description); + static::assertSame(FlowPhpParquetEngine::class, $description->data['engine']); + static::assertSame( + $engine->normalize(), + (new Rebuild()) + ->of($description->normalize(), ConfiguredParquetEngine::class) + ->engine() + ->normalize(), + ); + } + + #[RequiresPhpExtension('flow_php')] + public function test_a_flow_php_engine_declares_flow_php_and_no_codec(): void + { + static::assertSame( + ['bcmath', 'flow_php', 'json', 'zlib'], + (new ConfiguredParquetEngine(new FlowPhpParquetEngine()))->describe()?->extensions(), + ); + } + + #[RequiresPhpExtension('arrow')] + public function test_an_arrow_engine_declares_arrow_and_no_codec(): void + { + static::assertSame( + ['arrow', 'bcmath', 'json', 'zlib'], + (new ConfiguredParquetEngine(new RustParquetEngine()))->describe()?->extensions(), + ); + } + public function test_an_engine_without_a_normal_form_does_not_describe(): void { static::assertNull((new ConfiguredParquetEngine(new RefusingParquetEngine()))->describe()); diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/ParquetSourceFileTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/ParquetSourceFileTest.php index 6ead1fd046..a468089f69 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/ParquetSourceFileTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/ParquetSourceFileTest.php @@ -4,6 +4,7 @@ namespace Flow\ETL\Adapter\Parquet\Tests\Unit\IO\Extractor; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; use Flow\ETL\Adapter\Parquet\Tests\Context\ParquetFilesContext; use Flow\ETL\Adapter\Parquet\Tests\Context\ParquetSourceFileContext; use Flow\ETL\Foundation\Exception\RuntimeException; @@ -19,7 +20,6 @@ use Generator; use PHPUnit\Framework\Attributes\RequiresPhpExtension; -use function extension_loaded; use function Flow\ETL\DSL\int_schema; use function Flow\ETL\DSL\schema; use function Flow\ETL\DSL\str_schema; @@ -94,10 +94,9 @@ public function test_a_php_engine_file_opens_the_php_lane(): void } #[RequiresPhpExtension('flow_php')] - #[RequiresPhpExtension('arrow')] - public function test_with_flow_php_a_rust_engine_file_opens_the_rust_lane(): void + public function test_a_flow_php_engine_file_opens_the_rust_lane(): void { - $file = ParquetSourceFileContext::over(new NativeLocalFilesystem(), engine: new RustParquetEngine()); + $file = ParquetSourceFileContext::over(new NativeLocalFilesystem(), engine: new FlowPhpParquetEngine()); $source = $file->open(); static::assertInstanceOf(RustIterator::class, $source->batches( @@ -110,12 +109,8 @@ public function test_with_flow_php_a_rust_engine_file_opens_the_rust_lane(): voi } #[RequiresPhpExtension('arrow')] - public function test_without_flow_php_a_rust_engine_file_opens_the_php_lane(): void + public function test_an_arrow_engine_file_opens_the_php_lane(): void { - if (extension_loaded('flow_php')) { - static::markTestSkipped('flow_php is loaded'); - } - $file = ParquetSourceFileContext::over(new NativeLocalFilesystem(), engine: new RustParquetEngine()); $source = $file->open(); diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/RustParquetOpenSourceTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/RustParquetOpenSourceTest.php index 5369bdd622..8cc3c54512 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/RustParquetOpenSourceTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Extractor/RustParquetOpenSourceTest.php @@ -4,6 +4,7 @@ namespace Flow\ETL\Adapter\Parquet\Tests\Unit\IO\Extractor; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileReader; use Flow\ETL\Adapter\Parquet\IO\Extractor\RustParquetOpenSource; use Flow\ETL\Adapter\Parquet\Tests\Context\ParquetFilesContext; use Flow\ETL\Tests\FlowTestCase; @@ -12,7 +13,6 @@ use Flow\ETL\Values\Column\PhpBackend; use Flow\Filesystem\Exception\RuntimeException; use Flow\Filesystem\Tests\Double\FailingReadSourceStream; -use Flow\Parquet\Engine\RustParquetFileReader; use PHPUnit\Framework\Attributes\RequiresPhpExtension; use PHPUnit\Framework\Attributes\TestWith; @@ -26,7 +26,6 @@ use function range; #[RequiresPhpExtension('flow_php')] -#[RequiresPhpExtension('arrow')] final class RustParquetOpenSourceTest extends FlowTestCase { /** @@ -43,7 +42,7 @@ public function test_a_planned_window_crosses_row_groups(int $offset, ?int $limi $read = []; - foreach ((new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path( + foreach ((new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path( 'memory://groups.parquet', )))))->batches( schema(int_schema('id')), @@ -67,7 +66,7 @@ public function test_an_empty_schema_yields_the_rows_of_the_window(int $offset, $counted = 0; - foreach (ParquetFilesContext::rows((new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path( + foreach (ParquetFilesContext::rows((new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path( 'memory://groups.parquet', )))))->batches( schema(), @@ -90,7 +89,7 @@ public function test_an_empty_schema_yields_the_rows_the_row_filter_keeps(): voi $counted = 0; - foreach (ParquetFilesContext::rows((new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path( + foreach (ParquetFilesContext::rows((new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path( 'memory://groups.parquet', )))))->batches( schema(), @@ -112,7 +111,7 @@ public function test_columns_are_adopted_by_the_backend(): void { $filesystem = memory_filesystem(); ParquetFilesContext::rowGroups($filesystem, 'memory://groups.parquet', 10, 4); - $source = new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path( + $source = new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path( 'memory://groups.parquet', )))); @@ -138,7 +137,7 @@ public function test_a_second_batches_call_closes_the_first_reader(): void { $filesystem = memory_filesystem(); ParquetFilesContext::rowGroups($filesystem, 'memory://groups.parquet', 10, 4); - $source = new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path( + $source = new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path( 'memory://groups.parquet', )))); $first = $source->batches( @@ -172,7 +171,7 @@ public function test_close_before_batches_is_harmless(): void $filesystem = memory_filesystem(); ParquetFilesContext::rowGroups($filesystem, 'memory://groups.parquet', 10, 4); - (new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path( + (new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path( 'memory://groups.parquet', )))))->close(); @@ -187,7 +186,7 @@ public function test_an_exception_the_stream_throws_while_opening_surfaces_as_it $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Reading "memory://groups.parquet" failed'); - new RustParquetOpenSource(new RustParquetFileReader(new FailingReadSourceStream($filesystem->readFrom(path( + new RustParquetOpenSource(new FlowPhpParquetFileReader(new FailingReadSourceStream($filesystem->readFrom(path( 'memory://groups.parquet', ))))); } diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetFileWriterFactoryTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetFileWriterFactoryTest.php index 742f05e0a9..b10d3f99e3 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetFileWriterFactoryTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetFileWriterFactoryTest.php @@ -5,6 +5,7 @@ namespace Flow\ETL\Adapter\Parquet\Tests\Unit\IO\Loader; use Closure; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; use Flow\ETL\Adapter\Parquet\IO\Loader\ParquetFileWriter; use Flow\ETL\Adapter\Parquet\IO\Loader\ParquetFileWriterFactory; use Flow\ETL\Adapter\Parquet\IO\Loader\RustParquetFileWriter; @@ -45,27 +46,37 @@ public static function engines(): iterable } /** - * flow_php's native lane writes only into arrow-ext's writer; every other writer takes PHP columns. + * flow_php's native lane writes only into its own engine's writer; every other writer takes PHP columns. * * @return iterable}> */ public static function lanes(): iterable { - $arrow = extension_loaded('arrow'); - $rust = $arrow && FlowPhpExtension::detect()->available() - ? RustParquetFileWriter::class - : ParquetFileWriter::class; + $flowPhp = FlowPhpExtension::detect()->available(); - yield 'no engine' => [static fn(): ?ParquetEngine => null, $rust]; - yield 'little-endian adaptive engine' => [static fn(): ParquetEngine => new AdaptiveParquetEngine(), $rust]; + yield 'no engine' => [ + static fn(): ?ParquetEngine => null, + $flowPhp ? RustParquetFileWriter::class : ParquetFileWriter::class, + ]; + yield 'little-endian adaptive engine' => [ + static fn(): ParquetEngine => new AdaptiveParquetEngine(), + ParquetFileWriter::class, + ]; yield 'big-endian adaptive engine' => [ static fn(): ParquetEngine => new AdaptiveParquetEngine(ByteOrder::BIG_ENDIAN), ParquetFileWriter::class, ]; yield 'php engine' => [static fn(): ParquetEngine => new PhpParquetEngine(), ParquetFileWriter::class]; - if ($arrow) { - yield 'rust engine' => [static fn(): ParquetEngine => new RustParquetEngine(), $rust]; + if (extension_loaded('arrow')) { + yield 'rust engine' => [static fn(): ParquetEngine => new RustParquetEngine(), ParquetFileWriter::class]; + } + + if ($flowPhp) { + yield 'flow_php engine' => [ + static fn(): ParquetEngine => new FlowPhpParquetEngine(), + RustParquetFileWriter::class, + ]; } } diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetLoaderTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetLoaderTest.php index c9728f8369..de19828681 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetLoaderTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/ParquetLoaderTest.php @@ -8,6 +8,7 @@ use Flow\ETL\Adapter\Parquet\Tests\Context\ParquetFilesContext; use Flow\ETL\Foundation\Describe\Description; use Flow\ETL\Foundation\Exception\RuntimeException; +use Flow\ETL\Foundation\FlowPhpExtension; use Flow\ETL\Foundation\VoidProgress; use Flow\ETL\IO\Filesystem\SaveMode; use Flow\ETL\IO\Loader\File\FileCommit; @@ -238,15 +239,22 @@ public function test_partitioning_returns_what_partition_by_set(): void */ public static function compression_extensions(): Generator { - yield 'gzip' => [Compressions::GZIP, ['bcmath', 'json', 'zlib']]; - yield 'uncompressed' => [Compressions::UNCOMPRESSED, ['bcmath', 'json', 'zlib']]; - yield 'brotli' => [Compressions::BROTLI, ['bcmath', 'brotli', 'json', 'zlib']]; - yield 'lz4' => [Compressions::LZ4, ['bcmath', 'json', 'lz4', 'zlib']]; - yield 'lz4 raw' => [Compressions::LZ4_RAW, ['bcmath', 'json', 'lz4', 'zlib']]; - yield 'zstd' => [Compressions::ZSTD, ['bcmath', 'json', 'zlib', 'zstd']]; + $flowPhp = FlowPhpExtension::detect()->available(); + $engine = ['bcmath', 'flow_php', 'json', 'zlib']; + + yield 'gzip' => [Compressions::GZIP, $flowPhp ? $engine : ['bcmath', 'json', 'zlib']]; + yield 'uncompressed' => [Compressions::UNCOMPRESSED, $flowPhp ? $engine : ['bcmath', 'json', 'zlib']]; + yield 'brotli' => [Compressions::BROTLI, $flowPhp ? $engine : ['bcmath', 'brotli', 'json', 'zlib']]; + yield 'lz4' => [Compressions::LZ4, $flowPhp ? $engine : ['bcmath', 'json', 'lz4', 'zlib']]; + yield 'lz4 raw' => [Compressions::LZ4_RAW, $flowPhp ? $engine : ['bcmath', 'json', 'lz4', 'zlib']]; + yield 'zstd' => [Compressions::ZSTD, $flowPhp ? $engine : ['bcmath', 'json', 'zlib', 'zstd']]; yield 'snappy' => [ Compressions::SNAPPY, - extension_loaded('snappy') ? ['bcmath', 'json', 'snappy', 'zlib'] : ['bcmath', 'json', 'zlib'], + match (true) { + $flowPhp => $engine, + extension_loaded('snappy') => ['bcmath', 'json', 'snappy', 'zlib'], + default => ['bcmath', 'json', 'zlib'], + }, ]; } diff --git a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/RustParquetFileWriterTest.php b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/RustParquetFileWriterTest.php index 6a2f623db8..4eedc9b237 100644 --- a/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/RustParquetFileWriterTest.php +++ b/src/adapter/etl-adapter-parquet/tests/Flow/ETL/Adapter/Parquet/Tests/Unit/IO/Loader/RustParquetFileWriterTest.php @@ -4,6 +4,7 @@ namespace Flow\ETL\Adapter\Parquet\Tests\Unit\IO\Loader; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine; use Flow\ETL\Adapter\Parquet\IO\Loader\ParquetSchemaConformance; use Flow\ETL\Adapter\Parquet\IO\Loader\RustParquetFileWriter; use Flow\ETL\Adapter\Parquet\Tests\Context\ParquetFilesContext; @@ -12,11 +13,7 @@ use Flow\ETL\Values\Column\PhpBackend; use Flow\Filesystem\Exception\RuntimeException as FilesystemRuntimeException; use Flow\Filesystem\Tests\Double\FailingAppendDestinationStream; -use Flow\Parquet\Engine\Arrow\OptionsConverter; -use Flow\Parquet\Engine\Arrow\SchemaConverter as ArrowSchemaConverter; -use Flow\Parquet\Engine\RustParquetFileWriter as ArrowRustParquetFileWriter; use Flow\Parquet\Exception\RuntimeException; -use Flow\Parquet\Option; use Flow\Parquet\Options; use Flow\Parquet\ParquetFile\Compressions; use PHPUnit\Framework\Attributes\RequiresPhpExtension; @@ -30,7 +27,6 @@ use function Flow\Filesystem\DSL\path; #[RequiresPhpExtension('flow_php')] -#[RequiresPhpExtension('arrow')] final class RustParquetFileWriterTest extends FlowTestCase { public function test_a_batch_of_php_columns_reads_back_equal(): void @@ -71,12 +67,11 @@ public function test_an_exception_append_throws_surfaces_as_itself(): void $schema = schema(int_schema('id')); $parquetSchema = (new SchemaConverter())->toParquetSchema($schema); $writer = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + (new FlowPhpParquetEngine())->openForWrite( new FailingAppendDestinationStream($filesystem->writeTo(path('memory://out.parquet'))), - ArrowSchemaConverter::toExtension($parquetSchema), + $parquetSchema, Compressions::SNAPPY, - OptionsConverter::toExtension(Options::default()), - Options::default()->getInt(Option::ARROW_WRITE_BATCH_SIZE), + Options::default(), ), new ParquetSchemaConformance($parquetSchema), new PhpBackend(), diff --git a/src/core/etl/src/Flow/ETL/Kernels/Sort/ExternalSort.php b/src/core/etl/src/Flow/ETL/Kernels/Sort/ExternalSort.php index 33103380dc..3efe93445a 100644 --- a/src/core/etl/src/Flow/ETL/Kernels/Sort/ExternalSort.php +++ b/src/core/etl/src/Flow/ETL/Kernels/Sort/ExternalSort.php @@ -283,7 +283,7 @@ public function merge(array $streams, Backend $backend, MemoryBudget $budget, Ba } // held in a variable, so the keys are still alive when the second measurement runs - $keys = (new RowOrder($this->columns))->keys($first); + $_keys = (new RowOrder($this->columns))->keys($first); $perFrame = $full - $budget->remaining(); // a merge round copies the held rows twice more $remaining = intdiv($full, 2); @@ -351,7 +351,7 @@ public static function coalesced(Generator $rows, int $size, Backend $backend): if ($pending !== []) { $batch = Rows::concat($pending[0]->schema(), $backend, ...$pending); - $pending = []; + unset($pending); yield $batch; } diff --git a/src/extension/arrow-ext/php/Flow/Arrow/Parquet/RustBatchReader.php b/src/extension/arrow-ext/php/Flow/Arrow/Parquet/RustBatchReader.php deleted file mode 100644 index e05a5e2a2d..0000000000 --- a/src/extension/arrow-ext/php/Flow/Arrow/Parquet/RustBatchReader.php +++ /dev/null @@ -1,60 +0,0 @@ - $columns root column names - * @param int<1, max> $batchSize - */ - public function __construct(RustParquetFileReader $file, array $columns, int $batchSize, ReadPlan $plan) - { - throw new RuntimeException('arrow extension is not loaded'); - } - - public function close(): void - { - throw new RuntimeException('arrow extension is not loaded'); - } - - /** - * At most $batchSize rows as one Arrow C Data struct array, null after the last. - */ - public function next(): ?RustParquetBatch - { - throw new RuntimeException('arrow extension is not loaded'); - } - - /** - * The matches the plan's offset skipped: final once next() returned its first batch, or null without one. - * - * @return int<0, max> - */ - public function skipped(): int - { - throw new RuntimeException('arrow extension is not loaded'); - } - - /** - * The struct schema every batch has, before any batch is read. - */ - public function schema(): RustArrowSchema - { - throw new RuntimeException('arrow extension is not loaded'); - } -} diff --git a/src/extension/arrow-ext/php/Flow/Arrow/RustArrowSchema.php b/src/extension/arrow-ext/php/Flow/Arrow/RustArrowSchema.php deleted file mode 100644 index 260d5dc0ca..0000000000 --- a/src/extension/arrow-ext/php/Flow/Arrow/RustArrowSchema.php +++ /dev/null @@ -1,32 +0,0 @@ - ModuleBuilder { .class::() .class::() .class::() - .class::() - .class::() - .class::() } diff --git a/src/extension/arrow-ext/tests/phpt/001_extension_loaded.phpt b/src/extension/arrow-ext/tests/phpt/001_extension_loaded.phpt index 80f841ba90..7bbcfae692 100644 --- a/src/extension/arrow-ext/tests/phpt/001_extension_loaded.phpt +++ b/src/extension/arrow-ext/tests/phpt/001_extension_loaded.phpt @@ -1,12 +1,12 @@ --TEST-- -arrow extension is loaded and the Parquet and Arrow C Data classes are registered +arrow extension is loaded and the Parquet classes are registered --SKIPIF-- --FILE-- isInternal() ? 'internal' : 'userland', ', ', $r->isFinal() ? 'final' : 'open', "\n"; } @@ -14,14 +14,6 @@ foreach (['Flow\Parquet\Engine\RustParquetEngine', 'Flow\Parquet\Engine\RustParq foreach (['Flow\Arrow\Parquet\Reader', 'Flow\Arrow\Parquet\Writer', 'Flow\Arrow\Parquet\Exception'] as $class) { var_dump(class_exists($class, false)); } - -foreach (['Flow\Arrow\RustParquetBatch', 'Flow\Arrow\RustArrowSchema'] as $class) { - try { - new $class(); - } catch (Throwable $e) { - echo $class, ': ', $e->getMessage(), "\n"; - } -} ?> --EXPECT-- bool(true) @@ -29,11 +21,6 @@ Flow\Parquet\Engine\RustParquetEngine: internal, final Flow\Parquet\Engine\RustParquetFileReader: internal, final Flow\Arrow\Parquet\RustColumnsReader: internal, final Flow\Parquet\Engine\RustParquetFileWriter: internal, final -Flow\Arrow\Parquet\RustBatchReader: internal, final -Flow\Arrow\RustParquetBatch: internal, final -Flow\Arrow\RustArrowSchema: internal, final bool(false) bool(false) bool(false) -Flow\Arrow\RustParquetBatch: You cannot instantiate this class from PHP. -Flow\Arrow\RustArrowSchema: You cannot instantiate this class from PHP. diff --git a/src/extension/arrow-ext/tests/phpt/050_parquet_batch_roundtrip.phpt b/src/extension/arrow-ext/tests/phpt/050_parquet_batch_roundtrip.phpt deleted file mode 100644 index d44b79b476..0000000000 --- a/src/extension/arrow-ext/tests/phpt/050_parquet_batch_roundtrip.phpt +++ /dev/null @@ -1,96 +0,0 @@ ---TEST-- -RustBatchReader batches written back through RustParquetFileWriter::writeArrowBatch() read as the file; writer columns the batch lacks are nulls, children the writer lacks are ignored, a batch imports once, userland objects are refused, nothing leaks ---SKIPIF-- - ---FILE-- - ['id' => $i, 'name' => $i % 3 ? "name {$i}" : null, 'tags' => $i % 4 ? [$i, $i + 1] : null], range(0, 249)); - -$roundTrip = static function (Filesystem $filesystem) use ($source, $target, $options, $rows): array { - $writer = new RustParquetFileWriter($filesystem->writeTo(path('memory://source.parquet')), SchemaConverter::toExtension($source), Compressions::SNAPPY, $options, 100); - $writer->writeRows($rows); - $writer->close(); - - $source = new RustParquetFileReader($filesystem->readFrom(path('memory://source.parquet'))); - $batches = new RustBatchReader($source, ['id', 'name', 'tags'], 100, arrow_read_plan($source)); - $schema = $batches->schema(); - $copy = new RustParquetFileWriter($filesystem->writeTo(path('memory://copy.parquet')), SchemaConverter::toExtension($target), Compressions::SNAPPY, $options, 100); - $counts = []; - - while (($batch = $batches->next()) !== null) { - $counts[] = $batch->count(); - $copy->writeArrowBatch($batch); - } - - $copy->close(); - - return [$schema, $counts]; -}; - -$filesystem = memory_filesystem(); -[$schema, $counts] = $roundTrip($filesystem); -$expected = array_map(static fn(array $row): array => ['id' => $row['id'], 'name' => $row['name'], 'missing' => null], $rows); - -echo get_class($schema), ' ', $schema->arrowSchemaAddress() > 0 ? 'has an address' : 'NO ADDRESS', "\n"; -echo 'batches: ', implode(',', $counts), "\n"; -echo 'round trip: ', iterator_to_array(Reader::php()->readStream($filesystem->readFrom(path('memory://copy.parquet')))->values(), false) === $expected ? 'identical' : 'DIFFER', "\n"; - -$source = new RustParquetFileReader($filesystem->readFrom(path('memory://source.parquet'))); -$batches = new RustBatchReader($source, ['id', 'name', 'tags'], 100, arrow_read_plan($source)); -$batch = $batches->next(); -$twice = new RustParquetFileWriter($filesystem->writeTo(path('memory://twice.parquet')), SchemaConverter::toExtension($target), Compressions::SNAPPY, $options, 100); -$twice->writeArrowBatch($batch); -echo arrow_outcome(static fn() => $twice->writeArrowBatch($batch)), "\n"; -echo arrow_outcome(static fn() => $twice->writeArrowBatch(new UserlandBatch())), "\n"; -$twice->close(); - -for ($i = 0; $i < 10; $i++) { - $roundTrip(memory_filesystem()); -} -gc_collect_cycles(); -$baseline = memory_get_usage(false); - -for ($i = 0; $i < 100; $i++) { - $roundTrip(memory_filesystem()); -} -gc_collect_cycles(); - -var_dump(memory_get_usage(false) <= $baseline); -?> ---EXPECT-- -Flow\Arrow\RustArrowSchema has an address -batches: 100,100,50 -round trip: identical -Flow\Parquet\Exception\InvalidArgumentException: Arrow C Data batch is already imported -Flow\Parquet\Exception\InvalidArgumentException: Arrow C Data batch must be an extension's class, got UserlandBatch -bool(true) diff --git a/src/extension/arrow-ext/tests/phpt/054_abi_matches_flow_php_parquet.phpt b/src/extension/arrow-ext/tests/phpt/054_abi_matches_flow_php_parquet.phpt index 5596066c9a..c1cff8e5e4 100644 --- a/src/extension/arrow-ext/tests/phpt/054_abi_matches_flow_php_parquet.phpt +++ b/src/extension/arrow-ext/tests/phpt/054_abi_matches_flow_php_parquet.phpt @@ -31,6 +31,6 @@ $writer->close(); ?> --EXPECT-- bool(true) -int(2) +int(3) bool(true) bool(true) diff --git a/src/extension/arrow-ext/tests/phpt/073_allocated_bytes_follow_a_parquet_read.phpt b/src/extension/arrow-ext/tests/phpt/073_allocated_bytes_follow_a_parquet_read.phpt index dd03f22e3a..01c757094e 100644 --- a/src/extension/arrow-ext/tests/phpt/073_allocated_bytes_follow_a_parquet_read.phpt +++ b/src/extension/arrow-ext/tests/phpt/073_allocated_bytes_follow_a_parquet_read.phpt @@ -6,18 +6,18 @@ Flow\Arrow\allocated_bytes() grows while a batch read from a Parquet file is hel readFrom(path(__DIR__ . '/fixtures/arrow_schema_hints.parquet'))); -$batches = new RustBatchReader($file, ['id', 'plain', 'binary'], 10, arrow_read_plan($file)); -$batch = $batches->next(); +$columns = $file->readColumns(['id', 'plain', 'binary'], 10, arrow_read_plan($file)); +$columns->rewind(); +$chunk = $columns->current(); $held = \Flow\Arrow\allocated_bytes(); -unset($batch, $batches, $file); +unset($chunk, $columns, $file); var_dump(is_int($start)); var_dump($held > $start); diff --git a/src/extension/flow-php-ext/Cargo.lock b/src/extension/flow-php-ext/Cargo.lock index 81bf01a467..0f756819e2 100644 --- a/src/extension/flow-php-ext/Cargo.lock +++ b/src/extension/flow-php-ext/Cargo.lock @@ -690,14 +690,6 @@ dependencies = [ "zlib-rs", ] -[[package]] -name = "flow-arrow-c" -version = "0.1.0" -dependencies = [ - "arrow-array", - "arrow-schema", -] - [[package]] name = "flow-batch-frame" version = "0.1.0" @@ -780,7 +772,6 @@ dependencies = [ "bytes", "ext-php-rs", "ext-php-rs-build", - "flow-arrow-c", "flow-batch-frame", "flow-column-kernels", "flow-column-text", diff --git a/src/extension/flow-php-ext/Cargo.toml b/src/extension/flow-php-ext/Cargo.toml index 7a61beed92..0c488ea5fa 100644 --- a/src/extension/flow-php-ext/Cargo.toml +++ b/src/extension/flow-php-ext/Cargo.toml @@ -19,7 +19,6 @@ arrow-schema.workspace = true arrow-select = "60" bytes = "1" ext-php-rs = "0.16" -flow-arrow-c = { path = "crates/flow-arrow-c" } flow-batch-frame = { path = "crates/flow-batch-frame" } flow-column-kernels = { path = "crates/flow-column-kernels" } flow-column-text = { path = "crates/flow-column-text" } diff --git a/src/extension/flow-php-ext/Makefile b/src/extension/flow-php-ext/Makefile index 81c5495488..12566e2ccf 100644 --- a/src/extension/flow-php-ext/Makefile +++ b/src/extension/flow-php-ext/Makefile @@ -16,10 +16,6 @@ endif CARGO_OUTPUT := target/release/libflow_php.$(LIB_EXT) EXTENSION_SO := $(MODULE_DIR)/flow_php.so -# arrow-ext's built extension: loaded before flow_php in every test run, so the Parquet ETL phpts run instead of skip -ARROW_SO ?= -LOAD_ARROW := $(if $(ARROW_SO),-d extension=$(realpath $(ARROW_SO)),) - .PHONY: all build clean test install rebuild all: build @@ -48,7 +44,7 @@ test: build sed -n '/^--SKIPIF--$$/,/^--FILE--$$/p' "$$f" | sed '1d;$$d' > "$$skipif"; \ skip_out=""; \ if [ -s "$$skipif" ]; then \ - skip_out=$$($(PHP) $(LOAD_ARROW) -d extension=$$(realpath $(EXTENSION_SO)) "$$skipif" 2>&1) || true; \ + skip_out=$$($(PHP) -d extension=$$(realpath $(EXTENSION_SO)) "$$skipif" 2>&1) || true; \ fi; \ rm -f "$$skipif"; \ case "$$skip_out" in skip*) \ @@ -58,7 +54,7 @@ test: build esac; \ sed -n '/^--FILE--$$/,/^--EXPECT/p' "$$f" | sed '1d;$$d' > "$$tmp"; \ expected=$$(sed -n '/^--EXPECT\(F\)\{0,1\}--$$/,$$p' "$$f" | sed '1d' | tr -d '\r'); \ - actual=$$($(PHP) $(LOAD_ARROW) -d extension=$$(realpath $(EXTENSION_SO)) "$$tmp" 2>&1) || true; \ + actual=$$($(PHP) -d extension=$$(realpath $(EXTENSION_SO)) "$$tmp" 2>&1) || true; \ actual=$$(printf '%s' "$$actual" | tr -d '\r'); \ rm -f "$$tmp"; \ if [ "$$actual" = "$$expected" ]; then \ diff --git a/src/extension/flow-php-ext/crates/flow-arrow-c/Cargo.toml b/src/extension/flow-php-ext/crates/flow-arrow-c/Cargo.toml deleted file mode 100644 index 34155679ec..0000000000 --- a/src/extension/flow-php-ext/crates/flow-arrow-c/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "flow-arrow-c" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] - -[dependencies] -arrow-array.workspace = true -arrow-schema.workspace = true diff --git a/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs b/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs deleted file mode 100644 index ae210dc058..0000000000 --- a/src/extension/flow-php-ext/crates/flow-arrow-c/src/lib.rs +++ /dev/null @@ -1,455 +0,0 @@ -//! Batches across the Arrow C Data Interface; imported buffers count in [`imported_bytes`] while they live. - -use std::ffi::{c_char, CStr, CString}; -use std::sync::atomic::{AtomicI64, Ordering}; - -use arrow_array::ffi::{from_ffi_and_data_type, to_ffi, FFI_ArrowArray, FFI_ArrowSchema}; -use arrow_array::{Array, ArrayRef, StructArray}; -use arrow_schema::{ArrowError, DataType, Field, Fields}; - -/// Bytes of the imported batches alive right now: added on import, subtracted when a batch's last buffer drops. -static IMPORTED: AtomicI64 = AtomicI64::new(0); - -pub fn imported_bytes() -> i64 { - IMPORTED.load(Ordering::Relaxed) -} - -/// What an import refuses; nothing was taken from the producer. -#[derive(Debug)] -pub enum Refusal { - NotStruct, - Count { - children: i64, - columns: usize, - }, - Name { - child: String, - column: usize, - }, - /// Column `column` arrives as `child`, which its plan does not store. - Type { - column: usize, - child: Field, - }, - Schema(ArrowError), - Released, - Length { - children: i64, - schema: i64, - }, - Invalid(ArrowError), -} - -/// What every batch of one source must carry, resolved once by [`check`]: the struct type the arrays are imported -/// as, and each child's name and format string as the producer writes them. -#[derive(Debug)] -pub struct Expected { - data_type: DataType, - children: Vec<(CString, CString)>, -} - -// The spec's leading C Data Interface fields: arrow-rs 60 hides them, its accessors panic on a null format. -#[repr(C)] -struct SchemaHead { - format: *const c_char, - name: *const c_char, - metadata: *const c_char, - flags: i64, - n_children: i64, -} - -#[repr(C)] -struct ArrayHead { - length: i64, - null_count: i64, - offset: i64, - n_buffers: i64, - n_children: i64, -} - -fn schema_head(schema: &FFI_ArrowSchema) -> &SchemaHead { - unsafe { &*(schema as *const FFI_ArrowSchema).cast::() } -} - -fn array_head(array: &FFI_ArrowArray) -> &ArrayHead { - unsafe { &*(array as *const FFI_ArrowArray).cast::() } -} - -/// The struct schema `schema`, its children named and typed as `columns` (name, stored type) are. -pub fn check(schema: &FFI_ArrowSchema, columns: &[(&[u8], DataType)]) -> Result { - let head = schema_head(schema); - - if head.format.is_null() || unsafe { CStr::from_ptr(head.format) }.to_bytes() != b"+s" { - return Err(Refusal::NotStruct); - } - - if head.n_children != columns.len() as i64 { - return Err(Refusal::Count { - children: head.n_children, - columns: columns.len(), - }); - } - - let mut fields = Vec::with_capacity(columns.len()); - let mut children = Vec::with_capacity(columns.len()); - - for (column, (child, (name, stored))) in schema.children().zip(columns).enumerate() { - let field = Field::try_from(child).map_err(Refusal::Schema)?; - - if field.name().as_bytes() != *name { - return Err(Refusal::Name { - child: field.name().clone(), - column, - }); - } - - if field.data_type() != stored { - return Err(Refusal::Type { column, child: field }); - } - - let child_head = schema_head(child); - - children.push(( - unsafe { CStr::from_ptr(child_head.name) }.to_owned(), - unsafe { CStr::from_ptr(child_head.format) }.to_owned(), - )); - fields.push(field); - } - - Ok(Expected { - data_type: DataType::Struct(Fields::from(fields)), - children, - }) -} - -/// Refuses a struct schema whose children are not `expected`'s by count, name or format: the per-batch guard, with no -/// `Field` built. -pub fn same_children(schema: &FFI_ArrowSchema, expected: &Expected) -> Result<(), Refusal> { - let head = schema_head(schema); - - if head.format.is_null() || unsafe { CStr::from_ptr(head.format) }.to_bytes() != b"+s" { - return Err(Refusal::NotStruct); - } - - if head.n_children != expected.children.len() as i64 { - return Err(Refusal::Count { - children: head.n_children, - columns: expected.children.len(), - }); - } - - for (column, (child, (name, format))) in schema.children().zip(&expected.children).enumerate() { - let child_head = schema_head(child); - - if unsafe { CStr::from_ptr(child_head.name) } != name.as_c_str() { - return Err(Refusal::Name { - child: String::from_utf8_lossy(unsafe { CStr::from_ptr(child_head.name) }.to_bytes()).into_owned(), - column, - }); - } - - if unsafe { CStr::from_ptr(child_head.format) } != format.as_c_str() { - return Err(Refusal::Type { - column, - child: Field::try_from(child).map_err(Refusal::Schema)?, - }); - } - } - - Ok(()) -} - -/// An imported array: the producer's, moved here, and the bytes it counts while arrow-rs holds its buffers. -struct Counted { - inner: FFI_ArrowArray, - bytes: i64, -} - -/// The forwarder's release: arrow-rs calls it once, when the batch's last buffer drops; dropping `inner` runs the -/// producer's release. -unsafe extern "C" fn counted_release(array: *mut FFI_ArrowArray) { - let Some(array) = (unsafe { array.as_mut() }) else { - return; - }; - let Counted { inner, bytes } = *unsafe { Box::from_raw(array.private_data().cast::()) }; - - IMPORTED.fetch_sub(bytes, Ordering::Relaxed); - drop(inner); - unsafe { array.set_release(None) }; -} - -/// Moves `source` behind the counting forwarder once `schema` passed [`same_children`]; an early refusal takes nothing. -pub fn take( - schema: &FFI_ArrowSchema, - source: &mut FFI_ArrowArray, - expected: &Expected, -) -> Result<(usize, Vec), Refusal> { - same_children(schema, expected)?; - - if source.is_released() { - return Err(Refusal::Released); - } - - let (source_head, head) = (array_head(source), schema_head(schema)); - - if source_head.n_children != head.n_children || source_head.length < 0 { - return Err(Refusal::Length { - children: source_head.n_children, - schema: head.n_children, - }); - } - - let moved = unsafe { std::ptr::read(source) }; - unsafe { source.set_release(None) }; - - let counted = Box::into_raw(Box::new(Counted { inner: moved, bytes: 0 })); - let mut forward = unsafe { std::ptr::read(&(*counted).inner) }; - unsafe { - forward.set_release(Some(counted_release)); - forward.set_private_data(counted.cast()); - } - - let data = unsafe { from_ffi_and_data_type(forward, expected.data_type.clone()) } - .and_then(|data| data.validate().map(|()| data)) - .map_err(Refusal::Invalid)?; - let bytes = data.get_buffer_memory_size() as i64; - - // the forwarder lives in arrow-rs's owner of `data`'s buffers, so `counted` does too - unsafe { (*counted).bytes = bytes }; - IMPORTED.fetch_add(bytes, Ordering::Relaxed); - - let batch = StructArray::from(data); - - Ok((batch.len(), batch.into_parts().1)) -} - -/// `columns` as one struct batch of `rows` rows, every child nullable. -pub fn export(rows: usize, columns: Vec<(String, ArrayRef)>) -> Result<(FFI_ArrowSchema, FFI_ArrowArray), ArrowError> { - let fields = columns - .iter() - .map(|(name, array)| Field::new(name, array.data_type().clone(), true)) - .collect::(); - let arrays = columns.into_iter().map(|(_, array)| array).collect(); - let (array, schema) = - StructArray::try_new_with_length(fields, arrays, None, rows).and_then(|batch| to_ffi(&batch.to_data()))?; - - Ok((schema, array)) -} - -#[cfg(test)] -mod tests { - use std::ffi::c_void; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{Arc, Mutex}; - - use arrow_array::ffi::{to_ffi, FFI_ArrowArray, FFI_ArrowSchema}; - use arrow_array::types::Int64Type; - use arrow_array::{Array, ArrayRef, Int64Array, ListArray, StructArray}; - use arrow_schema::{DataType, Field, Fields}; - - use super::{check, imported_bytes, same_children, take, Expected, Refusal}; - - /// `IMPORTED` is process-wide: the tests that import run one at a time. - static SERIAL: Mutex<()> = Mutex::new(()); - - static RELEASES: AtomicUsize = AtomicUsize::new(0); - - /// The producer: arrow-rs's export, wrapped so its release counts how often it ran. - unsafe extern "C" fn counting_release(array: *mut FFI_ArrowArray) { - let array = unsafe { &mut *array }; - drop(unsafe { Box::from_raw(array.private_data().cast::()) }); - unsafe { array.set_release(None) }; - RELEASES.fetch_add(1, Ordering::SeqCst); - } - - fn columns() -> Vec<(String, ArrayRef)> { - vec![ - ( - "id".to_string(), - Arc::new(Int64Array::from_iter((0..1000).map(|i| (i % 3 != 0).then_some(i)))) as ArrayRef, - ), - ( - "list".to_string(), - Arc::new(ListArray::from_iter_primitive::( - (0..1000).map(|i| (i % 5 != 0).then(|| vec![Some(i), None])), - )) as ArrayRef, - ), - ] - } - - fn produced() -> (FFI_ArrowArray, FFI_ArrowSchema) { - let fields = columns() - .iter() - .map(|(name, array)| Field::new(name, array.data_type().clone(), true)) - .collect::(); - let batch = StructArray::new(fields, columns().into_iter().map(|(_, array)| array).collect(), None); - let (inner, schema) = to_ffi(&batch.to_data()).unwrap(); - let inner = Box::into_raw(Box::new(inner)); - let mut array = unsafe { std::ptr::read(inner) }; - unsafe { - array.set_release(Some(counting_release)); - array.set_private_data(inner.cast::()); - } - - (array, schema) - } - - fn stored() -> Vec<(&'static [u8], DataType)> { - vec![(b"id", DataType::Int64), (b"list", columns()[1].1.data_type().clone())] - } - - /// From a producer whose release is arrow-rs's own, so building it counts no release of `produced()`'s. - fn expected() -> Expected { - let (_, schema) = other_producer(&stored()); - - check(&schema, &stored()).unwrap() - } - - fn imported() -> i64 { - imported_bytes() - } - - #[test] - fn an_imported_batch_counts_its_buffers_until_the_last_one_drops() { - let _serial = SERIAL.lock().unwrap(); - let (mut array, schema) = produced(); - let releases = RELEASES.load(Ordering::SeqCst); - - let (rows, arrays) = take(&schema, &mut array, &expected()).unwrap(); - - assert!(array.release().is_none()); - assert_eq!(rows, 1000); - assert_eq!(arrays.len(), 2); - assert_eq!(arrays[0].as_ref(), columns()[0].1.as_ref()); - assert_eq!(arrays[1].as_ref(), columns()[1].1.as_ref()); - assert_eq!( - imported(), - arrays - .iter() - .map(|array| array.to_data().get_buffer_memory_size() as i64) - .sum::() - ); - - let first = arrays.into_iter().next().unwrap(); - assert!(imported() > 0); - assert_eq!(RELEASES.load(Ordering::SeqCst), releases); - - drop(first); - assert_eq!(imported(), 0); - assert_eq!(RELEASES.load(Ordering::SeqCst), releases + 1); - - drop(array); - drop(schema); - assert_eq!(RELEASES.load(Ordering::SeqCst), releases + 1); - } - - /// `check` refuses the open, `take` through `same_children` refuses the batch; neither moves the array. - fn refused(columns: &[(&[u8], DataType)], refusal: impl Fn(&Refusal) -> bool) { - let _serial = SERIAL.lock().unwrap(); - let (mut array, schema) = produced(); - let releases = RELEASES.load(Ordering::SeqCst); - - assert!(refusal(&check(&schema, columns).unwrap_err())); - - let (_, other) = other_producer(columns); - let expected = check(&other, columns).unwrap(); - - assert!(refusal(&take(&schema, &mut array, &expected).unwrap_err())); - assert_eq!(imported(), 0); - assert!(array.release().is_some()); - assert_eq!(RELEASES.load(Ordering::SeqCst), releases); - - drop(array); - assert_eq!(RELEASES.load(Ordering::SeqCst), releases + 1); - } - - /// A producer whose batch has exactly `columns`. - fn other_producer(columns: &[(&[u8], DataType)]) -> (FFI_ArrowArray, FFI_ArrowSchema) { - let fields = columns - .iter() - .map(|(name, data_type)| Field::new(String::from_utf8_lossy(name), data_type.clone(), true)) - .collect::(); - let arrays = fields - .iter() - .map(|field| arrow_array::new_empty_array(field.data_type())) - .collect::>(); - - to_ffi(&StructArray::new(fields, arrays, None).to_data()).unwrap() - } - - #[test] - fn a_child_of_another_type_is_refused_before_the_move() { - refused( - &[(b"id", DataType::Float64), (b"list", stored()[1].1.clone())], - |refusal| matches!(refusal, Refusal::Type { column: 0, .. }), - ); - } - - #[test] - fn a_child_of_another_name_is_refused_before_the_move() { - refused( - &[(b"id", DataType::Int64), (b"other", stored()[1].1.clone())], - |refusal| matches!(refusal, Refusal::Name { column: 1, .. }), - ); - } - - #[test] - fn same_children_compares_names_and_formats_without_building_fields() { - let _serial = SERIAL.lock().unwrap(); - let (_array, schema) = produced(); - - assert!(same_children(&schema, &expected()).is_ok()); - - let (_, renamed) = other_producer(&[(b"id", DataType::Int64), (b"other", stored()[1].1.clone())]); - assert!(matches!( - same_children(&renamed, &expected()), - Err(Refusal::Name { column: 1, .. }) - )); - - let (_, retyped) = other_producer(&[(b"id", DataType::Float64), (b"list", stored()[1].1.clone())]); - assert!(matches!( - same_children(&retyped, &expected()), - Err(Refusal::Type { column: 0, .. }) - )); - - let (_, fewer) = other_producer(&[(b"id", DataType::Int64)]); - assert!(matches!( - same_children(&fewer, &expected()), - Err(Refusal::Count { - children: 1, - columns: 2 - }) - )); - } - - #[test] - fn another_child_count_is_refused_before_the_move() { - refused(&[(b"id", DataType::Int64)], |refusal| { - matches!( - refusal, - Refusal::Count { - children: 2, - columns: 1 - } - ) - }); - } - - #[test] - fn an_already_imported_batch_is_refused() { - let _serial = SERIAL.lock().unwrap(); - let (mut array, schema) = produced(); - - let (_, arrays) = take(&schema, &mut array, &expected()).unwrap(); - let counted = imported(); - - assert!(matches!( - take(&schema, &mut array, &expected()).unwrap_err(), - Refusal::Released - )); - assert_eq!(imported(), counted); - - drop(arrays); - assert_eq!(imported(), 0); - } -} diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpColumnsReader.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpColumnsReader.php new file mode 100644 index 0000000000..de467f1138 --- /dev/null +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpColumnsReader.php @@ -0,0 +1,63 @@ +>|SkippedMatches> + */ +final class FlowPhpColumnsReader implements Iterator +{ + /** + * @param list $columns root names or struct paths + * @param int<1, max> $batchSize + */ + public function __construct(FlowPhpParquetFileReader $file, array $columns, int $batchSize, ReadPlan $plan) + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * At most $batchSize rows, keyed by $columns; a plan with an offset yields one SkippedMatches first, or alone. + * + * @return null|array>|SkippedMatches + */ + public function current(): array|SkippedMatches|null + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function key(): ?int + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function next(): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function rewind(): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function valid(): bool + { + throw new RuntimeException('flow_php extension is not loaded'); + } +} diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetEngine.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetEngine.php new file mode 100644 index 0000000000..4b9bbd9866 --- /dev/null +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetEngine.php @@ -0,0 +1,75 @@ +> $rows + */ + public function writeRows( + DestinationStream $stream, + Schema $schema, + Compressions $compression, + Options $options, + iterable $rows, + ): void { + throw new RuntimeException('flow_php extension is not loaded'); + } +} diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileReader.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileReader.php new file mode 100644 index 0000000000..dc0e19398b --- /dev/null +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileReader.php @@ -0,0 +1,63 @@ + $columns resolved names, never empty + * @param int $batchSize upper bound of rows per chunk, refused below 1 + */ + public function readColumns(array $columns, int $batchSize, ReadPlan $plan): FlowPhpColumnsReader + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * @param list $columns resolved names, never empty + * @param int $batchSize upper bound of rows per chunk, refused below 1 + */ + public function readStoredColumns(array $columns, int $batchSize, ReadPlan $plan): FlowPhpColumnsReader + { + throw new RuntimeException('flow_php extension is not loaded'); + } +} diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileWriter.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileWriter.php new file mode 100644 index 0000000000..bee12c5487 --- /dev/null +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFileWriter.php @@ -0,0 +1,84 @@ + $schema Flow\Parquet\Engine\Arrow\SchemaConverter::toExtension() + * @param array $options Flow\Parquet\Engine\Arrow\OptionsConverter::toExtension() + * @param int $batchSize rows per written batch; below 1 is refused + * + * @throws \Flow\Parquet\Exception\RuntimeException for Compressions::LZO + */ + public function __construct( + DestinationStream $stream, + array $schema, + Compressions $compression, + array $options, + int $batchSize, + ) { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * Buffered rows, the footer, then the stream closed. + */ + public function close(): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * An array as writeRows() (keys ignored), a Traversable row by row. + * + * @param iterable> $rows + */ + public function writeBatch(iterable $rows): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * @param array> $columns by top-level column name, every list of one length; a writer column + * the array lacks is nulls, a key the writer lacks is ignored + */ + public function writeColumns(array $columns): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function writeStoredColumns(array $columns): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * @param array $row a writer column the row lacks is null + */ + public function writeRow(array $row): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * @param list> $rows + */ + public function writeRows(array $rows): void + { + throw new RuntimeException('flow_php extension is not loaded'); + } +} diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFooter.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFooter.php new file mode 100644 index 0000000000..2f82bf278b --- /dev/null +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Engine/FlowPhpParquetFooter.php @@ -0,0 +1,67 @@ + $columns + */ + public function rowGroupChunks(array $columns): RowGroupChunks + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function rowsNumber(): int + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function schema(): Schema + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * The whole footer, decoded on the first call. + */ + public function thrift(): FileMetaData + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + /** + * Σ row group total_byte_size (uncompressed). + */ + public function totalByteSize(): int + { + throw new RuntimeException('flow_php extension is not loaded'); + } +} diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Extractor/RustParquetOpenSource.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Extractor/RustParquetOpenSource.php index 5738813854..626f8ead75 100644 --- a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Extractor/RustParquetOpenSource.php +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Extractor/RustParquetOpenSource.php @@ -4,11 +4,11 @@ namespace Flow\ETL\Adapter\Parquet\IO\Extractor; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileReader; use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Rows; use Flow\ETL\Values\RustIterator; use Flow\ETL\Values\Schema; -use Flow\Parquet\Engine\RustParquetFileReader; use Flow\Parquet\Reader\ReadPlan; use RuntimeException; @@ -20,7 +20,7 @@ final class RustParquetOpenSource implements ParquetOpenSource { - public function __construct(RustParquetFileReader $file) + public function __construct(FlowPhpParquetFileReader $file) { throw new RuntimeException('flow_php extension is not loaded'); } diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Loader/RustParquetFileWriter.php b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Loader/RustParquetFileWriter.php index 34d5d4755d..8f7f72a6ef 100644 --- a/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Loader/RustParquetFileWriter.php +++ b/src/extension/flow-php-ext/php/Flow/ETL/Adapter/Parquet/IO/Loader/RustParquetFileWriter.php @@ -4,10 +4,10 @@ namespace Flow\ETL\Adapter\Parquet\IO\Loader; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileWriter; use Flow\ETL\IO\Loader\File\FileWriter; use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Rows; -use Flow\Parquet\Engine\RustParquetFileWriter as ArrowRustParquetFileWriter; use RuntimeException; use function extension_loaded; @@ -19,11 +19,11 @@ final class RustParquetFileWriter implements FileWriter { /** - * @param ArrowRustParquetFileWriter $writer arrow-ext's writer, which owns the stream + * @param FlowPhpParquetFileWriter $writer the flow_php engine's writer, which owns the stream * @param Backend $backend the backend a cast column is built with */ public function __construct( - ArrowRustParquetFileWriter $writer, + FlowPhpParquetFileWriter $writer, ParquetSchemaConformance $conformance, Backend $backend, ) { @@ -39,7 +39,7 @@ public function close(): void } /** - * Every column of the conformed rows as one Arrow C Data batch; a writer column the rows lack is written as nulls. + * Every column of the conformed rows; a writer column the rows lack is written as nulls. */ public function write(Rows $rows): void { diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustColumnsBatch.php b/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustColumnsBatch.php deleted file mode 100644 index b40e529355..0000000000 --- a/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustColumnsBatch.php +++ /dev/null @@ -1,46 +0,0 @@ - i64 { - self.rows as i64 - } - - #[php(name = "arrowSchemaAddress")] - pub fn arrow_schema_address(&self) -> i64 { - std::ptr::from_ref(&self.schema) as i64 - } - - #[php(name = "arrowArrayAddress")] - pub fn arrow_array_address(&self) -> i64 { - std::ptr::from_ref(&self.array) as i64 - } -} - -fn refused(refusal: Refusal, columns: &[(Vec, Rc)]) -> PhpException { - let message = match refusal { - Refusal::NotStruct => "Arrow C Data batch must be a struct".to_string(), - Refusal::Count { children, columns } => { - format!("Arrow C Data batch of {children} children does not match the {columns} columns read") - } - Refusal::Name { child, column } => format!( - "Arrow C Data batch child \"{child}\" is not the column \"{}\"", - String::from_utf8_lossy(&columns[column].0) - ), - Refusal::Type { column, child } => { - let (name, plan) = &columns[column]; - let type_name = match call_method(&plan.type_zv, "toString", &mut []) { - Ok(type_name) => type_name, - Err(exception) => return exception, - }; - - format!( - "Parquet column \"{}\" ({}) is read as {}, its schema type {} stores {}", - String::from_utf8_lossy(name), - child.metadata().get(SOURCE_TYPE).map_or("", String::as_str), - child.data_type(), - String::from_utf8_lossy(type_name.zend_str().map_or(&b""[..], |name| name.as_bytes())), - data_type(&plan.kind), - ) - } - Refusal::Schema(error) => format!("Arrow C Data schema is refused: {error}"), - Refusal::Released => "Arrow C Data batch is already imported".to_string(), - Refusal::Length { children, schema } => { - format!("Arrow C Data batch of {children} children does not match its schema of {schema}") - } - Refusal::Invalid(error) => { - format!("Arrow C Data batch is not a valid struct array: {error}") - } - }; - - invalid_argument(message) -} - -/// The object of an exporter's internal class. -fn exporter(carrier: &Zval) -> PhpResult<(&ZendObject, &ClassEntry)> { - let object = carrier - .object() - .ok_or_else(|| invalid_argument("Arrow C Data carrier must be an object".to_string()))?; - let ce = unsafe { object.ce.as_ref() } - .ok_or_else(|| invalid_argument("Arrow C Data carrier has no class".to_string()))?; - - if ce.type_ != ZEND_INTERNAL_CLASS { - return Err(invalid_argument(format!( - "Arrow C Data carrier must be an extension's class, got {}", - ce.name().unwrap_or_default() - ))); - } - - Ok((object, ce)) -} - -/// `$object->$method()` of an address method: a pointer the exporter owns. -fn address(object: &ZendObject, ce: &ClassEntry, method: &str) -> PhpResult { - let address = call_handle_transparent(ce_method_ref(ce, method)?, Some(object), &mut [])?; - - address - .long() - .and_then(|address| usize::try_from(address).ok()) - .filter(|address| *address != 0) - .ok_or_else(|| invalid_argument(format!("Arrow C Data {method}() must return a non-null address"))) -} - -fn stored(columns: &[(Vec, Rc)]) -> Vec<(&[u8], DataType)> { - columns - .iter() - .map(|(name, plan)| (name.as_slice(), data_type(&plan.kind))) - .collect() -} - -/// Refuses a schema carrier (`arrowSchemaAddress()`) whose struct children are not `columns`, by name and stored type; -/// what every batch of the source is then imported as. -pub fn check_schema(schema: &Zval, columns: &[(Vec, Rc)]) -> PhpResult { - let (object, ce) = exporter(schema)?; - let schema = unsafe { &*(address(object, ce, "arrowSchemaAddress")? as *const FFI_ArrowSchema) }; - - check(schema, &stored(columns)).map_err(|refusal| refused(refusal, columns)) -} - -/// The batch `batch` carries (`arrowSchemaAddress()` read by reference, `arrowArrayAddress()` moved): the row count -/// and one array per column of `columns`, as `expected` describes. -pub fn import( - batch: &Zval, - expected: &Expected, - columns: &[(Vec, Rc)], -) -> PhpResult<(usize, Vec)> { - let (object, ce) = exporter(batch)?; - let schema = unsafe { &*(address(object, ce, "arrowSchemaAddress")? as *const FFI_ArrowSchema) }; - let source = unsafe { &mut *(address(object, ce, "arrowArrayAddress")? as *mut FFI_ArrowArray) }; - - take(schema, source, expected).map_err(|refusal| refused(refusal, columns)) -} - -/// `columns` as one struct batch of `rows` rows, every child nullable. -pub fn export(rows: usize, columns: Vec<(String, ArrayRef)>) -> PhpResult { - let (schema, array) = flow_arrow_c::export(rows, columns) - .map_err(|error| invalid_argument(format!("flow_php failed to export an Arrow C Data batch: {error}")))?; - - Ok(RustColumnsBatch { schema, array, rows }) -} diff --git a/src/extension/flow-php-ext/src/backend.rs b/src/extension/flow-php-ext/src/backend.rs index 5ab3af9aa9..f3fef5bb93 100644 --- a/src/extension/flow-php-ext/src/backend.rs +++ b/src/extension/flow-php-ext/src/backend.rs @@ -17,7 +17,7 @@ use ext_php_rs::convert::IntoZval; use ext_php_rs::error::Result as ZvalResult; use ext_php_rs::flags::{ClassFlags, DataType}; use ext_php_rs::prelude::*; -use ext_php_rs::types::{ZendCallable, ZendHashTable, ZendObject, Zval}; +use ext_php_rs::types::{ZendHashTable, ZendObject, Zval}; use flow_batch_frame::column::decode; use flow_batch_frame::frame; use flow_batch_frame::kind::Kind; @@ -545,13 +545,12 @@ impl RustBackend { #[php(name = "allocatedBytes")] pub fn allocated_bytes(&self) -> i64 { - crate::alloc::own_bytes() + arrow_bytes() + crate::alloc::own_bytes() } - /// The arrow bytes count as they are now, not at their own peak: they are another allocator's. #[php(name = "allocatedPeakBytes")] pub fn allocated_peak_bytes(&self) -> i64 { - crate::alloc::own_peak_bytes() + arrow_bytes() + crate::alloc::own_peak_bytes() } #[php(name = "resetAllocatedPeak")] @@ -565,15 +564,6 @@ impl RustBackend { } } -/// The arrow extension's bytes, else the imported batches alone: an imported batch is arrow's memory, so never both. -fn arrow_bytes() -> i64 { - ZendCallable::try_from_name("Flow\\Arrow\\allocated_bytes") - .ok() - .and_then(|callable| callable.try_call(vec![]).ok()) - .and_then(|bytes| bytes.long()) - .unwrap_or_else(flow_arrow_c::imported_bytes) -} - /// The schema and backend every batch of one source is adopted under. pub struct Adoption { schema: Zval, diff --git a/src/extension/flow-php-ext/src/globals.rs b/src/extension/flow-php-ext/src/globals.rs index 6a0d2a9d80..ac0a465f16 100644 --- a/src/extension/flow-php-ext/src/globals.rs +++ b/src/extension/flow-php-ext/src/globals.rs @@ -19,6 +19,7 @@ pub static GLOBALS: ModuleGlobals = ModuleGlobals::new(); pub extern "C" fn request_startup(_type: i32, _module_number: i32) -> i32 { unsafe { GLOBALS.get_mut() }.closed = false; + flow_parquet_engine::php::request_startup(); 0 } @@ -27,6 +28,7 @@ pub extern "C" fn request_shutdown(_type: i32, _module_number: i32) -> i32 { let globals = unsafe { GLOBALS.get_mut() }; globals.ctx = None; globals.closed = true; + flow_parquet_engine::php::request_shutdown(); 0 } diff --git a/src/extension/flow-php-ext/src/lib.rs b/src/extension/flow-php-ext/src/lib.rs index 75dc591a9f..5b3ae92f6a 100644 --- a/src/extension/flow-php-ext/src/lib.rs +++ b/src/extension/flow-php-ext/src/lib.rs @@ -1,6 +1,5 @@ mod alloc; mod arithmetic; -mod arrow_c; mod backend; mod batch_columns; mod builder; @@ -55,6 +54,11 @@ pub unsafe extern "C" fn module_startup(_type: i32, _module_number: i32) -> i32 return -1; } + if let Err(e) = flow_parquet_engine::interfaces::register() { + eprintln!("flow_php: failed to register the Flow\\Parquet interfaces: {e}"); + return -1; + } + 0 } @@ -81,5 +85,9 @@ pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { .class::() .class::() .class::() - .class::() + .class::() + .class::() + .class::() + .class::() + .class::() } diff --git a/src/extension/flow-php-ext/src/parquet/etl.rs b/src/extension/flow-php-ext/src/parquet/etl.rs index 6c50c73d78..f062811818 100644 --- a/src/extension/flow-php-ext/src/parquet/etl.rs +++ b/src/extension/flow-php-ext/src/parquet/etl.rs @@ -1,5 +1,5 @@ //! `Flow\ETL\Adapter\Parquet\{RustParquetOpenSource, RustParquetFileWriter}`: `Rows` of `RustColumn`s straight from -//! arrow-ext's Parquet batches, and any conformed `Rows` straight to its writer, through the Arrow C Data Interface. +//! the batches of the `flow_php` Parquet engine, and any conformed `Rows` straight to its writer, in process. use std::cell::RefCell; use std::rc::Rc; @@ -7,13 +7,18 @@ use std::sync::Arc; use arrow_array::ArrayRef; use arrow_select::concat::concat; -use ext_php_rs::convert::IntoZval; +use ext_php_rs::convert::{FromZvalMut, IntoZval}; use ext_php_rs::flags::ClassFlags; use ext_php_rs::prelude::*; use ext_php_rs::types::{ZendHashTable, Zval}; -use flow_arrow_c::Expected; +use flow_batch_frame::kind::data_type; +use flow_parquet_engine::library::{ + batch_size, read_plan, RustParquetFileReader as EngineFileReader, RustParquetFileWriter as EngineFileWriter, +}; +use flow_parquet_engine::read::ParquetReader; +use flow_parquet_engine::render::{parquet_exception, Side}; +use flow_parquet_engine::source::PhpStream; -use crate::arrow_c; use crate::backend::{adopt_batch, native_column, Adoption, Definitions}; use crate::batch_columns::HeldBatch; use crate::column::RustColumn; @@ -25,18 +30,19 @@ use crate::exception::ext_exception; use crate::interfaces::{file_writer_ce, parquet_open_source_ce}; use crate::iterator::RustIterator; use crate::plan::TypePlan; +use crate::render::invalid_argument; -const FILE_READER: &str = "Flow\\Parquet\\Engine\\RustParquetFileReader"; -const ARROW_FILE_WRITER: &str = "Flow\\Parquet\\Engine\\RustParquetFileWriter"; -const BATCH_READER: &str = "Flow\\Arrow\\Parquet\\RustBatchReader"; const SKIPPED_ROWS: &str = "Flow\\ETL\\IO\\Extractor\\File\\SkippedRows"; type Imported = (usize, Vec); +/// The reader of the last `batches()`: emptied by the next one and by `close()`. +type SharedReader = Rc>>; + // PhpParquetOpenSource fills every batch across row groups, so a group's remainder is carried into the next batch fn next_full_batch( - batches: &Zval, - expected: &Expected, + reader: &SharedReader, + stream: &PhpStream, columns: &[(Vec, Rc)], batch_size: usize, carried: &mut Vec, @@ -49,17 +55,18 @@ fn next_full_batch( return held(full, columns).map(Some); } - let batch = call_method(batches, "next", &mut [])?; + let batch = reader.borrow_mut().as_mut().and_then(Iterator::next); - if batch.is_null() { - return if carried.is_empty() { - Ok(None) - } else { - held(joined(std::mem::take(carried))?, columns).map(Some) - }; + match batch { + None => { + return if carried.is_empty() { + Ok(None) + } else { + held(joined(std::mem::take(carried))?, columns).map(Some) + }; + } + Some(batch) => carried.push(batch.map_err(|error| parquet_exception(error, stream, Side::Read))?), } - - carried.push(arrow_c::import(&batch, expected, columns)?); } } @@ -109,24 +116,36 @@ fn held((count, arrays): Imported, columns: &[(Vec, Rc)]) -> PhpRe Ok(HeldBatch { columns: held, count }) } -fn skipped_rows(batches: &Zval) -> PhpResult { - let count = call_method(batches, "skipped", &mut [])? - .long() - .ok_or_else(|| ext_exception("flow_php expected RustBatchReader::skipped() to return an int"))?; +fn skipped_rows(reader: &SharedReader) -> PhpResult { + let count = reader.borrow().as_ref().map_or(0, ParquetReader::skipped); - Ok(construct(find_class(SKIPPED_ROWS)?, &mut [zval_long(count)])?.into_zval(false)?) + Ok(construct( + find_class(SKIPPED_ROWS)?, + &mut [zval_long(i64::try_from(count).unwrap_or(i64::MAX))], + )? + .into_zval(false)?) } -/// `$object` is arrow-ext's `$class`: the only object whose Arrow state flow_php can read. -fn expect_arrow(object: &Zval, class: &str) -> PhpResult<()> { - if object - .object() - .is_some_and(|object| find_class(class).is_ok_and(|ce| object.instance_of(ce))) - { - return Ok(()); +/// Refuses a column whose stored type is not the one its schema type stores, before any batch. +fn stored_types(reader: &ParquetReader, columns: &[(Vec, Rc)]) -> PhpResult<()> { + for (((name, plan), canonical), field) in columns.iter().zip(reader.types()).zip(reader.fields()) { + if *canonical == data_type(&plan.kind) { + continue; + } + + let type_name = call_method(&plan.type_zv, "toString", &mut [])?; + + return Err(invalid_argument(format!( + "Parquet column \"{}\" ({}) is read as {}, its schema type {} stores {}", + String::from_utf8_lossy(name), + field.data_type(), + canonical, + String::from_utf8_lossy(type_name.zend_str().map_or(&b""[..], |name| name.as_bytes())), + data_type(&plan.kind), + ))); } - Err(ext_exception(format!("flow_php expected a {class}"))) + Ok(()) } #[php_class] @@ -137,15 +156,18 @@ fn expect_arrow(object: &Zval, class: &str) -> PhpResult<()> { )] pub struct RustParquetOpenSource { file: Zval, - /// The `RustBatchReader` of the last `batches()`, closed by the next one and by `close()`. - batches: RefCell>, + batches: RefCell>, } #[php_impl] impl RustParquetOpenSource { - /// `$file`: arrow-ext's `Flow\Parquet\Engine\RustParquetFileReader`, which owns the stream. + /// `$file`: the `flow_php` engine's `FlowPhpParquetFileReader`, which owns the stream. pub fn __construct(file: &Zval) -> PhpResult { - expect_arrow(file, FILE_READER)?; + if file.extract::<&EngineFileReader>().is_none() { + return Err(ext_exception( + "flow_php expected a Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFileReader", + )); + } Ok(Self { file: file.shallow_clone(), @@ -158,30 +180,28 @@ impl RustParquetOpenSource { pub fn batches(&self, schema: &Zval, batchSize: i64, plan: &Zval, backend: &Zval) -> PhpResult { let definitions = Definitions::of(schema)?; let columns = definitions.plans(); - let mut names = ZendHashTable::new(); - - for (name, _) in &columns { - names.push(zval_str(name))?; - } - - let mut names_zv = Zval::new(); - names_zv.set_hashtable(names); + let names = columns + .iter() + .map(|(name, _)| String::from_utf8_lossy(name).into_owned()) + .collect::>(); self.close()?; - let batches = construct( - find_class(BATCH_READER)?, - &mut [ - self.file.shallow_clone(), - names_zv, - zval_long(batchSize), - plan.shallow_clone(), - ], - )? - .into_zval(false)?; - *self.batches.borrow_mut() = Some(batches.shallow_clone()); - - let expected = arrow_c::check_schema(&call_method(&batches, "schema", &mut [])?, &columns)?; + let file = self + .file + .extract::<&EngineFileReader>() + .ok_or_else(|| ext_exception("flow_php expected its FlowPhpParquetFileReader"))?; + let batch_size = batch_size(batchSize)?; + let (stream, meta) = file.read()?; + let stream = Arc::clone(stream); + let read = read_plan(meta, plan, &stream)?; + let reader = ParquetReader::open(Arc::clone(&stream), meta, &names, read, batch_size) + .map_err(|error| parquet_exception(error, &stream, Side::Read))?; + stored_types(&reader, &columns)?; + + let reader: SharedReader = Rc::new(RefCell::new(Some(reader))); + *self.batches.borrow_mut() = Some(Rc::clone(&reader)); + let adoption = Adoption::new(definitions, schema, backend); let mut reports_skipped = read_property(expect_object(plan, "a ReadPlan")?, "offset")? .long() @@ -189,15 +209,13 @@ impl RustParquetOpenSource { > 0; let mut first_rows: Option = None; let mut carried: Vec = Vec::new(); - // RustBatchReader's constructor refused a batch size below 1 - let batch_size = batchSize as usize; Ok(RustIterator::new(Box::new(move || { if let Some(rows) = first_rows.take() { return Ok(Some(rows)); } - let rows = next_full_batch(&batches, &expected, &columns, batch_size, &mut carried)? + let rows = next_full_batch(&reader, &stream, &columns, batch_size, &mut carried)? .map(|batch| adopt_batch(&adoption, batch)) .transpose()?; @@ -208,16 +226,13 @@ impl RustParquetOpenSource { // the reader's count is final once its first batch, or its end, is reached first_rows = rows; - Ok(Some(skipped_rows(&batches)?)) + Ok(Some(skipped_rows(&reader)?)) }))) } pub fn close(&self) -> PhpResult<()> { - // the borrow ends before close() runs PHP - let batches = self.batches.borrow_mut().take(); - - if let Some(batches) = batches { - call_method(&batches, "close", &mut [])?; + if let Some(reader) = self.batches.borrow_mut().take() { + reader.borrow_mut().take(); } Ok(()) @@ -240,7 +255,11 @@ pub struct RustParquetFileWriter { impl RustParquetFileWriter { /// `$writer` owns the stream; `$conformance` and `$backend` come from the run. pub fn __construct(writer: &Zval, conformance: &Zval, backend: &Zval) -> PhpResult { - expect_arrow(writer, ARROW_FILE_WRITER)?; + if writer.extract::<&EngineFileWriter>().is_none() { + return Err(ext_exception( + "flow_php expected a Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFileWriter", + )); + } Ok(Self { writer: writer.shallow_clone(), @@ -282,11 +301,9 @@ impl RustParquetFileWriter { Ok(()) })?; - let mut batch = Zval::new(); - arrow_c::export(count, arrays)?.set_zval(&mut batch, false)?; - call_method(&self.writer, "writeArrowBatch", &mut [batch])?; - - Ok(()) + <&mut EngineFileWriter>::from_zval_mut(&mut self.writer) + .ok_or_else(|| ext_exception("flow_php expected its FlowPhpParquetFileWriter"))? + .write_arrow_columns(count, &arrays) } /// The writer's buffered rows, the footer, then the stream closed. diff --git a/src/extension/flow-php-ext/src/parquet/mod.rs b/src/extension/flow-php-ext/src/parquet/mod.rs index fcf58cca5e..f30842db9b 100644 --- a/src/extension/flow-php-ext/src/parquet/mod.rs +++ b/src/extension/flow-php-ext/src/parquet/mod.rs @@ -1,4 +1,4 @@ -//! Parquet in flow_php: the `Flow\ETL\Adapter\Parquet` surface over arrow-ext's Parquet batches. +//! Parquet in flow_php: the `Flow\ETL\Adapter\Parquet` surface over the `flow_php` Parquet engine. #[allow( non_snake_case, diff --git a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt index 73b0410681..94b3ac767f 100644 --- a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt +++ b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt @@ -26,6 +26,11 @@ interface Flow\ETL\Adapter\JSON\IO\Extractor\JsonOpenSource class Flow\ETL\Adapter\JSON\IO\Extractor\RustJsonOpenSource implements Flow\ETL\Adapter\JSON\IO\Extractor\JsonOpenSource interface Flow\ETL\Adapter\JSON\IO\Loader\JsonEncoder class Flow\ETL\Adapter\JSON\IO\Loader\RustJsonEncoder implements Flow\ETL\Adapter\JSON\IO\Loader\JsonEncoder +class Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpColumnsReader implements Iterator +class Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetEngine implements Flow\Parquet\ParquetEngine +class Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileReader implements Flow\Parquet\ParquetFileReader +class Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileWriter implements Flow\Parquet\ParquetFileWriter +class Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFooter implements Flow\Parquet\ParquetFile\Footer interface Flow\ETL\Adapter\Parquet\IO\Extractor\ParquetOpenSource class Flow\ETL\Adapter\Parquet\IO\Extractor\RustParquetOpenSource implements Flow\ETL\Adapter\Parquet\IO\Extractor\ParquetOpenSource class Flow\ETL\Adapter\Parquet\IO\Loader\RustParquetFileWriter implements Flow\ETL\IO\Loader\File\FileWriter @@ -39,10 +44,13 @@ interface Flow\ETL\Values\Column\GroupedTotals class Flow\ETL\Values\Column\RustBackend implements Flow\ETL\Values\Column\Backend, Flow\ETL\Foundation\Describe\Describable class Flow\ETL\Values\Column\RustColumn implements Flow\ETL\Values\Column\Column class Flow\ETL\Values\Column\RustColumnBuilder implements Flow\ETL\Values\Column\ColumnBuilder -class Flow\ETL\Values\Column\RustColumnsBatch implements class Flow\ETL\Values\Column\RustGroupedCounts implements Flow\ETL\Values\Column\GroupedCounts class Flow\ETL\Values\Column\RustGroupedTotals implements Flow\ETL\Values\Column\GroupedTotals interface Flow\ETL\Values\Grouping\GroupTable class Flow\ETL\Values\Grouping\RustGroupTable implements Flow\ETL\Values\Grouping\GroupTable class Flow\ETL\Values\RustIterator implements Iterator +interface Flow\Parquet\ParquetEngine +interface Flow\Parquet\ParquetFileReader +interface Flow\Parquet\ParquetFileWriter +interface Flow\Parquet\ParquetFile\Footer bool(true) diff --git a/src/extension/flow-php-ext/tests/phpt/068_parquet_read_parity.phpt b/src/extension/flow-php-ext/tests/phpt/068_parquet_read_parity.phpt index 89c862f0e6..8f71694645 100644 --- a/src/extension/flow-php-ext/tests/phpt/068_parquet_read_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/068_parquet_read_parity.phpt @@ -2,7 +2,6 @@ RustParquetOpenSource reads every lib Parquet fixture as PhpParquetEngine does, both refuse it, or it refuses naming the engine that reads it --SKIPIF-- - --FILE-- - --FILE-- writeTo(path('memory://groups.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), Compressions::SNAPPY, @@ -64,7 +63,7 @@ foreach ([0, -1] as $batchSize) { echo outcome(static fn() => rust_parquet_batches($filesystem->readFrom(path('memory://groups.parquet')), $schema, $batchSize)), "\n"; } -echo outcome(static fn() => (new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path('memory://groups.parquet')))))->batches($schema, 10, ReadPlan::window(100, new InMemoryIndexes()), new RustBackend())), "\n"; +echo outcome(static fn() => (new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path('memory://groups.parquet')))))->batches($schema, 10, ReadPlan::window(100, new InMemoryIndexes()), new RustBackend())), "\n"; ?> --EXPECT-- row groups: 8192,8192,8192,8192,8192,8192,8192,8192 diff --git a/src/extension/flow-php-ext/tests/phpt/070_parquet_write_roundtrip.phpt b/src/extension/flow-php-ext/tests/phpt/070_parquet_write_roundtrip.phpt index fcb0cc04c8..988e88f8c6 100644 --- a/src/extension/flow-php-ext/tests/phpt/070_parquet_write_roundtrip.phpt +++ b/src/extension/flow-php-ext/tests/phpt/070_parquet_write_roundtrip.phpt @@ -2,13 +2,12 @@ RustParquetFileWriter writes native and PHP columns that PhpParquetEngine reads back equal, and refuses a string that is not valid UTF-8 --SKIPIF-- - --FILE-- backend(new PhpBackend())->build()); $write = static function (Schema $schema, array $batches): void { $writer = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + new FlowPhpParquetFileWriter( memory_filesystem()->writeTo(path('memory://unused.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), Compressions::ZSTD, @@ -76,7 +75,7 @@ $write = static function (Schema $schema, array $batches): void { $filesystem = memory_filesystem(); $writer = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + new FlowPhpParquetFileWriter( $filesystem->writeTo(path('memory://roundtrip.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), Compressions::ZSTD, @@ -100,7 +99,7 @@ var_dump(comparable($read) === comparable([...php_rows($schema, $values)->toArra $partial = memory_filesystem(); $partialWriter = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + new FlowPhpParquetFileWriter( $partial->writeTo(path('memory://partial.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema(schema(int_schema('id'), str_schema('name', nullable: true)))), Compressions::SNAPPY, diff --git a/src/extension/flow-php-ext/tests/phpt/071_parquet_no_leaks.phpt b/src/extension/flow-php-ext/tests/phpt/071_parquet_no_leaks.phpt index 95855e55df..eb5475261c 100644 --- a/src/extension/flow-php-ext/tests/phpt/071_parquet_no_leaks.phpt +++ b/src/extension/flow-php-ext/tests/phpt/071_parquet_no_leaks.phpt @@ -2,12 +2,11 @@ RustParquetOpenSource and RustParquetFileWriter leak neither PHP memory nor native allocations, refusals included --SKIPIF-- - --FILE-- 1, 'name' => "\xff", 'tags' => []]]; $cycle = static function () use ($schema, $values, $extension, $conformance, $options, $mismatched, $invalid): void { $filesystem = memory_filesystem(); - $writer = new RustParquetFileWriter(new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://leaks.parquet')), $extension, Compressions::SNAPPY, $options, 1_000), $conformance, new PhpBackend()); + $writer = new RustParquetFileWriter(new FlowPhpParquetFileWriter($filesystem->writeTo(path('memory://leaks.parquet')), $extension, Compressions::SNAPPY, $options, 1_000), $conformance, new PhpBackend()); $writer->write(native_rows($schema, $values)); $writer->write(php_rows($schema, $values)); $writer->close(); @@ -43,7 +42,7 @@ $cycle = static function () use ($schema, $values, $extension, $conformance, $op foreach ($reader as $_) { } - $refused = new RustParquetFileWriter(new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://refused.parquet')), $extension, Compressions::SNAPPY, $options, 1_000), $conformance, new PhpBackend()); + $refused = new RustParquetFileWriter(new FlowPhpParquetFileWriter($filesystem->writeTo(path('memory://refused.parquet')), $extension, Compressions::SNAPPY, $options, 1_000), $conformance, new PhpBackend()); try { $refused->write(native_rows($schema, $invalid)); diff --git a/src/extension/flow-php-ext/tests/phpt/072_parquet_allocations_counted.phpt b/src/extension/flow-php-ext/tests/phpt/072_parquet_allocations_counted.phpt index 9c3f185b31..bd7eb96b74 100644 --- a/src/extension/flow-php-ext/tests/phpt/072_parquet_allocations_counted.phpt +++ b/src/extension/flow-php-ext/tests/phpt/072_parquet_allocations_counted.phpt @@ -1,36 +1,32 @@ --TEST-- -Batches RustParquetOpenSource holds are counted by RustBackend::allocatedBytes(): at least their columns' buffer bytes, and nothing once they are released +Batches RustParquetOpenSource holds over the flow_php engine are counted by RustBackend::allocatedBytes(): at least their columns' buffer bytes, and nothing once they are released --SKIPIF-- - --FILE-- toParquetSchema($schema); +$engine = new FlowPhpParquetEngine(); $filesystem = memory_filesystem(); $writer = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( - $filesystem->writeTo(path('memory://held.parquet')), - ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), - Compressions::SNAPPY, - OptionsConverter::toExtension(Options::default()), - 1_000, - ), - new ParquetSchemaConformance((new SchemaConverter())->toParquetSchema($schema)), + $engine->openForWrite($filesystem->writeTo(path('memory://held.parquet')), $parquetSchema, Compressions::SNAPPY, Options::default()), + new ParquetSchemaConformance($parquetSchema), new PhpBackend(), ); @@ -42,14 +38,20 @@ $writer->close(); gc_collect_cycles(); $before = (new RustBackend())->allocatedBytes(); -$reader = rust_parquet_batches($filesystem->readFrom(path('memory://held.parquet')), $schema, 1_000); +$file = $engine->openForRead($filesystem->readFrom(path('memory://held.parquet'))); +$reader = (new RustParquetOpenSource($file))->batches( + $schema, + 1_000, + ReadPlan::window($file->footer()->rowsNumber(), new InMemoryIndexes()), + new RustBackend(), +); $held = []; foreach ($reader as $batch) { $held[] = $batch; } -unset($reader); +unset($reader, $file); gc_collect_cycles(); $bufferBytes = 0; diff --git a/src/extension/flow-php-ext/tests/phpt/089_parquet_arrow_c_no_leaks.phpt b/src/extension/flow-php-ext/tests/phpt/089_parquet_arrow_c_no_leaks.phpt deleted file mode 100644 index 6eeb82f95c..0000000000 --- a/src/extension/flow-php-ext/tests/phpt/089_parquet_arrow_c_no_leaks.phpt +++ /dev/null @@ -1,103 +0,0 @@ ---TEST-- -Batches crossing to and from arrow-ext through the Arrow C Data Interface leak neither PHP memory nor native allocations: abandoned, never imported, imported twice, refused before and after export, writer dropped unclosed ---SKIPIF-- - - ---FILE-- -toParquetSchema($schema); -$extension = ArrowSchemaConverter::toExtension($parquetSchema); -$conformance = new ParquetSchemaConformance($parquetSchema); -$options = OptionsConverter::toExtension(Options::default()); -$values = array_map(static fn(int $i): array => ['id' => $i, 'name' => $i % 3 ? "name {$i}" : null, 'tags' => $i % 4 ? [$i, null] : null], range(0, 99)); -// built once: a fresh Type object per cycle would grow flow_php's type-plan cache, which is bounded, not leaked -$rows = native_rows($schema, $values); -$invalid = native_rows($schema, [['id' => 1, 'name' => "\xff", 'tags' => null]]); -$mismatched = schema(str_schema('id')); - -$cycle = static function () use ($schema, $extension, $conformance, $options, $rows, $invalid, $mismatched): void { - $filesystem = memory_filesystem(); - $writer = new RustParquetFileWriter(new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://leaks.parquet')), $extension, Compressions::SNAPPY, $options, 30), $conformance, new PhpBackend()); - $writer->write($rows); - $writer->write($rows); - $writer->close(); - - $reader = rust_parquet_batches($filesystem->readFrom(path('memory://leaks.parquet')), $schema, 30); - - foreach ($reader as $_) { - } - - $abandoned = rust_parquet_batches($filesystem->readFrom(path('memory://leaks.parquet')), $schema, 30); - $abandoned->rewind(); - unset($abandoned); - - $file = new RustParquetFileReader($filesystem->readFrom(path('memory://leaks.parquet'))); - $batches = new RustBatchReader($file, ['id', 'name', 'tags'], 30, ReadPlan::window($file->footer()->rowsNumber(), new InMemoryIndexes())); - $batches->next(); - $twice = $batches->next(); - $copy = new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://copy.parquet')), $extension, Compressions::SNAPPY, $options, 30); - $copy->writeArrowBatch($twice); - - try { - $copy->writeArrowBatch($twice); - throw new LogicException('a batch was imported twice'); - } catch (Flow\Parquet\Exception\InvalidArgumentException) { - } - - $copy->close(); - - try { - rust_parquet_batches($filesystem->readFrom(path('memory://leaks.parquet')), $mismatched, 30); - throw new LogicException('a string schema read an int column'); - } catch (Flow\ETL\Foundation\Exception\InvalidArgumentException) { - } - - $refused = new RustParquetFileWriter(new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://refused.parquet')), $extension, Compressions::SNAPPY, $options, 30), $conformance, new PhpBackend()); - - try { - $refused->write($invalid); - throw new LogicException('invalid UTF-8 was written'); - } catch (Flow\Parquet\Exception\RuntimeException) { - } - - $unclosed = new RustParquetFileWriter(new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://unclosed.parquet')), $extension, Compressions::SNAPPY, $options, 30), $conformance, new PhpBackend()); - $unclosed->write($rows); -}; - -for ($i = 0; $i < 10; $i++) { - $cycle(); -} -gc_collect_cycles(); -$baseline = memory_get_usage(false); -$baselineRust = (new RustBackend())->allocatedBytes(); - -for ($i = 0; $i < 200; $i++) { - $cycle(); -} -gc_collect_cycles(); - -var_dump(memory_get_usage(false) <= $baseline); -var_dump((new RustBackend())->allocatedBytes() === $baselineRust); -?> ---EXPECT-- -bool(true) -bool(true) diff --git a/src/extension/flow-php-ext/tests/phpt/090_parquet_schema_refused_at_open.phpt b/src/extension/flow-php-ext/tests/phpt/090_parquet_schema_refused_at_open.phpt index 3dfee2f616..087e5d501b 100644 --- a/src/extension/flow-php-ext/tests/phpt/090_parquet_schema_refused_at_open.phpt +++ b/src/extension/flow-php-ext/tests/phpt/090_parquet_schema_refused_at_open.phpt @@ -1,13 +1,12 @@ --TEST-- -RustParquetOpenSource refuses a schema type that stores another arrow type when batches() is called, before any batch: over a zero-row file and past the end of an 8-row-group file; a file other than RustParquetFileReader and a writer other than RustParquetFileWriter are refused +RustParquetOpenSource refuses a schema type that stores another arrow type when batches() is called, before any batch: over a zero-row file and past the end of an 8-row-group file; a file other than FlowPhpParquetFileReader and a writer other than FlowPhpParquetFileWriter are refused --SKIPIF-- - --FILE-- toParquetSchema($schema)); -$empty = new ArrowRustParquetFileWriter($filesystem->writeTo(path('memory://empty.parquet')), $extension, Compressions::SNAPPY, OptionsConverter::toExtension(Options::default()), 10); +$empty = new FlowPhpParquetFileWriter($filesystem->writeTo(path('memory://empty.parquet')), $extension, Compressions::SNAPPY, OptionsConverter::toExtension(Options::default()), 10); $empty->close(); $groups = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + new FlowPhpParquetFileWriter( $filesystem->writeTo(path('memory://groups.parquet')), $extension, Compressions::SNAPPY, @@ -52,5 +51,5 @@ echo outcome(static fn() => new Flow\ETL\Adapter\Parquet\IO\Loader\RustParquetFi --EXPECT-- Flow\ETL\Foundation\Exception\InvalidArgumentException: Parquet column "id" (Int64) is read as Int64, its schema type string stores LargeBinary Flow\ETL\Foundation\Exception\InvalidArgumentException: Parquet column "id" (Int64) is read as Int64, its schema type string stores LargeBinary -Flow\ETL\Foundation\Exception\RuntimeException: flow_php expected a Flow\Parquet\Engine\RustParquetFileReader -Flow\ETL\Foundation\Exception\RuntimeException: flow_php expected a Flow\Parquet\Engine\RustParquetFileWriter +Flow\ETL\Foundation\Exception\RuntimeException: flow_php expected a Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileReader +Flow\ETL\Foundation\Exception\RuntimeException: flow_php expected a Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileWriter diff --git a/src/extension/flow-php-ext/tests/phpt/091_parquet_canonical_layout_contract.phpt b/src/extension/flow-php-ext/tests/phpt/091_parquet_canonical_layout_contract.phpt index 031ade66e9..02765dc200 100644 --- a/src/extension/flow-php-ext/tests/phpt/091_parquet_canonical_layout_contract.phpt +++ b/src/extension/flow-php-ext/tests/phpt/091_parquet_canonical_layout_contract.phpt @@ -1,13 +1,12 @@ --TEST-- -arrow-ext's canonical Arrow layout (parquet/canonical.rs) is the layout flow_php's columns store (flow-batch-frame kind::data_type()): every Flow type, nested included, crosses RustBatchReader → RustParquetOpenSource with its values intact +arrow-ext's canonical Arrow layout (parquet/canonical.rs) is the layout flow_php's columns store (flow-batch-frame kind::data_type()): every Flow type, nested included, crosses the flow_php engine reader → RustParquetOpenSource with its values intact --SKIPIF-- - --FILE-- writeTo(path('memory://layout.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), Compressions::SNAPPY, diff --git a/src/extension/flow-php-ext/tests/phpt/097_parquet_uint64_numeric_string.phpt b/src/extension/flow-php-ext/tests/phpt/097_parquet_uint64_numeric_string.phpt index 9d3b9f3e7b..e06152ca9a 100644 --- a/src/extension/flow-php-ext/tests/phpt/097_parquet_uint64_numeric_string.phpt +++ b/src/extension/flow-php-ext/tests/phpt/097_parquet_uint64_numeric_string.phpt @@ -1,8 +1,7 @@ --TEST-- -A UINT_64 leaf crosses RustBatchReader → RustParquetOpenSource as a numeric_string column (arrow-ext hands it over as LargeBinary decimal text, the Bytes kind flow_php stores numeric_string in); DataFrame rows written through RustParquetFileWriter into an explicit UINT_64 schema take an integer column (negatives refused) and a numeric_string column (non-canonical text refused) +A UINT_64 leaf crosses the flow_php engine reader → RustParquetOpenSource as a numeric_string column (arrow-ext hands it over as LargeBinary decimal text, the Bytes kind flow_php stores numeric_string in); DataFrame rows written through RustParquetFileWriter into an explicit UINT_64 schema take an integer column (negatives refused) and a numeric_string column (non-canonical text refused) --SKIPIF-- - --FILE-- readFrom(path('memory://uint64.parque $write = static function (Flow\ETL\Values\Schema $schema, array $values) use ($parquet, $filesystem): string { return outcome(static function () use ($schema, $values, $parquet, $filesystem): array { $fileWriter = new RustParquetFileWriter( - new ArrowRustParquetFileWriter( + new FlowPhpParquetFileWriter( $filesystem->writeTo(path('memory://uint64_write.parquet')), ArrowSchemaConverter::toExtension($parquet), Compressions::SNAPPY, diff --git a/src/extension/flow-php-ext/tests/phpt/109_parquet_skipped_rows_parity.phpt b/src/extension/flow-php-ext/tests/phpt/109_parquet_skipped_rows_parity.phpt index 60daf2df40..af399f84bc 100644 --- a/src/extension/flow-php-ext/tests/phpt/109_parquet_skipped_rows_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/109_parquet_skipped_rows_parity.phpt @@ -1,7 +1,7 @@ --TEST-- RustParquetOpenSource yields SkippedRows exactly as PhpParquetOpenSource for a matched-row offset inside a file, past every match, beside no match, and not at all without an offset --SKIPIF-- - + --FILE-- writeTo(path('memory://ids.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), Compressions::SNAPPY, @@ -84,7 +84,7 @@ foreach ($cases as $label => [$filter, $offset, $limit]) { offset: $offset, ); $php = yielded((new PhpParquetOpenSource($phpFile))->batches($schema, 64, $plan, new PhpBackend())); - $rust = yielded((new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path('memory://ids.parquet')))))->batches($schema, 64, $plan, new RustBackend())); + $rust = yielded((new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path('memory://ids.parquet')))))->batches($schema, 64, $plan, new RustBackend())); echo $label, ': ', $php === $rust ? $rust : "MISMATCH\n php: " . $php . "\n rust: " . $rust, "\n"; } diff --git a/src/extension/flow-php-ext/tests/phpt/110_parquet_batch_boundaries_parity.phpt b/src/extension/flow-php-ext/tests/phpt/110_parquet_batch_boundaries_parity.phpt index 4d20055594..9c925e4b81 100644 --- a/src/extension/flow-php-ext/tests/phpt/110_parquet_batch_boundaries_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/110_parquet_batch_boundaries_parity.phpt @@ -1,7 +1,7 @@ --TEST-- RustParquetOpenSource fills every batch to the batch size across row groups exactly as PhpParquetOpenSource: batches smaller than a group, larger than a group, larger than the file, a non-divisor, and behind a matched-row offset --SKIPIF-- - + --FILE-- writeTo(path('memory://groups.parquet')), ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), Compressions::SNAPPY, @@ -82,7 +82,7 @@ foreach ($cases as $label => [$batchSize, $filter, $offset, $limit]) { ? ReadPlan::forFilter($phpFile->reader()->footer(), $phpFile->indexes(), null) : ReadPlan::forFilter($phpFile->reader()->footer(), $phpFile->indexes(), BoundFilter::bind($filter, $phpFile->schema(), new Options()), limit: $limit, offset: $offset); $php = batches((new PhpParquetOpenSource($phpFile))->batches($schema, $batchSize, $plan, new PhpBackend())); - $rust = batches((new RustParquetOpenSource(new RustParquetFileReader($filesystem->readFrom(path('memory://groups.parquet')))))->batches($schema, $batchSize, $plan, new RustBackend())); + $rust = batches((new RustParquetOpenSource(new FlowPhpParquetFileReader($filesystem->readFrom(path('memory://groups.parquet')))))->batches($schema, $batchSize, $plan, new RustBackend())); $sizes = substr($rust, 0, (int) strrpos($rust, ' ')); echo $label, ': ', $php === $rust ? (strlen($sizes) > 60 ? substr($sizes, 0, 40) . '... (' . count(explode(',', $sizes)) . ' batches)' : $sizes) : "MISMATCH\n php: " . $php . "\n rust: " . $rust, "\n"; diff --git a/src/extension/flow-php-ext/tests/phpt/123_allocated_bytes_count_arrow_once.phpt b/src/extension/flow-php-ext/tests/phpt/123_allocated_bytes_count_arrow_once.phpt deleted file mode 100644 index 657a142e53..0000000000 --- a/src/extension/flow-php-ext/tests/phpt/123_allocated_bytes_count_arrow_once.phpt +++ /dev/null @@ -1,57 +0,0 @@ ---TEST-- -RustBackend::allocatedBytes() counts a batch imported from a Parquet read once: it grows with Flow\Arrow\allocated_bytes(), and the rest stays as it was before the read ---SKIPIF-- - - ---FILE-- -writeTo(path('memory://counted.parquet')), - ArrowSchemaConverter::toExtension((new SchemaConverter())->toParquetSchema($schema)), - Compressions::SNAPPY, - OptionsConverter::toExtension(Options::default()), - 1_000, - ), - new ParquetSchemaConformance((new SchemaConverter())->toParquetSchema($schema)), - new PhpBackend(), -); - -foreach (array_chunk(range(0, 65_535), 8_192) as $ids) { - $writer->write(native_rows($schema, array_map(static fn(int $i): array => ['id' => $i, 'email' => "user{$i}@example.com"], $ids))); -} - -$writer->close(); -gc_collect_cycles(); - -$backend = new RustBackend(); -$arrowBefore = \Flow\Arrow\allocated_bytes(); -$restBefore = $backend->allocatedBytes() - $arrowBefore; -$held = iterator_to_array(rust_parquet_batches($filesystem->readFrom(path('memory://counted.parquet')), $schema, 65_536), false); -gc_collect_cycles(); - -var_dump(array_sum(array_map(count(...), $held))); -var_dump(\Flow\Arrow\allocated_bytes() - $arrowBefore > 1_048_576); -var_dump(abs($backend->allocatedBytes() - \Flow\Arrow\allocated_bytes() - $restBefore) < 1_048_576); -?> ---EXPECT-- -int(65536) -bool(true) -bool(true) diff --git a/src/extension/flow-php-ext/tests/phpt/bootstrap.php b/src/extension/flow-php-ext/tests/phpt/bootstrap.php index 1ea360b9ba..2cfb836e66 100644 --- a/src/extension/flow-php-ext/tests/phpt/bootstrap.php +++ b/src/extension/flow-php-ext/tests/phpt/bootstrap.php @@ -9,6 +9,7 @@ use Flow\ETL\Adapter\CSV\IO\Extractor\RustCSVOpenSource; use Flow\ETL\Adapter\CSV\IO\Loader\PhpCSVEncoder; use Flow\ETL\Adapter\JSON\IO\Loader\PhpJsonEncoder; +use Flow\ETL\Adapter\Parquet\IO\Engine\FlowPhpParquetFileReader; use Flow\ETL\Adapter\Parquet\IO\Extractor\RustParquetOpenSource; use Flow\ETL\Foundation\Exception\InvalidArgumentException; use Flow\ETL\Foundation\Exception\RuntimeException; @@ -21,7 +22,6 @@ use Flow\ETL\Values\Rows\RowsBuilder; use Flow\ETL\Values\Schema; use Flow\Filesystem\SourceStream; -use Flow\Parquet\Engine\RustParquetFileReader; use Flow\Parquet\Reader\ReadPlan; use function Flow\ETL\DSL\bool_schema; @@ -271,7 +271,7 @@ function rust_parquet_batches( int $offset = 0, ?int $limit = null, ): Iterator { - $file = new RustParquetFileReader($stream); + $file = new FlowPhpParquetFileReader($stream); return (new RustParquetOpenSource($file))->batches( $schema, diff --git a/src/extension/parquet-engine/src/batch.rs b/src/extension/parquet-engine/src/batch.rs deleted file mode 100644 index 5ee5894937..0000000000 --- a/src/extension/parquet-engine/src/batch.rs +++ /dev/null @@ -1,333 +0,0 @@ -//! One batch is a struct-typed `FFI_ArrowSchema` plus `FFI_ArrowArray`, owned until a consumer moves the array out. - -use std::collections::HashMap; -use std::ffi::{c_char, CStr}; -use std::sync::Arc; - -use arrow_array::ffi::{from_ffi, to_ffi, FFI_ArrowArray, FFI_ArrowSchema}; -use arrow_array::{Array, StructArray}; -use arrow_schema::{DataType, Field, Fields}; -use ext_php_rs::flags::ClassFlags; -use ext_php_rs::prelude::*; -use ext_php_rs::types::{ZendObject, Zval}; -use ext_php_rs::zend::ClassEntry; - -use crate::error::Error; -use crate::library::{batch_size, read_plan, RustParquetFileReader, INVALID_ARGUMENT}; -use crate::php::{call_handle_transparent, ce_method_ref}; -use crate::read::ParquetReader; -use crate::render::{exception, parquet_exception, Side}; -use crate::source::PhpStream; - -/// Child field metadata: the arrow type of the file column the canonical child was read from. -pub const SOURCE_TYPE: &str = "parquet.source_type"; - -/// `ZEND_INTERNAL_CLASS` (zend_compile.h): a class an extension registered, which userland can neither declare nor -/// extend once final. -const ZEND_INTERNAL_CLASS: c_char = 1; - -#[php_class] -#[php(name = "Flow\\Arrow\\RustParquetBatch", flags = ClassFlags::Final)] -pub struct RustParquetBatch { - schema: FFI_ArrowSchema, - array: FFI_ArrowArray, - rows: usize, -} - -#[php_impl] -impl RustParquetBatch { - pub fn count(&self) -> i64 { - self.rows as i64 - } - - #[php(name = "arrowSchemaAddress")] - pub fn arrow_schema_address(&self) -> i64 { - std::ptr::from_ref(&self.schema) as i64 - } - - #[php(name = "arrowArrayAddress")] - pub fn arrow_array_address(&self) -> i64 { - std::ptr::from_ref(&self.array) as i64 - } -} - -#[php_class] -#[php(name = "Flow\\Arrow\\RustArrowSchema", flags = ClassFlags::Final)] -pub struct RustArrowSchema { - schema: FFI_ArrowSchema, -} - -#[php_impl] -impl RustArrowSchema { - #[php(name = "arrowSchemaAddress")] - pub fn arrow_schema_address(&self) -> i64 { - std::ptr::from_ref(&self.schema) as i64 - } -} - -#[php_class] -#[php(name = "Flow\\Arrow\\Parquet\\RustBatchReader", flags = ClassFlags::Final)] -pub struct RustBatchReader { - reader: Option, - skipped: usize, - stream: Arc, - /// The projection: canonical children named by column, each with its `SOURCE_TYPE`. - fields: Fields, -} - -#[php_impl] -impl RustBatchReader { - /// `$columns`: root names; `$batchSize` rows at most per `next()`. - pub fn __construct( - file: &RustParquetFileReader, - columns: Vec, - batch_size: i64, - plan: &Zval, - ) -> PhpResult { - let batch_size = self::batch_size(batch_size)?; - let (stream, meta) = file.read()?; - let stream = Arc::clone(stream); - let plan = read_plan(meta, plan, &stream)?; - let reader = ParquetReader::open(Arc::clone(&stream), meta, &columns, plan, batch_size) - .map_err(|error| parquet_exception(error, &stream, Side::Read))?; - let fields = columns - .iter() - .zip(reader.fields()) - .zip(reader.types()) - .map(|((name, field), canonical)| { - Field::new(name, canonical.clone(), true).with_metadata(HashMap::from([( - SOURCE_TYPE.to_string(), - field.data_type().to_string(), - )])) - }) - .collect(); - - Ok(Self { - reader: Some(reader), - skipped: 0, - stream, - fields, - }) - } - - /// The struct schema of every batch, known before the first. - pub fn schema(&self) -> PhpResult { - Ok(RustArrowSchema { - schema: FFI_ArrowSchema::try_from(&DataType::Struct(self.fields.clone())) - .map_err(|error| parquet_exception(Error::Arrow(error), &self.stream, Side::Read))?, - }) - } - - /// At most `$batchSize` rows as one struct batch, null after the last. - #[php(name = "next")] - pub fn next_batch(&mut self) -> PhpResult> { - let Some(reader) = self.reader.as_mut() else { - return Ok(None); - }; - - let batch = reader.next(); - self.skipped = reader.skipped(); - - let (rows, arrays) = match batch { - None => { - self.reader = None; - - return Ok(None); - } - Some(batch) => batch.map_err(|error| parquet_exception(error, &self.stream, Side::Read))?, - }; - - let exported = StructArray::try_new_with_length(self.fields.clone(), arrays, None, rows) - .and_then(|array| to_ffi(&array.to_data())) - .map_err(|error| parquet_exception(Error::Arrow(error), &self.stream, Side::Read))?; - - Ok(Some(RustParquetBatch { - array: exported.0, - schema: exported.1, - rows, - })) - } - - /// The matches the plan's offset skipped: final once `next()` returned its first batch, or null without one. - pub fn skipped(&self) -> i64 { - i64::try_from(self.skipped).unwrap_or(i64::MAX) - } - - pub fn close(&mut self) { - self.reader = None; - } -} - -fn refused(message: String) -> PhpException { - exception(INVALID_ARGUMENT, message) -} - -/// `$object->$method()` of an address method: a pointer the exporter owns. -fn address(object: &ZendObject, ce: &ClassEntry, method: &str) -> PhpResult { - let address = call_handle_transparent(ce_method_ref(ce, method)?, Some(object), &mut [])?; - - address - .long() - .and_then(|address| usize::try_from(address).ok()) - .filter(|address| *address != 0) - .ok_or_else(|| refused(format!("Arrow C Data {method}() must return a non-null address"))) -} - -/// The struct batch `$batch` carries, moved out of it: an internal class's `arrowSchemaAddress()` (read by reference) -/// and `arrowArrayAddress()` (moved, its release left NULL), refused before the move unless the schema is a struct -/// of as many children as the array and the array was not imported before. -pub fn import(batch: &Zval) -> PhpResult { - let object = batch - .object() - .ok_or_else(|| refused("Arrow C Data batch must be an object".to_string()))?; - let ce = unsafe { object.ce.as_ref() }.ok_or_else(|| refused("Arrow C Data batch has no class".to_string()))?; - - if ce.type_ != ZEND_INTERNAL_CLASS { - return Err(refused(format!( - "Arrow C Data batch must be an extension's class, got {}", - ce.name().unwrap_or_default() - ))); - } - - let schema = address(object, ce, "arrowSchemaAddress")? as *const FFI_ArrowSchema; - let source = address(object, ce, "arrowArrayAddress")? as *mut FFI_ArrowArray; - - unsafe { check(schema, source) }.map_err(refused)?; - - let schema = unsafe { &*schema }; - let moved = unsafe { FFI_ArrowArray::from_raw(source) }; - - let data = unsafe { from_ffi(moved, schema) } - .and_then(|data| data.validate().map(|()| data)) - .map_err(|error| refused(format!("Arrow C Data batch is not a valid struct array: {error}")))?; - - Ok(StructArray::from(data)) -} - -/// The leading fields of `struct ArrowSchema` and `struct ArrowArray` as the Arrow C Data Interface specification -/// declares them (https://arrow.apache.org/docs/format/CDataInterface.html#structure-definitions): read before the -/// arrow-rs accessors, which panic on a null format and cast a negative count to `usize`. -#[repr(C)] -struct SchemaHead { - format: *const c_char, - name: *const c_char, - metadata: *const c_char, - flags: i64, - n_children: i64, -} - -#[repr(C)] -struct ArrayHead { - length: i64, - null_count: i64, - offset: i64, - n_buffers: i64, - n_children: i64, -} - -/// # Safety -/// -/// `schema` and `array` point to live C Data Interface structs. -unsafe fn check(schema: *const FFI_ArrowSchema, array: *const FFI_ArrowArray) -> Result<(), String> { - let schema_head = unsafe { &*(schema as *const SchemaHead) }; - let array_head = unsafe { &*(array as *const ArrayHead) }; - - if schema_head.format.is_null() || unsafe { CStr::from_ptr(schema_head.format) }.to_bytes() != b"+s" { - return Err("Arrow C Data batch must be a struct array".to_string()); - } - - if unsafe { &*array }.is_released() { - return Err("Arrow C Data batch is already imported".to_string()); - } - - if array_head.length < 0 { - return Err(format!( - "Arrow C Data batch length must not be negative, {} given", - array_head.length - )); - } - - if array_head.n_children < 0 || schema_head.n_children < 0 || array_head.n_children != schema_head.n_children { - return Err(format!( - "Arrow C Data batch of {} children does not match its schema of {}", - array_head.n_children, schema_head.n_children - )); - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use arrow_array::ffi::to_ffi; - use arrow_array::types::Int64Type; - use arrow_array::{Array, ArrayRef, Int64Array, ListArray, StructArray}; - use arrow_schema::{DataType, Field, Fields}; - - fn batch() -> StructArray { - let ids: ArrayRef = Arc::new(Int64Array::from_iter((0..1000).map(|i| (i % 7 != 0).then_some(i)))); - let lists: ArrayRef = Arc::new(ListArray::from_iter_primitive::( - (0..1000).map(|i| Some(vec![Some(i), None, Some(i * 2)])), - )); - - StructArray::new( - Fields::from(vec![ - Field::new("id", DataType::Int64, true), - Field::new("list", lists.data_type().clone(), true), - ]), - vec![ids, lists], - None, - ) - } - - fn refusal(mutate: impl FnOnce(*mut super::SchemaHead, *mut super::ArrayHead)) -> Result<(), String> { - let (mut array, mut schema) = to_ffi(&batch().to_data()).unwrap(); - let schema_ptr = &mut schema as *mut arrow_array::ffi::FFI_ArrowSchema; - let array_ptr = &mut array as *mut arrow_array::ffi::FFI_ArrowArray; - let schema_head = schema_ptr as *mut super::SchemaHead; - let array_head = array_ptr as *mut super::ArrayHead; - let (format, length, children) = - unsafe { ((*schema_head).format, (*array_head).length, (*array_head).n_children) }; - - mutate(schema_head, array_head); - let result = unsafe { super::check(schema_ptr, array_ptr) }; - - unsafe { - (*schema_head).format = format; - (*array_head).length = length; - (*array_head).n_children = children; - } - - result - } - - #[test] - fn a_null_format_is_refused_before_the_accessors() { - assert_eq!( - refusal(|schema, _| unsafe { (*schema).format = std::ptr::null() }), - Err("Arrow C Data batch must be a struct array".to_string()) - ); - } - - #[test] - fn a_negative_length_is_refused() { - assert_eq!( - refusal(|_, array| unsafe { (*array).length = -1 }), - Err("Arrow C Data batch length must not be negative, -1 given".to_string()) - ); - } - - #[test] - fn a_negative_or_mismatched_child_count_is_refused() { - assert_eq!( - refusal(|_, array| unsafe { (*array).n_children = -1 }), - Err("Arrow C Data batch of -1 children does not match its schema of 2".to_string()) - ); - assert_eq!( - refusal(|_, array| unsafe { (*array).n_children = 1 }), - Err("Arrow C Data batch of 1 children does not match its schema of 2".to_string()) - ); - } -} diff --git a/src/extension/parquet-engine/src/engine.rs b/src/extension/parquet-engine/src/engine.rs index c6c67de8e0..aed3d09d4f 100644 --- a/src/extension/parquet-engine/src/engine.rs +++ b/src/extension/parquet-engine/src/engine.rs @@ -27,7 +27,7 @@ use crate::render::{exception, INVALID_ARGUMENT}; #[cfg_attr( feature = "flow-php-names", php( - name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetEngine", + name = "Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetEngine", flags = ClassFlags::Final, implements(ce = parquet_engine_ce, stub = "Flow\\Parquet\\ParquetEngine") ) diff --git a/src/extension/parquet-engine/src/lib.rs b/src/extension/parquet-engine/src/lib.rs index 0a33996aed..1f26a833e4 100644 --- a/src/extension/parquet-engine/src/lib.rs +++ b/src/extension/parquet-engine/src/lib.rs @@ -1,12 +1,11 @@ //! Parquet over Flow filesystem streams: one reader, one cast table and one writer, surfaced as the -//! `flow-php/parquet` lib's values (`library`) and as Arrow C Data struct batches (`batch`). +//! `flow-php/parquet` lib's values (`library`). #[cfg(all(feature = "arrow-names", feature = "flow-php-names"))] compile_error!("flow-parquet-engine: enable exactly one of the features arrow-names, flow-php-names"); #[cfg(not(any(feature = "arrow-names", feature = "flow-php-names")))] compile_error!("flow-parquet-engine: enable exactly one of the features arrow-names, flow-php-names"); -pub mod batch; pub mod canonical; pub mod cells; pub mod chunks; diff --git a/src/extension/parquet-engine/src/library.rs b/src/extension/parquet-engine/src/library.rs index c78596742e..d2eed2cfd6 100644 --- a/src/extension/parquet-engine/src/library.rs +++ b/src/extension/parquet-engine/src/library.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use std::sync::Arc; -use arrow_array::{new_null_array, Array, ArrayRef}; +use arrow_array::{new_null_array, ArrayRef}; use ext_php_rs::convert::IntoZval; use ext_php_rs::error::Result as ZvalResult; use ext_php_rs::flags::{ClassFlags, DataType}; @@ -17,7 +17,6 @@ use parquet::arrow::ArrowSchemaConverter; use parquet::basic::Type as PhysicalType; use parquet::file::metadata::ParquetMetaData; -use crate::batch; use crate::cells::{Checked, Classes, ReadCell, Refusal, Scalar, Times, Validated, WriteColumn}; use crate::chunks::chunk_spans; use crate::error::Error; @@ -221,7 +220,7 @@ pub fn batch_size(value: i64) -> PhpResult { #[cfg(feature = "arrow-names")] const FOOTER_CLASS: &str = "Flow\\Parquet\\Engine\\RustParquetFooter"; #[cfg(feature = "flow-php-names")] -const FOOTER_CLASS: &str = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFooter"; +const FOOTER_CLASS: &str = "Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFooter"; /// `ParquetFileReader::footer()`'s return, typed as the footer class of the extension that registers it: the class /// registers before the reader, so the covariant return type is checked. @@ -250,7 +249,7 @@ impl IntoZval for FooterObject { #[cfg_attr( feature = "flow-php-names", php( - name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFileReader", + name = "Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFileReader", flags = ClassFlags::Final, implements(ce = parquet_file_reader_ce, stub = "Flow\\Parquet\\ParquetFileReader") ) @@ -418,7 +417,7 @@ impl RustParquetFileReader { #[cfg_attr( feature = "flow-php-names", php( - name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFooter", + name = "Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFooter", flags = ClassFlags::Final, implements(ce = footer_ce, stub = "Flow\\Parquet\\ParquetFile\\Footer") ) @@ -638,7 +637,7 @@ impl IntoZval for Chunk { #[cfg_attr( feature = "flow-php-names", php( - name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpColumnsReader", + name = "Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpColumnsReader", flags = ClassFlags::Final, implements(ce = ce::iterator, stub = "\\Iterator") ) @@ -892,7 +891,7 @@ fn codec(compression: &Zval) -> PhpResult<&'static str> { #[cfg_attr( feature = "flow-php-names", php( - name = "Flow\\ETL\\Adapter\\Parquet\\Engine\\FlowPhpParquetFileWriter", + name = "Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFileWriter", flags = ClassFlags::Final, implements(ce = parquet_file_writer_ce, stub = "Flow\\Parquet\\ParquetFileWriter") ) @@ -915,6 +914,30 @@ impl Drop for RustParquetFileWriter { } impl RustParquetFileWriter { + /// `rows` rows of `columns` by name: missing writer columns are nulls, extra columns are ignored. + pub fn write_arrow_columns(&mut self, rows: usize, columns: &[(String, ArrayRef)]) -> PhpResult<()> { + self.open()?; + self.flush()?; + + let writer = self + .writer + .as_mut() + .ok_or_else(|| exception(RUNTIME, "Writer is not open".to_string()))?; + let arrays = writer + .schema() + .fields() + .iter() + .map(|field| match columns.iter().find(|(name, _)| name == field.name()) { + Some((_, column)) => Arc::clone(column), + None => new_null_array(field.data_type(), rows), + }) + .collect::>(); + + writer + .write(rows, &arrays) + .map_err(|error| parquet_exception(error, &self.stream, Side::Write)) + } + fn write_lists(&mut self, columns: &ZendHashTable, stored: bool) -> PhpResult<()> { if self.writer.is_none() { return Err(exception(RUNTIME, "Writer is not open".to_string())); @@ -1224,33 +1247,6 @@ impl RustParquetFileWriter { for_each_value(rows.0, |row| self.write_row(row)) } - /// Moves out another extension's Arrow C Data batch: missing writer columns are nulls, extra children are ignored. - #[php(name = "writeArrowBatch")] - pub fn write_arrow_batch(&mut self, batch: &Zval) -> PhpResult<()> { - self.open()?; - self.flush()?; - - let batch = batch::import(batch)?; - let rows = batch.len(); - let writer = self - .writer - .as_mut() - .ok_or_else(|| exception(RUNTIME, "Writer is not open".to_string()))?; - let arrays = writer - .schema() - .fields() - .iter() - .map(|field| match batch.column_by_name(field.name()) { - Some(column) => Arc::clone(column), - None => new_null_array(field.data_type(), rows), - }) - .collect::>(); - - writer - .write(rows, &arrays) - .map_err(|error| parquet_exception(error, &self.stream, Side::Write)) - } - /// Buffered rows, the footer, then the stream closed - closed even when a flush or the footer is refused; the /// first refusal is the one thrown. pub fn close(&mut self) -> PhpResult<()> { diff --git a/src/lib/parquet/src/Flow/Parquet/Engine/Arrow/ReadPlanConverter.php b/src/lib/parquet/src/Flow/Parquet/Engine/Arrow/ReadPlanConverter.php index 7cf3dc2431..607e2c3e86 100644 --- a/src/lib/parquet/src/Flow/Parquet/Engine/Arrow/ReadPlanConverter.php +++ b/src/lib/parquet/src/Flow/Parquet/Engine/Arrow/ReadPlanConverter.php @@ -29,8 +29,7 @@ private function __construct( ) {} /** - * Called by name from arrow-ext RustBatchReader::__construct() and RustColumnsReader::__construct(), pinned by - * phpt 055. + * Called by name from arrow-ext RustColumnsReader::__construct(), pinned by phpt 055. * * @return array{selectors: list, matched: list, filter?: array, limit: ?int, offset: int} * file-absolute selectors (row count, skip) of the rows read and of the rows proven to match, the row filter's diff --git a/src/lib/parquet/src/Flow/Parquet/Engine/ArrowExtension.php b/src/lib/parquet/src/Flow/Parquet/Engine/ArrowExtension.php index d97a8a78a7..8ef4e9d271 100644 --- a/src/lib/parquet/src/Flow/Parquet/Engine/ArrowExtension.php +++ b/src/lib/parquet/src/Flow/Parquet/Engine/ArrowExtension.php @@ -17,7 +17,7 @@ /** * Equals the extension's FLOW_ARROW_ABI; both change together. */ - public const int ABI = 2; + public const int ABI = 3; public function __construct( public bool $loaded, From 7a99d3293248c24fedddf70331f3c700061d4ecf Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Mon, 16 Nov 2026 19:04:25 -0600 Subject: [PATCH 3/3] fix(flow-php/flow-php-ext): freed large buffers return to the system on Linux - mmap threshold fixed at 128 KiB at startup, the environment still wins - phpt 001 no longer depends on the extension load order --- .../components/extensions/flow-php-ext.md | 10 +++++ src/extension/flow-php-ext/src/alloc.rs | 40 +++++++++++++++++++ src/extension/flow-php-ext/src/lib.rs | 2 + .../tests/phpt/001_extension_loaded.phpt | 17 +++++--- 4 files changed, 64 insertions(+), 5 deletions(-) diff --git a/documentation/components/extensions/flow-php-ext.md b/documentation/components/extensions/flow-php-ext.md index 600ff57014..fa62815911 100644 --- a/documentation/components/extensions/flow-php-ext.md +++ b/documentation/components/extensions/flow-php-ext.md @@ -157,3 +157,13 @@ type before the first batch. Read and write refusals are the `Flow\Parquet\Excep With `engine: new RustParquetEngine()`, arrow-ext reads the file, the columns are built from PHP values, and a memory limit does not count the bytes of arrow-ext. +## Memory returned to the system + +When the extension loads on Linux with glibc, it fixes the mmap threshold of the process at 128 KiB. glibc otherwise +raises the threshold as large blocks are freed, and the freed buffers stay on the heap. With a fixed threshold, a sort +holds what its memory limit counts. The threshold applies to the whole process. To keep your own value, set it in the +environment: + +```bash +MALLOC_MMAP_THRESHOLD_=262144 php your_script.php +``` diff --git a/src/extension/flow-php-ext/src/alloc.rs b/src/extension/flow-php-ext/src/alloc.rs index 1d423f9292..0ad6b346fb 100644 --- a/src/extension/flow-php-ext/src/alloc.rs +++ b/src/extension/flow-php-ext/src/alloc.rs @@ -74,6 +74,30 @@ pub fn release_freed() { #[cfg(not(all(target_os = "linux", target_env = "gnu")))] pub fn release_freed() {} +#[cfg(any(test, all(target_os = "linux", target_env = "gnu")))] +fn fixes_mmap_threshold(environment_threshold: Option) -> bool { + environment_threshold.is_none() +} + +// glibc raises its mmap threshold as large blocks are freed, and freed large buffers then stay on the heap +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub fn fix_mmap_threshold() { + const M_MMAP_THRESHOLD: i32 = -3; + const MMAP_THRESHOLD_BYTES: i32 = 128 * 1024; + + extern "C" { + fn mallopt(param: i32, value: i32) -> i32; + } + + if fixes_mmap_threshold(std::env::var_os("MALLOC_MMAP_THRESHOLD_")) { + // SAFETY: mallopt takes no pointer and is safe to call at any time + unsafe { mallopt(M_MMAP_THRESHOLD, MMAP_THRESHOLD_BYTES) }; + } +} + +#[cfg(not(all(target_os = "linux", target_env = "gnu")))] +pub fn fix_mmap_threshold() {} + pub fn own_peak_bytes() -> i64 { PEAK.load(Ordering::Relaxed).max(own_bytes()) } @@ -81,3 +105,19 @@ pub fn own_peak_bytes() -> i64 { pub fn reset_peak() { PEAK.store(ALLOCATED.load(Ordering::Relaxed), Ordering::Relaxed); } + +#[cfg(test)] +mod tests { + use super::fixes_mmap_threshold; + use std::ffi::OsString; + + #[test] + fn fixes_mmap_threshold_when_the_environment_leaves_it_unset() { + assert!(fixes_mmap_threshold(None)); + } + + #[test] + fn leaves_mmap_threshold_to_the_environment_when_it_is_set() { + assert!(!fixes_mmap_threshold(Some(OsString::from("65536")))); + } +} diff --git a/src/extension/flow-php-ext/src/lib.rs b/src/extension/flow-php-ext/src/lib.rs index 5b3ae92f6a..950b185b7c 100644 --- a/src/extension/flow-php-ext/src/lib.rs +++ b/src/extension/flow-php-ext/src/lib.rs @@ -49,6 +49,8 @@ pub extern "C" fn php_module_info(_module: *mut ModuleEntry) { /// /// Only called by the PHP engine during module startup (MINIT). pub unsafe extern "C" fn module_startup(_type: i32, _module_number: i32) -> i32 { + alloc::fix_mmap_threshold(); + if let Err(e) = interfaces::register() { eprintln!("flow_php: failed to register the Flow\\ETL interfaces: {e}"); return -1; diff --git a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt index 94b3ac767f..ebae0ba74c 100644 --- a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt +++ b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt @@ -6,7 +6,10 @@ flow_php extension is loaded and registers the package interfaces and the Rust c getClassNames(); +$parquetInterfaces = ['Flow\Parquet\ParquetEngine', 'Flow\Parquet\ParquetFileReader', 'Flow\Parquet\ParquetFileWriter', 'Flow\Parquet\ParquetFile\Footer']; + +// the extension loaded first registers the Flow\Parquet interfaces, so their owner depends on the load order +$classes = array_diff((new ReflectionExtension('flow_php'))->getClassNames(), $parquetInterfaces); sort($classes); foreach ($classes as $class) { @@ -14,6 +17,10 @@ foreach ($classes as $class) { echo $reflection->isInterface() ? 'interface ' : 'class ', $class, $reflection->isInterface() ? '' : ' implements ' . implode(', ', array_diff($reflection->getInterfaceNames(), ['Traversable'])), "\n"; } +foreach ($parquetInterfaces as $interface) { + echo $interface, ': ', interface_exists($interface, false) ? 'interface' : 'missing', "\n"; +} + var_dump(class_exists('Flow\Floe\Exception\ExtensionException', false) === false); ?> --EXPECT-- @@ -49,8 +56,8 @@ class Flow\ETL\Values\Column\RustGroupedTotals implements Flow\ETL\Values\Column interface Flow\ETL\Values\Grouping\GroupTable class Flow\ETL\Values\Grouping\RustGroupTable implements Flow\ETL\Values\Grouping\GroupTable class Flow\ETL\Values\RustIterator implements Iterator -interface Flow\Parquet\ParquetEngine -interface Flow\Parquet\ParquetFileReader -interface Flow\Parquet\ParquetFileWriter -interface Flow\Parquet\ParquetFile\Footer +Flow\Parquet\ParquetEngine: interface +Flow\Parquet\ParquetFileReader: interface +Flow\Parquet\ParquetFileWriter: interface +Flow\Parquet\ParquetFile\Footer: interface bool(true)