Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions src/extension/arrow-ext/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/extension/arrow-ext/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
57 changes: 42 additions & 15 deletions src/extension/arrow-ext/tests/zts_request_threads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -71,23 +73,48 @@ fn request(code: &str) -> Option<i64> {
}

#[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<Vec<Option<i64>>> = (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<Vec<Option<i64>>> = (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:?}");
Expand Down
8 changes: 4 additions & 4 deletions src/extension/flow-php-ext/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/extension/flow-php-ext/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
9 changes: 6 additions & 3 deletions src/extension/flow-php-ext/src/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -56,8 +56,11 @@ pub fn native_modulo(left: &Zval, right: &Zval) -> Result<Option<RustColumn>, 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::<ClassRef<RustColumn>>()?,
right.extract::<ClassRef<RustColumn>>()?,
);

(left.data().null_count() == 0 && right.data().null_count() == 0).then_some((left, right))
}
10 changes: 5 additions & 5 deletions src/extension/flow-php-ext/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ impl RustBackend {

#[php(name = "isNull")]
pub fn is_null(&self, column: &Zval) -> PhpResult<ColumnValue> {
match column.extract::<&RustColumn>() {
match column.extract::<ClassRef<RustColumn>>() {
Some(native) => Ok(ColumnValue(boolean_column(is_null(native.data()))?.into_zval(false)?)),
None => self.adopt_result(call_method(
&instance(PHP_BACKEND)?,
Expand All @@ -415,7 +415,7 @@ impl RustBackend {

#[php(name = "isNotNull")]
pub fn is_not_null(&self, column: &Zval) -> PhpResult<ColumnValue> {
match column.extract::<&RustColumn>() {
match column.extract::<ClassRef<RustColumn>>() {
Some(native) => Ok(ColumnValue(
boolean_column(is_not_null(native.data()))?.into_zval(false)?,
)),
Expand Down Expand Up @@ -468,7 +468,7 @@ impl RustBackend {
}

pub fn adopt(&self, definition: &Zval, column: &Zval) -> PhpResult<ColumnValue> {
if column.extract::<&RustColumn>().is_some() {
if column.extract::<ClassRef<RustColumn>>().is_some() {
return Ok(ColumnValue(column.shallow_clone()));
}

Expand Down Expand Up @@ -668,12 +668,12 @@ pub fn adopt_batch(adoption: &Adoption, held: HeldBatch) -> PhpResult<Zval> {
/// `$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<TypePlan>, ArrayRef)> {
let adopted;
let native = match column.extract::<&RustColumn>() {
let native = match column.extract::<ClassRef<RustColumn>>() {
Some(native) => native,
None => {
adopted = RustBackend.adopt(definition, column)?.0;
adopted
.extract::<&RustColumn>()
.extract::<ClassRef<RustColumn>>()
.ok_or_else(|| ext_exception("flow_php expected RustBackend::adopt() to build a RustColumn"))?
}
};
Expand Down
4 changes: 2 additions & 2 deletions src/extension/flow-php-ext/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ClassRef<'a, RustColumn>> {
column
.extract::<&RustColumn>()
.extract::<ClassRef<RustColumn>>()
.filter(|native| native.data().data_type() == &flow_batch_frame::kind::data_type(&self.plan.kind))
}

Expand Down
4 changes: 2 additions & 2 deletions src/extension/flow-php-ext/src/canonical_rows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ pub fn row_columns(columns: &ZendHashTable) -> PhpResult<Vec<RowColumn>> {

pub fn named_column(name: Vec<u8>, column: &Zval) -> PhpResult<RowColumn> {
let adopted;
let native = match column.extract::<&RustColumn>() {
let native = match column.extract::<ClassRef<RustColumn>>() {
Some(native) => native,
None => {
adopted = RustBackend.adopt_result(column.shallow_clone())?.0;
adopted
.extract::<&RustColumn>()
.extract::<ClassRef<RustColumn>>()
.ok_or_else(|| ext_exception("flow_php expected RustBackend::adopt() to return a RustColumn"))?
}
};
Expand Down
28 changes: 15 additions & 13 deletions src/extension/flow-php-ext/src/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,20 +308,22 @@ impl RustColumn {
}

pub fn concat(&self, others: &[&Zval]) -> PhpResult<RustColumn> {
let natives = others
.iter()
.map(|other| {
other
.extract::<ClassRef<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)
))
})
})
.collect::<Result<Vec<_>, _>>()?;
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),
Expand Down
13 changes: 8 additions & 5 deletions src/extension/flow-php-ext/src/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -25,8 +25,8 @@ const ORDERED: [&str; 8] = [

pub fn native_comparison(left: &Zval, operator: &Zval, right: &Zval) -> Result<Option<RustColumn>, PhpException> {
let (Some(left), Some(right), Some(operator)) = (
left.extract::<&RustColumn>(),
right.extract::<&RustColumn>(),
left.extract::<ClassRef<RustColumn>>(),
right.extract::<ClassRef<RustColumn>>(),
native_operator(operator)?,
) else {
return Ok(None);
Expand All @@ -52,7 +52,10 @@ pub fn native_text_match(
needle: &Zval,
kernel: fn(&LargeBinaryArray, &LargeBinaryArray) -> BooleanArray,
) -> Result<Option<RustColumn>, PhpException> {
let (Some(haystack), Some(needle)) = (haystack.extract::<&RustColumn>(), needle.extract::<&RustColumn>()) else {
let (Some(haystack), Some(needle)) = (
haystack.extract::<ClassRef<RustColumn>>(),
needle.extract::<ClassRef<RustColumn>>(),
) else {
return Ok(None);
};

Expand All @@ -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<Option<RustColumn>, PhpException> {
let Some(strings) = strings.extract::<&RustColumn>() else {
let Some(strings) = strings.extract::<ClassRef<RustColumn>>() else {
return Ok(None);
};

Expand Down
Loading