diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index df4b36a4a6..a22ade06b5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -674,6 +674,12 @@ jobs: env: *extension-flow-php-rust-env run: cargo fmt --all --check && cargo clippy --workspace --locked --all-targets -- -D warnings + - name: Lint the ZTS request thread test + if: matrix.php == '8.6' && matrix.ts == 'zts' + working-directory: src/extension/flow-php-ext + env: *extension-flow-php-rust-env + run: cargo clippy --locked --features zts-embed --test zts_request_threads -- -D warnings + - name: Check both extensions lock the same flow-parquet-engine dependencies working-directory: src/extension run: | @@ -924,6 +930,12 @@ jobs: env: *extension-arrow-rust-env run: cargo fmt --all --check && cargo clippy --workspace --locked --all-targets -- -D warnings + - name: Lint the ZTS request thread test + if: matrix.php == '8.6' && matrix.ts == 'zts' + working-directory: src/extension/arrow-ext + env: *extension-arrow-rust-env + run: cargo clippy --locked --features zts-embed --test zts_request_threads -- -D warnings + - name: Install Composer Dependencies uses: ./.github/actions/composer-install with: diff --git a/src/extension/arrow-ext/Cargo.lock b/src/extension/arrow-ext/Cargo.lock index 3c88d0f5f9..9a9fd18bb7 100644 --- a/src/extension/arrow-ext/Cargo.lock +++ b/src/extension/arrow-ext/Cargo.lock @@ -591,9 +591,9 @@ dependencies = [ [[package]] name = "ext-php-rs" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d72e0a34c9c88383f784dc538404d5ed1b3a3451245fe7a3c05b78a859c8f1" +checksum = "05c899bc948194e65460f6cd14d6e33d13d1b0a27fe364b66f21aa606f0957b7" dependencies = [ "anyhow", "bindgen", @@ -624,9 +624,9 @@ dependencies = [ [[package]] name = "ext-php-rs-derive" -version = "0.12.5" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28870f7a35eada8b2571d2db76dda8d8ab786c9d645282cb8a8a6c9d9fd4855" +checksum = "538a8f7328e06cce93908fc9741f8bd4165cb8b5cc3aa4f85d3cb553a83fcf16" dependencies = [ "convert_case", "darling", diff --git a/src/extension/arrow-ext/Cargo.toml b/src/extension/arrow-ext/Cargo.toml index 46f5443a98..1ee4e340a1 100644 --- a/src/extension/arrow-ext/Cargo.toml +++ b/src/extension/arrow-ext/Cargo.toml @@ -13,7 +13,7 @@ arrow-validate = ["arrow-array/force_validate"] zts-embed = ["ext-php-rs/embed"] [dependencies] -ext-php-rs = "0.16" +ext-php-rs = "0.17" arrow-array = { version = "60", features = ["ffi"] } flow-parquet-engine = { path = "crates/flow-parquet-engine", features = ["arrow-names"] } diff --git a/src/extension/arrow-ext/tests/phpt/052_parquet_file_reader_writer_contracts.phpt b/src/extension/arrow-ext/tests/phpt/052_parquet_file_reader_writer_contracts.phpt index 5ef565484b..88ba3de907 100644 --- a/src/extension/arrow-ext/tests/phpt/052_parquet_file_reader_writer_contracts.phpt +++ b/src/extension/arrow-ext/tests/phpt/052_parquet_file_reader_writer_contracts.phpt @@ -162,6 +162,43 @@ $appending->writeRow(['id' => 1, 'name' => 'a']); echo arrow_outcome(static fn() => $appending->close()), "\n"; var_dump($inner->closed); echo arrow_outcome(static fn() => $writer($filesystem->writeTo(path('memory://lzo.parquet')), Compressions::LZO)), "\n"; +$reentrant = new class($filesystem->writeTo(path('memory://reentrant.parquet'))) implements Flow\Filesystem\DestinationStream { + public ?RustParquetFileWriter $writer = null; + + public function __construct(private Flow\Filesystem\DestinationStream $stream) {} + + public function append(string $data): self + { + $this->writer?->close(); + $this->stream->append($data); + + return $this; + } + + public function close(): void + { + $this->stream->close(); + } + + public function fromResource($resource): self + { + return $this; + } + + public function isOpen(): bool + { + return $this->stream->isOpen(); + } + + public function path(): Flow\Filesystem\Path + { + return $this->stream->path(); + } +}; +$reentrant->writer = $writer($reentrant); +$reentrant->writer->writeRow(['id' => 1, 'name' => 'a']); +echo arrow_outcome(static fn() => $reentrant->writer->close()), "\n"; +echo "survived\n"; ?> --EXPECT-- -- reader @@ -201,3 +238,5 @@ Flow\Parquet\Exception\RuntimeException: Writer is not open Flow\Filesystem\Exception\RuntimeException: Appending to "memory://append.parquet" failed bool(true) Flow\Parquet\Exception\RuntimeException: LZO compression is not supported by the Arrow engine +Error: Cannot modify object of class Flow\Parquet\Engine\RustParquetFileWriter while it is in use +survived diff --git a/src/extension/arrow-ext/tests/zts_request_threads.rs b/src/extension/arrow-ext/tests/zts_request_threads.rs index 434e9f4b66..04df4ecb10 100644 --- a/src/extension/arrow-ext/tests/zts_request_threads.rs +++ b/src/extension/arrow-ext/tests/zts_request_threads.rs @@ -8,6 +8,7 @@ use ext_php_rs::ffi::{ }; use std::ffi::{c_char, CString}; use std::ptr::null_mut; +use std::sync::mpsc; const THREADS: usize = 8; const REQUESTS: usize = 5; @@ -37,6 +38,7 @@ fn start_php_with_the_extension() { let sapi = Box::leak(Box::new( SapiBuilder::new("zts-request-threads", "ZTS request threads") .ub_write_function(discard_output) + .php_ini_ignore(1) .build() .unwrap(), )) as *mut SapiModule; @@ -71,23 +73,48 @@ fn request(code: &str) -> Option { } #[test] -fn every_request_on_a_thread_that_did_not_load_the_extension_releases_its_native_bytes() { - start_php_with_the_extension(); - let workload = parquet_read_then_release(); - - let threads: Vec>> = (0..THREADS) - .map(|_| { - let workload = workload.clone(); - std::thread::spawn(move || { - let _thread = PhpThreadGuard::new(); - (0..REQUESTS).map(|_| request(&workload)).collect() +fn request_threads_release_their_native_bytes_and_exit_after_the_unload() { + let engine = std::thread::spawn(|| { + start_php_with_the_extension(); + let workload = parquet_read_then_release(); + + let threads: Vec>> = (0..THREADS) + .map(|_| { + let workload = workload.clone(); + std::thread::spawn(move || { + let _thread = PhpThreadGuard::new(); + (0..REQUESTS).map(|_| request(&workload)).collect() + }) + .join() + .unwrap() }) - .join() - .unwrap() - }) - .collect(); + .collect(); + + // the late worker exits after the shutdown, where a thread exit destructor of an unloaded library crashes; a panic on either side drops its sender, so the other side does not hang + let (workload_ran, workload_result) = mpsc::channel(); + let (engine_down, wait_for_engine_down) = mpsc::channel::<()>(); + let late_worker = std::thread::spawn(move || { + let thread = PhpThreadGuard::new(); + let bytes = request(&workload); + std::mem::forget(thread); + workload_ran.send(bytes).unwrap(); + wait_for_engine_down.recv().ok(); + }); + + let late_worker_bytes = workload_result.recv(); + shut_php_down(); + engine_down.send(()).ok(); + + (threads, late_worker, late_worker_bytes) + }); + + let (threads, late_worker, late_worker_bytes) = engine.join().unwrap(); + late_worker.join().unwrap(); - shut_php_down(); + assert!( + late_worker_bytes.is_ok_and(|bytes| bytes.is_some()), + "the late worker's request failed: {late_worker_bytes:?}" + ); for (thread, bytes) in threads.iter().enumerate() { println!("thread {thread} native bytes after each request: {bytes:?}"); diff --git a/src/extension/flow-php-ext/Cargo.lock b/src/extension/flow-php-ext/Cargo.lock index ab4311d36d..bc7756b752 100644 --- a/src/extension/flow-php-ext/Cargo.lock +++ b/src/extension/flow-php-ext/Cargo.lock @@ -644,9 +644,9 @@ dependencies = [ [[package]] name = "ext-php-rs" -version = "0.16.5" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d72e0a34c9c88383f784dc538404d5ed1b3a3451245fe7a3c05b78a859c8f1" +checksum = "05c899bc948194e65460f6cd14d6e33d13d1b0a27fe364b66f21aa606f0957b7" dependencies = [ "anyhow", "bindgen", @@ -677,9 +677,9 @@ dependencies = [ [[package]] name = "ext-php-rs-derive" -version = "0.12.5" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28870f7a35eada8b2571d2db76dda8d8ab786c9d645282cb8a8a6c9d9fd4855" +checksum = "538a8f7328e06cce93908fc9741f8bd4165cb8b5cc3aa4f85d3cb553a83fcf16" dependencies = [ "convert_case", "darling", diff --git a/src/extension/flow-php-ext/Cargo.toml b/src/extension/flow-php-ext/Cargo.toml index 47b14ba8a3..881228bfe6 100644 --- a/src/extension/flow-php-ext/Cargo.toml +++ b/src/extension/flow-php-ext/Cargo.toml @@ -20,7 +20,7 @@ arrow-data.workspace = true arrow-schema.workspace = true arrow-select = "60" bytes = "1" -ext-php-rs = "0.16" +ext-php-rs = "0.17" 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/src/arithmetic.rs b/src/extension/flow-php-ext/src/arithmetic.rs index a1a903d8e8..952f285df8 100644 --- a/src/extension/flow-php-ext/src/arithmetic.rs +++ b/src/extension/flow-php-ext/src/arithmetic.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use arrow_array::cast::AsArray; use arrow_array::types::Int64Type; use ext_php_rs::exception::PhpException; -use ext_php_rs::types::Zval; +use ext_php_rs::types::{ClassRef, Zval}; use flow_column_kernels::arithmetic::{floats, ints, modulo, Operator}; use crate::column::RustColumn; @@ -56,8 +56,11 @@ pub fn native_modulo(left: &Zval, right: &Zval) -> Result, Ph } // a null operand is PHP's refusal, raised at its row by the PHP lane -fn null_free<'a>(left: &'a Zval, right: &'a Zval) -> Option<(&'a RustColumn, &'a RustColumn)> { - let (left, right) = (left.extract::<&RustColumn>()?, right.extract::<&RustColumn>()?); +fn null_free<'a>(left: &'a Zval, right: &'a Zval) -> Option<(ClassRef<'a, RustColumn>, ClassRef<'a, RustColumn>)> { + let (left, right) = ( + left.extract::>()?, + right.extract::>()?, + ); (left.data().null_count() == 0 && right.data().null_count() == 0).then_some((left, right)) } diff --git a/src/extension/flow-php-ext/src/backend.rs b/src/extension/flow-php-ext/src/backend.rs index 2fb466464b..128e273734 100644 --- a/src/extension/flow-php-ext/src/backend.rs +++ b/src/extension/flow-php-ext/src/backend.rs @@ -403,7 +403,7 @@ impl RustBackend { #[php(name = "isNull")] pub fn is_null(&self, column: &Zval) -> PhpResult { - match column.extract::<&RustColumn>() { + match column.extract::>() { Some(native) => Ok(ColumnValue(boolean_column(is_null(native.data()))?.into_zval(false)?)), None => self.adopt_result(call_method( &instance(PHP_BACKEND)?, @@ -415,7 +415,7 @@ impl RustBackend { #[php(name = "isNotNull")] pub fn is_not_null(&self, column: &Zval) -> PhpResult { - match column.extract::<&RustColumn>() { + match column.extract::>() { Some(native) => Ok(ColumnValue( boolean_column(is_not_null(native.data()))?.into_zval(false)?, )), @@ -468,7 +468,7 @@ impl RustBackend { } pub fn adopt(&self, definition: &Zval, column: &Zval) -> PhpResult { - if column.extract::<&RustColumn>().is_some() { + if column.extract::>().is_some() { return Ok(ColumnValue(column.shallow_clone())); } @@ -668,12 +668,12 @@ pub fn adopt_batch(adoption: &Adoption, held: HeldBatch) -> PhpResult { /// `$column` as a `RustColumn`'s plan and data: itself, or `RustBackend`'s adoption of it under `$definition`. pub fn native_column(definition: &Zval, column: &Zval) -> PhpResult<(Rc, ArrayRef)> { let adopted; - let native = match column.extract::<&RustColumn>() { + let native = match column.extract::>() { Some(native) => native, None => { adopted = RustBackend.adopt(definition, column)?.0; adopted - .extract::<&RustColumn>() + .extract::>() .ok_or_else(|| ext_exception("flow_php expected RustBackend::adopt() to build a RustColumn"))? } }; diff --git a/src/extension/flow-php-ext/src/builder.rs b/src/extension/flow-php-ext/src/builder.rs index 62625be2e4..c7663dcc09 100644 --- a/src/extension/flow-php-ext/src/builder.rs +++ b/src/extension/flow-php-ext/src/builder.rs @@ -439,9 +439,9 @@ impl RustColumnBuilder { Ok(()) } - fn same_kind<'a>(&self, column: &'a Zval) -> Option<&'a RustColumn> { + fn same_kind<'a>(&self, column: &'a Zval) -> Option> { column - .extract::<&RustColumn>() + .extract::>() .filter(|native| native.data().data_type() == &flow_batch_frame::kind::data_type(&self.plan.kind)) } diff --git a/src/extension/flow-php-ext/src/canonical_rows.rs b/src/extension/flow-php-ext/src/canonical_rows.rs index 53dfa1ac18..219d6726e8 100644 --- a/src/extension/flow-php-ext/src/canonical_rows.rs +++ b/src/extension/flow-php-ext/src/canonical_rows.rs @@ -49,12 +49,12 @@ pub fn row_columns(columns: &ZendHashTable) -> PhpResult> { pub fn named_column(name: Vec, column: &Zval) -> PhpResult { let adopted; - let native = match column.extract::<&RustColumn>() { + let native = match column.extract::>() { Some(native) => native, None => { adopted = RustBackend.adopt_result(column.shallow_clone())?.0; adopted - .extract::<&RustColumn>() + .extract::>() .ok_or_else(|| ext_exception("flow_php expected RustBackend::adopt() to return a RustColumn"))? } }; diff --git a/src/extension/flow-php-ext/src/column.rs b/src/extension/flow-php-ext/src/column.rs index 925c913eba..a66d925ed0 100644 --- a/src/extension/flow-php-ext/src/column.rs +++ b/src/extension/flow-php-ext/src/column.rs @@ -308,20 +308,22 @@ impl RustColumn { } pub fn concat(&self, others: &[&Zval]) -> PhpResult { + let natives = others + .iter() + .map(|other| { + other + .extract::>() + .filter(|native| native.data.data_type() == self.data.data_type()) + .ok_or_else(|| { + invalid_argument(format!( + "Flow\\ETL\\Values\\Column\\RustColumn cannot concat {}", + class_name(other) + )) + }) + }) + .collect::, _>>()?; let mut arrays: Vec<&dyn Array> = vec![self.data.as_ref()]; - - for other in others { - let native = other - .extract::<&RustColumn>() - .filter(|native| native.data.data_type() == self.data.data_type()) - .ok_or_else(|| { - invalid_argument(format!( - "Flow\\ETL\\Values\\Column\\RustColumn cannot concat {}", - class_name(other) - )) - })?; - arrays.push(native.data.as_ref()); - } + arrays.extend(natives.iter().map(|native| native.data.as_ref())); let data = arrow_select::concat::concat(&arrays).map_err(|e| match e { ArrowError::OffsetOverflowError(last) => offset_overflow(last as u64), diff --git a/src/extension/flow-php-ext/src/compare.rs b/src/extension/flow-php-ext/src/compare.rs index e09ada9e84..73a8fc6db7 100644 --- a/src/extension/flow-php-ext/src/compare.rs +++ b/src/extension/flow-php-ext/src/compare.rs @@ -7,7 +7,7 @@ use arrow_array::cast::AsArray; use arrow_array::types::{Float64Type, Int64Type}; use arrow_array::{ArrayRef, BooleanArray, Float64Array, LargeBinaryArray}; use ext_php_rs::exception::PhpException; -use ext_php_rs::types::Zval; +use ext_php_rs::types::{ClassRef, Zval}; use flow_column_kernels::compare::{compare_floats, compare_ordered, floats_of_ints, Operator}; use flow_column_kernels::digest::{hex_digests, HexDigest}; @@ -25,8 +25,8 @@ const ORDERED: [&str; 8] = [ pub fn native_comparison(left: &Zval, operator: &Zval, right: &Zval) -> Result, PhpException> { let (Some(left), Some(right), Some(operator)) = ( - left.extract::<&RustColumn>(), - right.extract::<&RustColumn>(), + left.extract::>(), + right.extract::>(), native_operator(operator)?, ) else { return Ok(None); @@ -52,7 +52,10 @@ pub fn native_text_match( needle: &Zval, kernel: fn(&LargeBinaryArray, &LargeBinaryArray) -> BooleanArray, ) -> Result, PhpException> { - let (Some(haystack), Some(needle)) = (haystack.extract::<&RustColumn>(), needle.extract::<&RustColumn>()) else { + let (Some(haystack), Some(needle)) = ( + haystack.extract::>(), + needle.extract::>(), + ) else { return Ok(None); }; @@ -72,7 +75,7 @@ pub fn native_text_match( // None sends the call to PhpBackend, as native_text_match does pub fn native_hash(strings: &Zval, digest: HexDigest) -> Result, PhpException> { - let Some(strings) = strings.extract::<&RustColumn>() else { + let Some(strings) = strings.extract::>() else { return Ok(None); }; diff --git a/src/extension/flow-php-ext/src/grouped_counts.rs b/src/extension/flow-php-ext/src/grouped_counts.rs index 8394250dee..c804825430 100644 --- a/src/extension/flow-php-ext/src/grouped_counts.rs +++ b/src/extension/flow-php-ext/src/grouped_counts.rs @@ -39,7 +39,7 @@ impl RustGroupedCounts { } } - match values.extract::<&RustColumn>() { + match values.extract::>() { Some(native) => { for (row, id) in ids.iter().enumerate() { self.counts[*id] += i64::from(!native.is_null_at(row)); @@ -68,7 +68,7 @@ impl RustGroupedCounts { #[php(name = "absorbEarlier")] pub fn absorb_earlier(&mut self, earlier: &Zval, into: &ZendHashTable) -> PhpResult<()> { - let counts = match earlier.extract::<&RustGroupedCounts>() { + let counts = match earlier.extract::>() { Some(native) => native.counts.clone(), None => call_method(earlier, "partials", &mut [])? .array() diff --git a/src/extension/flow-php-ext/src/grouped_totals.rs b/src/extension/flow-php-ext/src/grouped_totals.rs index 26875d5ae9..10f673ae48 100644 --- a/src/extension/flow-php-ext/src/grouped_totals.rs +++ b/src/extension/flow-php-ext/src/grouped_totals.rs @@ -35,9 +35,12 @@ pub struct RustGroupedTotals { impl RustGroupedTotals { pub fn add(&mut self, values: &Zval, ids: &Zval) -> PhpResult<()> { let ids = group_ids(ids)?; - let native = values.extract::<&RustColumn>(); + let native = values.extract::>(); - match native.map(|column| (column.plan().type_name.as_str(), column.data())) { + match native + .as_ref() + .map(|column| (column.plan().type_name.as_str(), column.data())) + { Some(("integer", data)) => { for (row, value) in data.as_primitive::().iter().enumerate() { match value { @@ -70,7 +73,7 @@ impl RustGroupedTotals { #[php(name = "absorbEarlier")] pub fn absorb_earlier(&mut self, earlier: &Zval, into: &ZendHashTable) -> PhpResult<()> { - let states = match earlier.extract::<&RustGroupedTotals>() { + let states = match earlier.extract::>() { Some(native) => (0..native.totals.counts.len()) .map(|id| { ( @@ -193,7 +196,7 @@ fn partial_states(partials: &Zval) -> PhpResult> { } pub fn group_ids(ids: &Zval) -> PhpResult> { - if let Some(native) = ids.extract::<&RustColumn>() { + if let Some(native) = ids.extract::>() { if let Some(ints) = native.data().as_primitive_opt::() { return ints .values() diff --git a/src/extension/flow-php-ext/src/multiset_hashes.rs b/src/extension/flow-php-ext/src/multiset_hashes.rs index f9add9ff16..07c9f2fa8d 100644 --- a/src/extension/flow-php-ext/src/multiset_hashes.rs +++ b/src/extension/flow-php-ext/src/multiset_hashes.rs @@ -65,7 +65,7 @@ impl RustGroupedMultisetHashes { #[php(name = "absorbEarlier")] pub fn absorb_earlier(&mut self, earlier: &Zval, into: &ZendHashTable) -> PhpResult<()> { - let lanes = match earlier.extract::<&RustGroupedMultisetHashes>() { + let lanes = match earlier.extract::>() { Some(native) => native.lanes.clone(), None => call_method(&call_method(earlier, "hashes", &mut [])?, "physicals", &mut [])? .array() diff --git a/src/extension/flow-php-ext/src/parquet/etl.rs b/src/extension/flow-php-ext/src/parquet/etl.rs index f062811818..a07d65e1a5 100644 --- a/src/extension/flow-php-ext/src/parquet/etl.rs +++ b/src/extension/flow-php-ext/src/parquet/etl.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use arrow_array::ArrayRef; use arrow_select::concat::concat; -use ext_php_rs::convert::{FromZvalMut, IntoZval}; +use ext_php_rs::convert::IntoZval; use ext_php_rs::flags::ClassFlags; use ext_php_rs::prelude::*; use ext_php_rs::types::{ZendHashTable, Zval}; @@ -163,7 +163,7 @@ pub struct RustParquetOpenSource { impl RustParquetOpenSource { /// `$file`: the `flow_php` engine's `FlowPhpParquetFileReader`, which owns the stream. pub fn __construct(file: &Zval) -> PhpResult { - if file.extract::<&EngineFileReader>().is_none() { + if file.extract::>().is_none() { return Err(ext_exception( "flow_php expected a Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFileReader", )); @@ -189,7 +189,7 @@ impl RustParquetOpenSource { let file = self .file - .extract::<&EngineFileReader>() + .extract::>() .ok_or_else(|| ext_exception("flow_php expected its FlowPhpParquetFileReader"))?; let batch_size = batch_size(batchSize)?; let (stream, meta) = file.read()?; @@ -255,7 +255,7 @@ 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 { - if writer.extract::<&EngineFileWriter>().is_none() { + if writer.extract::>().is_none() { return Err(ext_exception( "flow_php expected a Flow\\ETL\\Adapter\\Parquet\\IO\\Engine\\FlowPhpParquetFileWriter", )); @@ -291,7 +291,7 @@ impl RustParquetFileWriter { ht_for_each(columns, |name, index, column| { let name = column_key(name, index); - let data = match column.extract::<&RustColumn>() { + let data = match column.extract::>() { Some(native) => Arc::clone(native.data()), None => native_column(&call_method(&schema, "get", &mut [zval_str(&name)])?, column)?.1, }; @@ -301,7 +301,8 @@ impl RustParquetFileWriter { Ok(()) })?; - <&mut EngineFileWriter>::from_zval_mut(&mut self.writer) + self.writer + .extract::>() .ok_or_else(|| ext_exception("flow_php expected its FlowPhpParquetFileWriter"))? .write_arrow_columns(count, &arrays) } diff --git a/src/extension/flow-php-ext/src/sort.rs b/src/extension/flow-php-ext/src/sort.rs index 60e009a8fc..52dd93570e 100644 --- a/src/extension/flow-php-ext/src/sort.rs +++ b/src/extension/flow-php-ext/src/sort.rs @@ -10,7 +10,7 @@ use arrow_schema::{ArrowError, DataType}; use arrow_select::take::take; use ext_php_rs::convert::IntoZval; use ext_php_rs::exception::PhpException; -use ext_php_rs::types::{ZendHashTable, ZendObject, Zval}; +use ext_php_rs::types::{ClassRef, ZendHashTable, ZendObject, Zval}; use flow_column_kernels::sort::{php_ordered_floats, stable_indices, SortColumn, SortOptions}; use crate::backend::rows_from_columns; @@ -42,7 +42,7 @@ pub fn native_sort(rows: &Zval, sort_columns: &Zval) -> Result, Php ht_for_each(columns, |name, index, column| { let native = column - .extract::<&RustColumn>() + .extract::>() .ok_or_else(|| ext_exception("flow_php expected a RustColumn"))?; let gathered = take(native.data().as_ref(), &indices, None) .map_err(|e| ext_exception(format!("flow_php failed to gather sorted rows: {e}")))?; @@ -62,7 +62,7 @@ fn every_column_native(columns: &ZendHashTable) -> Result { let mut native = true; ht_for_each(columns, |_, _, column| { - native &= column.extract::<&RustColumn>().is_some(); + native &= column.extract::>().is_some(); Ok(()) })?; @@ -145,10 +145,10 @@ pub fn handed_off_native_bytes(rows: &Zval, sort_columns: &Zval) -> Result()) + .and_then(|column| column.extract::>()) { // a PHP copy holds a value twice the native width: a 16 B zval for an 8 B int, a zend_string header - keys += 2 * slice_bytes(native)?; + keys += 2 * slice_bytes(&native)?; } } @@ -159,8 +159,8 @@ fn native_bytes(columns: &ZendHashTable) -> Result { let mut bytes = 0; ht_for_each(columns, |_, _, column| { - if let Some(native) = column.extract::<&RustColumn>() { - bytes += slice_bytes(native)?; + if let Some(native) = column.extract::>() { + bytes += slice_bytes(&native)?; } Ok(()) @@ -197,13 +197,13 @@ fn array_slice_bytes(array: &dyn Array) -> Result { fn ordered_column<'a>( columns: &'a ZendHashTable, sort_column: &ZendObject, -) -> Result, PhpException> { +) -> Result>, PhpException> { let name = read_property(sort_column, "name")?; Ok(name .zend_str() .and_then(|name| ht_get(columns, name.as_bytes())) - .and_then(|column| column.extract::<&RustColumn>()) + .and_then(|column| column.extract::>()) .filter(|column| ORDERED.contains(&column.plan().type_name.as_str()))) } diff --git a/src/extension/flow-php-ext/src/text/batch.rs b/src/extension/flow-php-ext/src/text/batch.rs index 7254e8531d..89d5a1946c 100644 --- a/src/extension/flow-php-ext/src/text/batch.rs +++ b/src/extension/flow-php-ext/src/text/batch.rs @@ -118,7 +118,7 @@ pub fn batch(rows: &Zval, formats: &Formats, json_column_is_text: bool) -> PhpRe )) })?; - let native = match column.extract::<&RustColumn>() { + let native = match column.extract::>() { Some(native) => renders(&native.plan().values, formats, json_column_is_text) .then(|| (Rc::clone(native.plan()), ArrayRef::clone(native.data()))), None => { diff --git a/src/extension/flow-php-ext/tests/zts_request_threads.rs b/src/extension/flow-php-ext/tests/zts_request_threads.rs index 830817599f..e30b53e4b4 100644 --- a/src/extension/flow-php-ext/tests/zts_request_threads.rs +++ b/src/extension/flow-php-ext/tests/zts_request_threads.rs @@ -9,6 +9,7 @@ use ext_php_rs::ffi::{ use std::ffi::{c_char, CString}; use std::path::Path; use std::ptr::null_mut; +use std::sync::mpsc; const THREADS: usize = 8; const REQUESTS: usize = 5; @@ -48,6 +49,7 @@ fn start(extension: &Path) { let sapi = Box::leak(Box::new( SapiBuilder::new("zts-request-threads", "ZTS request threads") .ub_write_function(discard_output) + .php_ini_ignore(1) .build() .expect("the SAPI module builds"), )) as *mut SapiModule; @@ -79,11 +81,13 @@ fn request() -> Option { } #[test] -fn every_request_on_a_thread_that_did_not_load_the_extension_releases_its_native_bytes() { - assert!( - ext_php_rs::PHP_ZTS, - "zts_request_threads needs a ZTS PHP, this one is NTS" - ); +fn request_threads_release_their_native_bytes_and_exit_after_the_unload() { + const { + assert!( + ext_php_rs::PHP_ZTS, + "zts_request_threads needs a ZTS PHP, this one is NTS" + ) + }; let root = Path::new(env!("CARGO_MANIFEST_DIR")); let extension = root.join("ext/modules/flow_php.so"); let autoload = root.join("../../../vendor/autoload.php"); @@ -99,19 +103,43 @@ fn every_request_on_a_thread_that_did_not_load_the_extension_releases_its_native ); std::env::set_var("FLOW_PHP_AUTOLOAD", &autoload); - start(&extension); - let threads: Vec>> = (0..THREADS) - .map(|_| { - std::thread::spawn(|| { - let _thread = PhpThreadGuard::new(); - (0..REQUESTS).map(|_| request()).collect() + let (threads, late_bytes, late_worker) = std::thread::spawn(move || { + start(&extension); + // a panic on either side drops its sender, so the other side stops waiting instead of hanging + let (workload_ran, ran) = mpsc::channel(); + let (engine_down, down) = mpsc::channel::<()>(); + let late_worker = std::thread::spawn(move || { + let thread = PhpThreadGuard::new(); + let bytes = request(); + std::mem::forget(thread); + workload_ran.send(bytes).ok(); + down.recv().ok(); + }); + let threads: Vec>> = (0..THREADS) + .map(|_| { + std::thread::spawn(|| { + let _thread = PhpThreadGuard::new(); + (0..REQUESTS).map(|_| request()).collect() + }) + .join() + .expect("a request thread panicked") }) - .join() - .expect("a request thread panicked") - }) - .collect(); - stop(); + .collect(); + let late_bytes = ran.recv(); + stop(); + engine_down.send(()).ok(); + (threads, late_bytes, late_worker) + }) + .join() + .expect("the engine thread panicked"); + late_worker.join().expect("the late worker panicked"); + let late_bytes = late_bytes.expect("the late worker sent no request result"); + + assert!( + late_bytes.is_some(), + "the request of the late worker failed: {late_bytes:?}" + ); for (thread, bytes) in threads.iter().enumerate() { assert!( bytes.iter().all(Option::is_some), diff --git a/src/extension/parquet-engine/Cargo.toml b/src/extension/parquet-engine/Cargo.toml index 38afa0cbe9..9a1fb7ec8c 100644 --- a/src/extension/parquet-engine/Cargo.toml +++ b/src/extension/parquet-engine/Cargo.toml @@ -9,7 +9,7 @@ arrow-names = [] flow-php-names = [] [dependencies] -ext-php-rs = "0.16" +ext-php-rs = "0.17" arrow-array = { version = "60", features = ["ffi"] } arrow-buffer = "60" arrow-schema = { version = "60", features = ["canonical_extension_types"] } diff --git a/src/extension/pg-query-ext/ext/pg_query.c b/src/extension/pg-query-ext/ext/pg_query.c index 23585e6130..fab59413bf 100644 --- a/src/extension/pg-query-ext/ext/pg_query.c +++ b/src/extension/pg-query-ext/ext/pg_query.c @@ -12,6 +12,10 @@ #include +#ifdef COMPILE_DL_PG_QUERY +#include +#endif + #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" @@ -48,6 +52,15 @@ ZEND_GET_MODULE(pg_query) PHP_MINIT_FUNCTION(pg_query) { +#ifdef COMPILE_DL_PG_QUERY + Dl_info self; + + /* libpg_query registers a per-thread key destructor in this library; it must stay mapped until every thread exits */ + if (dladdr((void *) zm_startup_pg_query, &self) == 0 || dlopen(self.dli_fname, RTLD_NOW | RTLD_NODELETE) == NULL) { + return FAILURE; + } +#endif + pg_query_init(); /* Parse mode constants */ @@ -68,11 +81,7 @@ PHP_MINIT_FUNCTION(pg_query) PHP_MSHUTDOWN_FUNCTION(pg_query) { - /* Deliberately no pg_query_exit(). It frees libpg_query's TopMemoryContext, but pg_query_init() - * guards on a flag it never resets, so the contexts are gone and cannot be validly rebuilt. - * SAPIs that start the engine more than once per process -- embed, which the WASM playground - * uses -- then crash on the second startup. MSHUTDOWN runs at process teardown, so freeing - * here bought nothing anyway. */ + /* No pg_query_exit(): it frees only the calling thread's context and never resets its per-thread guard, so a later engine startup on this thread crashes */ return SUCCESS; } diff --git a/src/extension/pg-query-ext/tests/zts/zts_request_threads.c b/src/extension/pg-query-ext/tests/zts/zts_request_threads.c index 0eb1c46ea0..757efb6647 100644 --- a/src/extension/pg-query-ext/tests/zts/zts_request_threads.c +++ b/src/extension/pg-query-ext/tests/zts/zts_request_threads.c @@ -1,4 +1,4 @@ -// usage: zts_request_threads ; proves requests work on threads that did not load the extension, and a request after a parse error on the same thread gives correct results +// usage: zts_request_threads ; proves requests work on threads that did not load the extension, a request after a parse error gives correct results, and no thread crashes when it exits after the extension is unloaded #include #include #include @@ -66,39 +66,123 @@ static void *serve(void *status) return NULL; } -int main(int argc, char **argv) +struct lifecycle { + int argc; + char **argv; + int status; + int parsed; + int unloaded; + pthread_t late_worker; + int late_worker_started; + pthread_mutex_t lock; + pthread_cond_t changed; +}; + +static void *serve_after_unload(void *arg) { - if (argc != 2) { - fprintf(stderr, "usage: %s /absolute/path/to/zts.ini\n", argv[0]); - return 1; + struct lifecycle *lifecycle = arg; + + ts_resource(0); + ZEND_TSRMLS_CACHE_UPDATE(); + + int failed = request(PARSE_OK); + + pthread_mutex_lock(&lifecycle->lock); + + if (failed) { + lifecycle->status = 1; } - php_embed_module.php_ini_path_override = argv[1]; - php_embed_module.php_ini_ignore_cwd = 1; + lifecycle->parsed = 1; + pthread_cond_broadcast(&lifecycle->changed); + + while (!lifecycle->unloaded) { + pthread_cond_wait(&lifecycle->changed, &lifecycle->lock); + } + + pthread_mutex_unlock(&lifecycle->lock); + + return NULL; +} + +static void *run_engine(void *arg) +{ + struct lifecycle *lifecycle = arg; - if (php_embed_init(argc, argv) == FAILURE) { + if (php_embed_init(lifecycle->argc, lifecycle->argv) == FAILURE) { fprintf(stderr, "php_embed_init failed\n"); - return 1; + lifecycle->status = 1; + return NULL; } - int status = 0; + if (pthread_create(&lifecycle->late_worker, NULL, serve_after_unload, lifecycle) != 0) { + fprintf(stderr, "late worker failed to start\n"); + lifecycle->status = 1; + lifecycle->parsed = 1; + } else { + lifecycle->late_worker_started = 1; + } - for (int t = 0; t < THREADS && status == 0; t++) { + for (int t = 0; t < THREADS && lifecycle->status == 0; t++) { pthread_t thread; - if (pthread_create(&thread, NULL, serve, &status) != 0 || pthread_join(thread, NULL) != 0) { + if (pthread_create(&thread, NULL, serve, &lifecycle->status) != 0 || pthread_join(thread, NULL) != 0) { fprintf(stderr, "thread %d failed to run\n", t); - return 1; + lifecycle->status = 1; } } + pthread_mutex_lock(&lifecycle->lock); + + while (!lifecycle->parsed) { + pthread_cond_wait(&lifecycle->changed, &lifecycle->lock); + } + + pthread_mutex_unlock(&lifecycle->lock); + php_embed_shutdown(); - if (status != 0) { + pthread_mutex_lock(&lifecycle->lock); + lifecycle->unloaded = 1; + pthread_cond_broadcast(&lifecycle->changed); + pthread_mutex_unlock(&lifecycle->lock); + + return NULL; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "usage: %s /absolute/path/to/zts.ini\n", argv[0]); + return 1; + } + + php_embed_module.php_ini_path_override = argv[1]; + php_embed_module.php_ini_ignore_cwd = 1; + + struct lifecycle lifecycle = { + .argc = argc, + .argv = argv, + .lock = PTHREAD_MUTEX_INITIALIZER, + .changed = PTHREAD_COND_INITIALIZER, + }; + pthread_t engine; + + if (pthread_create(&engine, NULL, run_engine, &lifecycle) != 0 || pthread_join(engine, NULL) != 0) { + fprintf(stderr, "engine thread failed to run\n"); + return 1; + } + + if (lifecycle.late_worker_started && pthread_join(lifecycle.late_worker, NULL) != 0) { + fprintf(stderr, "late worker failed to run\n"); + return 1; + } + + if (lifecycle.status != 0) { return 1; } - printf("%d threads x %d rounds of 2 requests passed\n", THREADS, REQUESTS); + printf("%d threads x %d rounds of 2 requests passed; the engine thread and a parsing thread exited after the unload\n", THREADS, REQUESTS); return 0; }