This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 6d50c1ab08 [python] Use Native execution by default (#11144)
6d50c1ab08 is described below
commit 6d50c1ab088aa5b539982f8a5a090602c98473ff
Author: Jingsong Lee <[email protected]>
AuthorDate: Sat Nov 14 15:44:56 2026 +0800
[python] Use Native execution by default (#11144)
---
.github/workflows/ci-python.yml | 114 ++++++-----
docs/docs/pypaimon/installation.md | 22 +++
docs/docs/pypaimon/pytorch.md | 20 +-
docs/docs/pypaimon/reading.md | 4 +
docs/docs/pypaimon/writing.md | 17 +-
paimon-python/README.md | 37 ++--
paimon-python/conftest.py | 45 +++--
paimon-python/dev/lint-python.sh | 10 +-
paimon-python/dev/test_packaging.py | 38 ++--
.../pypaimon/common/options/core_options.py | 10 +-
.../pypaimon/execution/native/read/table_read.py | 24 ++-
paimon-python/pypaimon/execution/native/table.py | 11 ++
.../pypaimon/execution/native/write/commit.py | 2 +-
.../execution/native/write/native_commit.py | 8 +-
.../execution/native/write/native_merge_into.py | 3 +-
.../execution/native/write/native_update.py | 12 +-
.../execution/native/write/native_write.py | 7 +
paimon-python/pypaimon/read/read_dispatch.py | 5 +
paimon-python/pypaimon/tests/binary_row_test.py | 5 +-
.../tests/commit_update_schema_identity_test.py | 28 ++-
.../pypaimon/tests/default_execution_test.py | 81 ++++++++
.../pypaimon/tests/e2e/java_py_read_write_test.py | 3 +-
.../pypaimon/tests/execution_preference_test.py | 62 ++++++
.../pypaimon/tests/lazy_read_execution_test.py | 7 +-
.../pypaimon/tests/lerobot_native_reader_test.py | 18 +-
.../pypaimon/tests/multimodal_lerobot_ray_test.py | 25 ++-
.../pypaimon/tests/native_branch_write_test.py | 11 +-
paimon-python/pypaimon/tests/native_commit_test.py | 17 +-
.../tests/native_data_evolution_commit_test.py | 24 ++-
.../pypaimon/tests/native_file_scan_test.py | 21 +-
.../tests/native_interop_compatibility_test.py | 217 +++++++++++++++++++++
.../pypaimon/tests/native_loaded_schema_io_test.py | 12 +-
.../pypaimon/tests/native_plan_expanded_test.py | 3 +-
.../pypaimon/tests/native_plan_incremental_test.py | 1 +
.../pypaimon/tests/native_plan_integration_test.py | 30 +--
.../pypaimon/tests/native_plan_rest_test.py | 3 +-
paimon-python/pypaimon/tests/native_plan_test.py | 16 +-
.../tests/native_precomputed_bucket_test.py | 7 +-
.../pypaimon/tests/native_row_sidecar_test.py | 3 +-
.../tests/native_test_instrumentation_test.py | 34 ++++
.../native_update_inactive_vector_option_test.py | 13 +-
.../pypaimon/tests/native_variant_update_test.py | 56 +++++-
.../pypaimon/tests/native_video_read_test.py | 8 +-
paimon-python/pypaimon/tests/native_write_test.py | 8 +-
.../pypaimon/tests/native_write_type_test.py | 22 ++-
.../pypaimon/tests/parquet_row_range_test.py | 2 +
.../tests/public_streaming_table_scan_test.py | 8 +-
.../tests/ray_native_row_id_recovery_test.py | 48 +++--
paimon-python/pypaimon/tests/torch_read_test.py | 13 +-
paimon-python/pypaimon/tests/variant_test.py | 2 +-
paimon-python/pypaimon/write/backend_dispatch.py | 3 +-
paimon-python/pyproject.toml | 7 +-
tools/ci/test_python_commands.py | 70 +++++++
53 files changed, 1017 insertions(+), 260 deletions(-)
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml
index a40f5df9e3..cddb497d0c 100644
--- a/.github/workflows/ci-python.yml
+++ b/.github/workflows/ci-python.yml
@@ -32,10 +32,11 @@ env:
jobs:
# Lint + test on selected versions only (3.6 / 3.7 low end, 3.10 / 3.11 /
3.12 / 3.13 current), not every Python version.
test:
- name: Tests / Python ${{ matrix.python-version }}
+ name: ${{ (matrix.python-version == '3.6.15' || matrix.python-version ==
'3.7') && 'Legacy Python' || 'Native' }} / Python ${{ matrix.python-version }}
env:
- # Native planning, reading, writing and REST commits run in Native CI.
- PYTEST_ADDOPTS: "-m 'not native_plan'"
+ PYPAIMON_TEST_EXECUTION: ${{ (matrix.python-version == '3.6.15' ||
matrix.python-version == '3.7') && 'python' || 'native' }}
+ PYTEST_ADDOPTS: '--durations=20'
+ DAFT_RUNNER: 'native'
timeout-minutes: 90
runs-on: ubuntu-latest
container: "python:${{ matrix.python-version }}-slim"
@@ -142,7 +143,7 @@ jobs:
python paimon-python/dev/install.py legacy
else
python -m pip install torch --index-url
https://download.pytorch.org/whl/cpu
- dependency_group=python-tests
+ dependency_group=dev
if [[ "${{ matrix.python-version }}" == "3.10" ]]; then
dependency_group=torch
fi
@@ -150,12 +151,21 @@ jobs:
fi
python -m pip check
- - name: Verify Python test environment
+ - name: Verify default execution environment
run: |
python - <<'PY'
import importlib.util
+ import sys
- assert importlib.util.find_spec('pypaimon_rust') is None, 'Rust is
tested in Native CI'
+ if sys.version_info >= (3, 10):
+ from importlib.metadata import version
+ from packaging.version import Version
+ import pypaimon_rust.datafusion
+
+ assert Version(version('pypaimon-rust')) >= Version('0.5.0')
+ print('pypaimon-rust', version('pypaimon-rust'))
+ else:
+ assert importlib.util.find_spec('pypaimon_rust') is None
PY
- name: Run lint-python.sh
@@ -191,11 +201,15 @@ jobs:
pypaimon/tests/file_io_test.py
pypaimon/tests/filesystem_catalog_test.py \
pypaimon/tests/table_update_arrow_compatibility_test.py
- rust-plan:
- name: Native CI
+ python-execution:
+ name: Python Execution
timeout-minutes: 90
runs-on: ubuntu-latest
container: "python:3.11-slim"
+ env:
+ PYPAIMON_TEST_EXECUTION: 'python'
+ PYTEST_ADDOPTS: "-m 'not native_plan' --durations=20"
+ DAFT_RUNNER: 'native'
steps:
- name: Checkout code
uses: actions/checkout@v6
@@ -206,53 +220,65 @@ jobs:
build-essential git curl cmake pkg-config libssl-dev libclang-dev
tzdata \
&& rm -rf /var/lib/apt/lists/*
- - name: Install Rust toolchain
+ - name: Set up JDK ${{ env.JDK_VERSION }}
+ uses: actions/setup-java@v5
+ with:
+ java-version: ${{ env.JDK_VERSION }}
+ distribution: 'temurin'
+
+ - name: Set up Maven
+ shell: bash
+ env:
+ MAVEN_VERSION: '3.8.8'
run: |
- curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s --
-y --default-toolchain stable --profile minimal
- echo "$HOME/.cargo/bin" >> $GITHUB_PATH
+
maven_archive="${RUNNER_TEMP}/apache-maven-${MAVEN_VERSION}-bin.tar.gz"
+ curl --fail --location --retry 3 --retry-all-errors --retry-delay 2 \
+ --output "$maven_archive" \
+
"https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/${MAVEN_VERSION}/apache-maven-${MAVEN_VERSION}-bin.tar.gz"
\
+ || curl --fail --location --retry 3 --retry-all-errors
--retry-delay 2 \
+ --output "$maven_archive" \
+
"https://archive.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz"
+ tar -xzf "$maven_archive" -C "$RUNNER_TEMP"
+ echo "${RUNNER_TEMP}/apache-maven-${MAVEN_VERSION}/bin" >>
"$GITHUB_PATH"
+
+ - name: Cache Maven dependencies
+ uses: actions/cache@v5
+ with:
+ path: ~/.m2/repository
+ key: ci-maven-python-${{ runner.os }}-${{ runner.arch }}-${{
hashFiles('**/pom.xml') }}
+ restore-keys: |
+ ci-maven-python-${{ runner.os }}-${{ runner.arch }}-
- - name: Build paimon-rust from main
+ - name: Build Java
run: |
- python -m pip install --upgrade pip
- python -m pip install --upgrade
"git+https://github.com/apache/paimon-rust.git@main#subdirectory=bindings/python"
+ mvn -T 2C -B -ntp install -DskipTests \
+ -pl
paimon-core,paimon-lance,paimon-vortex/paimon-vortex-format,paimon-full-text,paimon-lumina,paimon-vector
-am
- name: Install Python test dependencies
run: |
+ python -m pip install --upgrade pip
python -m pip install torch --index-url
https://download.pytorch.org/whl/cpu
python -m pip install -e ./paimon-python --group
./paimon-python/pyproject.toml:dev
python -m pip check
- - name: Verify native wheel provenance
- run: |
- python - <<'PY'
- import importlib.metadata as metadata
- import json
-
- import pypaimon_rust
- import pypaimon_rust.datafusion
-
- distribution = metadata.distribution('pypaimon-rust')
- source = json.loads(distribution.read_text('direct_url.json'))
- print('pypaimon-rust', distribution.version,
- 'commit', source['vcs_info']['commit_id'])
- assert source['vcs_info']['requested_revision'] == 'main'
- assert callable(getattr(pypaimon_rust, 'temporal_match', None)), (
- 'Native CI requires the real temporal_match kernel')
- PY
-
- - name: Run Python tests with native planning, reading, writing,
updating and committing
+ - name: Run Python execution tests
shell: bash
- env:
- DAFT_RUNNER: 'native'
- PYTEST_ADDOPTS: '--durations=20'
- PYPAIMON_TEST_NATIVE_PLAN: '1'
- PYPAIMON_TEST_NATIVE_READ: '1'
- PYPAIMON_TEST_NATIVE_WRITE: '1'
- PYPAIMON_TEST_NATIVE_UPDATE: '1'
- PYPAIMON_TEST_NATIVE_COMMIT: '1'
run: |
bash paimon-python/dev/lint-python.sh -i pytest
+ native-timezones:
+ name: Native temporal casts
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-python@v6
+ with:
+ python-version: '3.11'
+ - name: Install Python test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install -e ./paimon-python --group
./paimon-python/pyproject.toml:test
- name: Verify native temporal casts in non-UTC system zones
shell: bash
env:
@@ -390,12 +416,10 @@ jobs:
python -m pip install torch --index-url
https://download.pytorch.org/whl/cpu
python -m pip install -e ./paimon-python --group
./paimon-python/pyproject.toml:torch
python -m pip check
- - name: Verify Python test environment
+ - name: Verify native test environment
run: |
python - <<'PY'
- import importlib.util
-
- assert importlib.util.find_spec('pypaimon_rust') is None, 'Rust is
tested in Native CI'
+ import pypaimon_rust.datafusion
PY
- name: Run lint-python.sh
diff --git a/docs/docs/pypaimon/installation.md
b/docs/docs/pypaimon/installation.md
index dbb28fc5eb..7854abec70 100644
--- a/docs/docs/pypaimon/installation.md
+++ b/docs/docs/pypaimon/installation.md
@@ -45,6 +45,28 @@ The package includes the core catalog, table, Arrow, and
pandas APIs, as well as
the `paimon` command. Core table reads and writes do not require a JVM or a
running Flink or Spark cluster.
+On Python 3.10 and newer, installation also includes `pypaimon-rust>=0.5.0`.
+Split planning, reads, writes, updates, and commits use Native execution by
+default when supported. Python 3.6–3.9 and unsupported operations use Python
+execution. To select Python execution explicitly for a table, disable all four
+options:
+
+```python
+table = table.copy({
+ "scan.native-plan.enabled": "false",
+ "read.native.enabled": "false",
+ "write.native.enabled": "false",
+ "commit.native.enabled": "false",
+})
+```
+
+The options are independent; disabling only native reads does not disable
native
+split planning or writes. Explicit `scan.native-plan.enabled=false` selects the
+Python planner even when native reads are enabled. Explicit
+`write.native.enabled=false` also selects Python row-ID update routing.
+REST catalog management continues to use the Python
+REST client.
+
## Optional dependencies
Install only the extras needed by your workload. Quote package names containing
diff --git a/docs/docs/pypaimon/pytorch.md b/docs/docs/pypaimon/pytorch.md
index 05b4908f24..7cdc10cbaf 100644
--- a/docs/docs/pypaimon/pytorch.md
+++ b/docs/docs/pypaimon/pytorch.md
@@ -29,6 +29,13 @@ under the License.
This requires `torch` to be installed.
+For multi-worker loading, set `multiprocessing_context="spawn"` and create and
+iterate the DataLoader inside an `if __name__ == "__main__":` guarded entry
+point. Native row iteration uses multithreaded Polars; forking after a read can
+inherit locked worker state and hang. See the
+[Polars multiprocessing
guide](https://docs.pola.rs/user-guide/misc/multiprocessing/).
+Define custom transforms and collators at module scope so workers can import
them.
+
You can read all the data into a `torch.utils.data.Dataset` or
`torch.utils.data.IterableDataset`:
```python
@@ -40,6 +47,7 @@ dataloader = DataLoader(
dataset,
batch_size=2,
num_workers=2, # Concurrency to read data
+ multiprocessing_context="spawn",
shuffle=False
)
@@ -176,7 +184,8 @@ dataset = table_read.to_torch(
batch_format="torch",
batch_size=1024,
)
-dataloader = DataLoader(dataset, batch_size=None, num_workers=2)
+dataloader = DataLoader(dataset, batch_size=None, num_workers=2,
+ multiprocessing_context="spawn")
for batch in dataloader:
train(batch["features"], batch["label"])
@@ -210,7 +219,8 @@ dataset = table_read.to_torch(
buffer_size=4096,
max_buffer_input_splits=4,
)
-loader = DataLoader(dataset, batch_size=None, num_workers=2)
+loader = DataLoader(dataset, batch_size=None, num_workers=2,
+ multiprocessing_context="spawn")
for epoch in range(10):
dataset.set_epoch(epoch)
@@ -289,7 +299,8 @@ dataset = (
)
)
-loader = DataLoader(dataset, batch_size=32, num_workers=4, shuffle=True)
+loader = DataLoader(dataset, batch_size=32, num_workers=4, shuffle=True,
+ multiprocessing_context="spawn")
```
Each raw item contains scalar group/order keys, a list for every selected
column,
@@ -463,6 +474,7 @@ from torchdata.stateful_dataloader import StatefulDataLoader
loader_config = dict(batch_size=32, shuffle=True, drop_last=False,
num_workers=4, prefetch_factor=2,
+ multiprocessing_context="spawn",
persistent_workers=True, in_order=True)
# Include the application's preprocessing/normalization version in this
contract.
run_config = dict(loader=loader_config, preprocessing="train-v1", world_size=1,
@@ -608,6 +620,7 @@ dataloader = DataLoader(
dataset,
batch_size=32,
num_workers=2,
+ multiprocessing_context="spawn",
shuffle=False,
)
```
@@ -648,6 +661,7 @@ dataloader = DataLoader(
dataset,
batch_size=32,
num_workers=2,
+ multiprocessing_context="spawn",
shuffle=False,
)
```
diff --git a/docs/docs/pypaimon/reading.md b/docs/docs/pypaimon/reading.md
index ec0d09c12e..3eb6e13f29 100644
--- a/docs/docs/pypaimon/reading.md
+++ b/docs/docs/pypaimon/reading.md
@@ -70,6 +70,10 @@ Nested `ROW` fields use dot notation, for example
key. Shared-shredding MAP files prune unselected keys; other layouts read the
full MAP and extract the key.
+With Native runtime 0.5.0, ORC shared-shredding MAP files use the Python
reader.
+This also applies to retained ORC files after the table's write format or MAP
+storage layout changes. Parquet shared-shredding MAP reads support Native
execution.
+
Limitations:
- Data-evolution tables support MAP keys, but not nested ROW fields.
diff --git a/docs/docs/pypaimon/writing.md b/docs/docs/pypaimon/writing.md
index 9925af72f9..6b5e15d739 100644
--- a/docs/docs/pypaimon/writing.md
+++ b/docs/docs/pypaimon/writing.md
@@ -90,9 +90,20 @@ the same method. Changing a builder affects only operations
created afterward.
### Native Write and Commit
-With the `pypaimon-rust` extension installed, set `write.native.enabled=true`
-to use Rust for Parquet/BLOB writes and `commit.native.enabled=true` to use
-Rust for REST snapshot publication. Batch and stream writers retain the same
+On Python 3.10+, `pypaimon-rust>=0.5.0` is installed by default.
+`write.native.enabled` and `commit.native.enabled` both default to `true`,
+selecting Rust for supported Parquet/BLOB writes and REST snapshot publication.
+Set either option to `false` to select its Python execution path.
+With the 0.5.0 Native runtime, ordinary fixed-bucket append tables use Python
+writers to retain advancing file sequence ranges for Java compaction.
+Configured shredded VARIANT columns use Python writes and updates to retain the
+nested Parquet field IDs required by Java readers. Direct updates that write
only
+ordinary columns can still use Native execution.
+Data Evolution commits containing retained row-ID
+files use Python publication so each snapshot attempt validates the written
+field IDs against its current schema. Native writes and update preparation
+remain available; this selection happens before any snapshot mutation.
+Batch and stream writers retain the same
prepare-and-commit lifecycle. Native commits also support overwrite,
`truncate_table()`, `truncate_partitions()` and commit callbacks.
Overwrite and truncate record an OVERWRITE snapshot even when no files match,
diff --git a/paimon-python/README.md b/paimon-python/README.md
index 2c6379e123..b90eeaeee2 100644
--- a/paimon-python/README.md
+++ b/paimon-python/README.md
@@ -10,6 +10,13 @@ This PyPi package contains the Python APIs for using Paimon.
Pypaimon requires Python 3.6+.
+On Python 3.10+, `pip install pypaimon` also installs `pypaimon-rust>=0.5.0`.
+Native split planning, reads, writes, updates and commits are enabled by
default
+for supported operations. Older Python versions and unsupported operations use
+Python execution. To select Python execution explicitly, set
+`scan.native-plan.enabled`, `read.native.enabled`, `write.native.enabled` and
+`commit.native.enabled` to `false` in the table options.
+
# Build
Run from `paimon-python/` with pip supporting dependency groups.
@@ -239,8 +246,8 @@ Native planning, reading, writing and committing remain
available for table data
# Native write and commit
-PyPaimon can write Arrow batches through the optional `pypaimon-rust` runtime.
-Enable it on a table independently of native commit:
+PyPaimon writes Arrow batches through `pypaimon-rust` by default on Python
3.10+.
+Native writes and commits can be configured independently:
```python
native_table = table.copy({"write.native.enabled": "true",
@@ -398,12 +405,13 @@ uncommitted and will never be submitted. Never call it
after a commit with an
unknown outcome: publication may have succeeded before its response failed.
Internal failure paths preserve prepared files instead of calling commit abort.
-Both native options are disabled by default.
+Both native options are enabled by default.
# Native commit
-PyPaimon can submit append and batch overwrite commits through the optional
-`pypaimon-rust` runtime. Enable it independently of native planning and
reading:
+PyPaimon can submit append and batch overwrite commits through
+`pypaimon-rust`, installed by default on Python 3.10+. Native commit is enabled
+by default and configured independently of native planning and reading:
```python
native_table = table.copy({"commit.native.enabled": "true"})
@@ -447,22 +455,24 @@ not installed, commits use Python. The current native
route supports main-branch
tables using filesystem/JDBC catalogs or `FileStoreTable.from_path()` with
standard FileIO. Truncate, REST/catalog-managed publication, custom
FileIO/environments, commit callbacks, and snapshot properties use Python.
-Data-evolution updates that need Python's row-id conflict rewriting also retain
-the Python path. Compact increments remain unsupported by both committers.
+With Native 0.5.0, Data Evolution commits containing retained row-ID files use
+Python publication to validate written field IDs against the schema of each
+snapshot attempt. Native write and update preparation remain available.
+Compact increments remain unsupported by both committers.
Fallback is limited to runtime availability, table construction and message
conversion before a native mutation starts. A native commit error propagates;
the adapter neither retries it through Python nor aborts files, since the
-snapshot may already have been published. The option is disabled by default.
+snapshot may already have been published. The option is enabled by default.
# Native scan planning
-PyPaimon can plan splits with the optional `pypaimon-rust` package. Planning
and
-reading are independently selectable, so native plans can still use the Python
-reader:
+PyPaimon plans splits with `pypaimon-rust` by default on Python 3.10+.
+Planning and reading are independently selectable, so native plans can still
+use the Python reader:
```python
-native_table = table.copy({"scan.native-plan.enabled": "true"})
+native_table = table.copy({"read.native.enabled": "false"})
builder = native_table.new_read_builder()
plan = builder.new_scan().plan()
rows = builder.new_read().to_arrow(plan.splits())
@@ -656,7 +666,8 @@ Continuous streaming delegates planning and resume state to
Rust core.
retaining scan filters and limits and requiring unrestricted query
authorization.
Writer restore, overwrite and index construction use this entrypoint and
delegate
planning to Rust core when Native planning is enabled.
-Native planning remains optional and is disabled by default.
+Native planning is enabled by default; set `scan.native-plan.enabled=false`
+and `read.native.enabled=false` to select Python planning and reading.
Binary partition keys use UTF-8 text and normal partition escaping in both
`partition.legacy-name` modes, matching Java. This makes repeated writes to the
diff --git a/paimon-python/conftest.py b/paimon-python/conftest.py
index 6316a3508a..da8764104d 100644
--- a/paimon-python/conftest.py
+++ b/paimon-python/conftest.py
@@ -25,6 +25,7 @@ _NATIVE_READ_ENV = "PYPAIMON_TEST_NATIVE_READ"
_NATIVE_WRITE_ENV = "PYPAIMON_TEST_NATIVE_WRITE"
_NATIVE_UPDATE_ENV = "PYPAIMON_TEST_NATIVE_UPDATE"
_NATIVE_COMMIT_ENV = "PYPAIMON_TEST_NATIVE_COMMIT"
+_EXECUTION_ENV = "PYPAIMON_TEST_EXECUTION"
_native_plan_count = 0
_native_read_count = 0
_native_write_count = 0
@@ -62,24 +63,28 @@ def native_rest_catalog(tmp_path):
server.shutdown()
+def _native_enabled(key):
+ return os.environ.get(key, "1" if os.environ.get(_EXECUTION_ENV) ==
"native" else "0") == "1"
+
+
def _native_plan_enabled():
- return os.environ.get(_NATIVE_PLAN_ENV) == "1"
+ return _native_enabled(_NATIVE_PLAN_ENV)
def _native_read_enabled():
- return os.environ.get(_NATIVE_READ_ENV) == "1"
+ return _native_enabled(_NATIVE_READ_ENV)
def _native_write_enabled():
- return os.environ.get(_NATIVE_WRITE_ENV) == "1"
+ return _native_enabled(_NATIVE_WRITE_ENV)
def _native_commit_enabled():
- return os.environ.get(_NATIVE_COMMIT_ENV) == "1"
+ return _native_enabled(_NATIVE_COMMIT_ENV)
def _native_update_enabled():
- return os.environ.get(_NATIVE_UPDATE_ENV) == "1"
+ return _native_enabled(_NATIVE_UPDATE_ENV)
def pytest_configure(config):
@@ -88,7 +93,9 @@ def pytest_configure(config):
config.addinivalue_line(
"markers", "python_read: keep Python reader assertions on the Python
lane")
config.addinivalue_line(
- "markers", "native_plan: exercise the real Rust planner in the Rust
main CI job")
+ "markers", "native_plan: exercise the released Rust runtime in Native
CI")
+ config.addinivalue_line(
+ "markers", "execution_defaults: exercise product defaults without CI
backend overrides")
config.addinivalue_line(
"markers", "python_write: keep Python writer assertions on the Python
lane")
config.addinivalue_line(
@@ -198,7 +205,7 @@ def pytest_configure(config):
def pytest_collection_modifyitems(items):
if _native_plan_enabled():
return
- skip_native = pytest.mark.skip(reason="native plan tests run in the Rust
Plan job")
+ skip_native = pytest.mark.skip(reason="native plan tests run in Native CI")
for item in items:
if item.get_closest_marker("native_plan") is not None:
item.add_marker(skip_native)
@@ -209,6 +216,9 @@ def enable_native_backends(request, monkeypatch):
global _force_native_for_test, _force_native_read_for_test
global _force_native_write_for_test, _force_native_commit_for_test
global _force_native_update_for_test
+ if request.node.get_closest_marker("execution_defaults") is not None:
+ yield
+ return
python_plan = request.node.get_closest_marker("python_plan") is not None
python_read = request.node.get_closest_marker("python_read") is not None
python_write = request.node.get_closest_marker("python_write") is not None
@@ -223,38 +233,35 @@ def enable_native_backends(request, monkeypatch):
force_write = _native_write_enabled() and not python_write
force_commit = _native_commit_enabled() and not python_commit
force_update = _native_update_enabled() and not python_write
- if not (force_plan or force_read or force_write or force_commit or
force_update):
- yield
- return
-
from pypaimon.common.options.core_options import CoreOptions
- if force_plan:
+ python_execution = os.environ.get(_EXECUTION_ENV) == "python"
+ if python_execution or python_plan:
original_plan = CoreOptions.native_plan_enabled
def plan_enabled(self, default=None):
- return original_plan(self, True if default is None else default)
+ return original_plan(self, False if default is None else default)
monkeypatch.setattr(CoreOptions, "native_plan_enabled", plan_enabled)
- if force_read:
+ if python_execution or python_plan or python_read:
original_read = CoreOptions.native_read_enabled
def read_enabled(self, default=None):
- return original_read(self, True if default is None else default)
+ return original_read(self, False if default is None else default)
monkeypatch.setattr(CoreOptions, "native_read_enabled", read_enabled)
- if force_write or force_update:
+ if python_execution or python_write:
original_write = CoreOptions.native_write_enabled
def write_enabled(self, default=None):
- return original_write(self, True if default is None else default)
+ return original_write(self, False if default is None else default)
monkeypatch.setattr(CoreOptions, "native_write_enabled", write_enabled)
- if force_commit:
+ if python_execution or python_commit:
original_commit = CoreOptions.native_commit_enabled
def commit_enabled(self, default=None):
- return original_commit(self, True if default is None else default)
+ return original_commit(self, False if default is None else default)
monkeypatch.setattr(CoreOptions, "native_commit_enabled",
commit_enabled)
_force_native_for_test = force_plan
diff --git a/paimon-python/dev/lint-python.sh b/paimon-python/dev/lint-python.sh
index ab8672651f..2753848902 100755
--- a/paimon-python/dev/lint-python.sh
+++ b/paimon-python/dev/lint-python.sh
@@ -247,9 +247,13 @@ function pytest_torch_check() {
}
# Mixed tests check - runs Java-Python interoperability tests
function mixed_check() {
- # Native plan/read coverage is asserted only by the main pytest session.
- unset PYPAIMON_TEST_NATIVE_PLAN
- unset PYPAIMON_TEST_NATIVE_READ
+ # Each mixed-test pytest session covers only one interoperability scenario.
+ # Keep its execution backend, but assert full Native coverage only in the
main suite.
+ export PYPAIMON_TEST_NATIVE_PLAN=0
+ export PYPAIMON_TEST_NATIVE_READ=0
+ export PYPAIMON_TEST_NATIVE_WRITE=0
+ export PYPAIMON_TEST_NATIVE_UPDATE=0
+ export PYPAIMON_TEST_NATIVE_COMMIT=0
# Get Python version
PYTHON_VERSION=$(python -c "import sys;
print(f'{sys.version_info.major}.{sys.version_info.minor}')")
diff --git a/paimon-python/dev/test_packaging.py
b/paimon-python/dev/test_packaging.py
index c453ee137c..fb24eb319c 100644
--- a/paimon-python/dev/test_packaging.py
+++ b/paimon-python/dev/test_packaging.py
@@ -326,28 +326,22 @@ class PackagingTest(unittest.TestCase):
self.assertEqual(supports_1_0_10, "1.0.10" in
active[0].specifier)
self.assertNotIn("2.0", active[0].specifier)
- def test_python_ci_dependencies_do_not_pull_native_sql(self):
- resolve = runpy.run_path(str(self.source /
"dev/install.py"))["resolve_group"]
- extras = self.config["project"]["optional-dependencies"]
-
- def dependencies(group):
- pending = list(resolve(self.config["dependency-groups"], group))
- names, expanded = set(), set()
- while pending:
- requirement = Requirement(pending.pop())
- names.add(canonicalize_name(requirement.name))
- if canonicalize_name(requirement.name) == "pypaimon":
- for extra in requirement.extras - expanded:
- pending.extend(extras[extra])
- expanded.add(extra)
- return names
-
- # Follow local extras too: the Rust extension previously entered the
- # ordinary Python and Torch environments indirectly through [sql].
- for group in ("torch", "python-tests", "legacy"):
- with self.subTest(group=group):
- self.assertNotIn("pypaimon-rust", dependencies(group))
- self.assertIn("pypaimon-rust", dependencies("dev"))
+ def test_native_runtime_installed_by_default_on_supported_python(self):
+ _, metadata, _ = wheel_contents(self.wheel)
+ native = [Requirement(value) for value in
metadata.get_all("Requires-Dist")
+ if canonicalize_name(Requirement(value).name) ==
"pypaimon-rust"]
+ for python_version in ("3.6", "3.7", "3.8", "3.9", "3.10", "3.11",
"3.13"):
+ with self.subTest(python=python_version):
+ environment = default_environment()
+ environment.update(python_version=python_version,
+ python_full_version=python_version + ".0",
extra="")
+ active = [requirement for requirement in native
+ if requirement.marker is None or
requirement.marker.evaluate(environment)]
+ supported = Version(python_version) >= Version("3.10")
+ self.assertEqual(1 if supported else 0, len(active))
+ if supported:
+ self.assertNotIn("0.4.0", active[0].specifier)
+ self.assertIn("0.5.0", active[0].specifier)
def test_dev_group_reuses_product_extras(self):
resolve = runpy.run_path(str(self.source /
"dev/install.py"))["resolve_group"]
diff --git a/paimon-python/pypaimon/common/options/core_options.py
b/paimon-python/pypaimon/common/options/core_options.py
index 1d2e8ce7c1..7b94e87347 100644
--- a/paimon-python/pypaimon/common/options/core_options.py
+++ b/paimon-python/pypaimon/common/options/core_options.py
@@ -723,7 +723,7 @@ class CoreOptions:
SCAN_NATIVE_PLAN_ENABLED: ConfigOption[bool] = (
ConfigOptions.key("scan.native-plan.enabled")
.boolean_type()
- .default_value(False)
+ .default_value(True)
.with_description("Plan splits via the native (pypaimon_rust) planner "
"instead of the Python manifest scanner; the
pypaimon "
"reader still reads the files.")
@@ -732,16 +732,16 @@ class CoreOptions:
READ_NATIVE_ENABLED: ConfigOption[bool] = (
ConfigOptions.key("read.native.enabled")
.boolean_type()
- .default_value(False)
+ .default_value(True)
.with_description("Read data via pypaimon_rust and return PyArrow
batches. "
- "This also enables native split planning;
unsupported "
+ "This also requests native split planning unless
explicitly disabled; unsupported "
"routes fall back to pypaimon.")
)
COMMIT_NATIVE_ENABLED: ConfigOption[bool] = (
ConfigOptions.key("commit.native.enabled")
.boolean_type()
- .default_value(False)
+ .default_value(True)
.with_description("Commit append and batch overwrite messages via
pypaimon_rust. Unsupported "
"operations use Python before any native commit is
attempted.")
)
@@ -749,7 +749,7 @@ class CoreOptions:
WRITE_NATIVE_ENABLED: ConfigOption[bool] = (
ConfigOptions.key("write.native.enabled")
.boolean_type()
- .default_value(False)
+ .default_value(True)
.with_description("Write Arrow data via pypaimon_rust when the table
and "
"writer API are supported. Unsupported routes use
Python "
"before any native data is written.")
diff --git a/paimon-python/pypaimon/execution/native/read/table_read.py
b/paimon-python/pypaimon/execution/native/read/table_read.py
index 5128bc7dcc..0db920065c 100644
--- a/paimon-python/pypaimon/execution/native/read/table_read.py
+++ b/paimon-python/pypaimon/execution/native/read/table_read.py
@@ -30,7 +30,7 @@ from pypaimon.execution.native import table as native_table
from pypaimon.execution.native.read import builder as native_builder
from pypaimon.read.read_type import OutputProjection, adapter_output_paths,
extract_array, output_schema
from pypaimon.read.split import Split
-from pypaimon.schema.data_types import DataField
+from pypaimon.schema.data_types import DataField, MapType
_NATIVE_READ_FILE_FORMATS = frozenset({
CoreOptions.FILE_FORMAT_PARQUET, CoreOptions.FILE_FORMAT_ORC,
@@ -115,8 +115,11 @@ class NativeTableRead:
return self._fallback(
"the table uses an unsupported BLOB view")
try:
+ if not self._orc_shared_shredding_supported(splits):
+ return self._fallback("ORC shared-shredding MAP columns
require the Python reader")
from pypaimon.execution.native.read.split_adapter import
native_split_from_python
except Exception as e:
+ runtime._raise_if_native_fork_safety_error(e)
return self._fallback(str(e), e, log=True)
rust_splits = []
for split in splits:
@@ -174,6 +177,25 @@ class NativeTableRead:
return False
return True
+ def _orc_shared_shredding_supported(self, splits):
+ # Rust 0.5.0 cannot restore Java's ORC shared-shredding MAP metadata.
+ # Check retained files and schemas: current write options may have
changed.
+ table = self._read.table
+ if not any(isinstance(field.type, MapType) for field in table.fields):
+ return True
+ schema_ids = {file.schema_id for split in splits for file in
split.files
+ if file.file_name.lower().endswith('.orc')}
+ if not schema_ids:
+ return True
+ if any(table.options.map_storage_layout(field.name) ==
'shared-shredding' for field in table.fields):
+ return False
+ for schema_id in schema_ids:
+ schema = table.schema_manager.get_schema(schema_id)
+ options = CoreOptions.from_dict(schema.options)
+ if any(options.map_storage_layout(field.name) ==
'shared-shredding' for field in schema.fields):
+ return False
+ return True
+
def convert_batches(self, batches, schema):
read = self._read
failure = None
diff --git a/paimon-python/pypaimon/execution/native/table.py
b/paimon-python/pypaimon/execution/native/table.py
index f218bb9b7b..21baf7e111 100644
--- a/paimon-python/pypaimon/execution/native/table.py
+++ b/paimon-python/pypaimon/execution/native/table.py
@@ -27,6 +27,17 @@ from pypaimon.common.options.config import CatalogOptions,
FuseOptions, OssOptio
from pypaimon.common.options.options_utils import OptionsUtils
+def _native_variant_write_supported(table, columns=None):
+ """Rust 0.5.0 omits Java-required field IDs inside shredded VARIANTs."""
+ if not table.options.variant_shredding_schema():
+ return True
+ from pypaimon.schema.data_types import AtomicType
+
+ names = set(table.field_names if columns is None else columns)
+ return not any(field.name in names and isinstance(field.type, AtomicType)
and field.type.type == 'VARIANT'
+ for field in table.fields)
+
+
def _native_blob_view_supported(table, read_names) -> bool:
"""Resolve Blob views natively only when Python itself can resolve them."""
if (not (table.options.blob_view_fields() & set(read_names))
diff --git a/paimon-python/pypaimon/execution/native/write/commit.py
b/paimon-python/pypaimon/execution/native/write/commit.py
index 71629f75fd..e140a8463d 100644
--- a/paimon-python/pypaimon/execution/native/write/commit.py
+++ b/paimon-python/pypaimon/execution/native/write/commit.py
@@ -76,7 +76,7 @@ def prepare_native_commit(owner, messages, *, batch=False):
create_native_commit, native_messages_supported,
to_native_commit_messages,
)
- if not native_messages_supported(owner.table, messages):
+ if not native_messages_supported(owner.table, messages, for_commit=True):
return None
if owner._native_commit is None or (batch and not
owner._native_commit._is_batch):
native = create_native_commit(
diff --git a/paimon-python/pypaimon/execution/native/write/native_commit.py
b/paimon-python/pypaimon/execution/native/write/native_commit.py
index 1ba1a67bc0..5f9c5256e3 100644
--- a/paimon-python/pypaimon/execution/native/write/native_commit.py
+++ b/paimon-python/pypaimon/execution/native/write/native_commit.py
@@ -30,12 +30,18 @@ from pypaimon.write.commit_message_serializer import (
)
-def native_messages_supported(table, messages) -> bool:
+def native_messages_supported(table, messages, *, for_commit=False) -> bool:
for message in messages:
if (message.compact_before or message.compact_after
or message.compact_changelog_files
or message.compact_index_adds or
message.compact_index_deletes):
return False
+ # Native 0.5.0 cannot validate retained field IDs against the schema of
+ # each publication attempt. Full-row updates also retain field IDs;
+ # write_cols=None does not exempt them. Pure conflict probes are safe.
+ if (for_commit and table.options.data_evolution_enabled()
+ and any(file.first_row_id is not None for file in
message.new_files)):
+ return False
partition = tuple(message.partition)
for file in message.new_files + message.changelog_files:
if file.external_path:
diff --git a/paimon-python/pypaimon/execution/native/write/native_merge_into.py
b/paimon-python/pypaimon/execution/native/write/native_merge_into.py
index 8aa072b54f..451cb0e9d6 100644
--- a/paimon-python/pypaimon/execution/native/write/native_merge_into.py
+++ b/paimon-python/pypaimon/execution/native/write/native_merge_into.py
@@ -20,6 +20,7 @@
import pyarrow as pa
from pypaimon.snapshot.snapshot import BATCH_COMMIT_IDENTIFIER
+from pypaimon.execution.native.table import _native_variant_write_supported
from pypaimon.execution.native.write.native_commit import
create_native_write_table, from_native_commit_messages
from pypaimon.execution.native.write.native_update import (
_dictionary_value_type, _native_row_id_table,
_native_update_columns_supported,
@@ -34,7 +35,7 @@ def create_native_merge_into(table, source, on, matched,
not_matched, commit_use
target_keys, source_keys = _normalize_on(on)
self_merge = _is_self_merge(table, source, target_keys, source_keys)
- if not_matched and table.options.video_frame_fields():
+ if not_matched and (table.options.video_frame_fields() or not
_native_variant_write_supported(table)):
return None
native_table = _native_row_id_table(table)
if native_table is None:
diff --git a/paimon-python/pypaimon/execution/native/write/native_update.py
b/paimon-python/pypaimon/execution/native/write/native_update.py
index 9c6819be11..d310f8c094 100644
--- a/paimon-python/pypaimon/execution/native/write/native_update.py
+++ b/paimon-python/pypaimon/execution/native/write/native_update.py
@@ -23,7 +23,7 @@ from datetime import date, datetime, time
import pyarrow as pa
import pyarrow.compute as pc
-from pypaimon.execution.native.table import _native_query_auth_supported
+from pypaimon.execution.native.table import _native_query_auth_supported,
_native_variant_write_supported
from pypaimon.execution.native.runtime import native_runtime_available
from pypaimon.schema.arrow_schema import arrow_schemas_compatible
from pypaimon.schema.data_types import MapType, PyarrowFieldParser, RowType,
VectorType, is_blob_file_field
@@ -257,7 +257,8 @@ def _native_update_columns_supported(table, columns):
if type(table) is not FileStoreTable:
return False
names = set(table.field_names if columns is None else columns)
- return not names.intersection(table.options.video_frame_fields())
+ return (not names.intersection(table.options.video_frame_fields())
+ and _native_variant_write_supported(table, names))
def _temporal_row_key_supported(value, data_type):
@@ -340,9 +341,10 @@ def _upsert_row_batches(rows, fields, schema, table=None,
blob_rows=None, key_na
def create_native_upsert(table, commit_user, data, keys, columns):
"""Prepare one core upsert from Arrow columns or named row values."""
- if table.options.video_frame_fields() or not
_native_update_columns_supported(table, columns):
- # An upsert can append unmatched rows; packed video writing is still
- # provided by the Python writer.
+ if (table.options.video_frame_fields() or not
_native_update_columns_supported(table, columns)
+ or not _native_variant_write_supported(table)):
+ # Unmatched inserts write the full schema, including packed video or
+ # shredded VARIANT columns outside the selected update columns.
return None
native_table = _native_row_id_table(table)
if native_table is None:
diff --git a/paimon-python/pypaimon/execution/native/write/native_write.py
b/paimon-python/pypaimon/execution/native/write/native_write.py
index 9f29670158..05329938b3 100644
--- a/paimon-python/pypaimon/execution/native/write/native_write.py
+++ b/paimon-python/pypaimon/execution/native/write/native_write.py
@@ -21,6 +21,7 @@ import pyarrow as pa
from pypaimon.common.options.core_options import ChangelogProducer
from pypaimon.snapshot.snapshot import BATCH_COMMIT_IDENTIFIER
from pypaimon.execution.native.runtime import native_runtime_available
+from pypaimon.execution.native.table import _native_variant_write_supported
from pypaimon.schema.arrow_schema import arrow_schemas_compatible
from pypaimon.schema.data_types import PyarrowFieldParser, is_blob_file_field
from pypaimon.table.bucket_mode import BucketMode
@@ -51,6 +52,12 @@ def create_native_write(table, commit_user,
static_partition=None, stream=False,
or table.options.file_format() != 'parquet'
or table.options.video_frame_fields()):
return None
+ # Rust 0.5.0 emits zero sequence bounds for ordinary bucketed append files.
+ # Java compaction needs advancing ranges to preserve their append order.
+ if not table.is_primary_key_table and table.bucket_mode() ==
BucketMode.HASH_FIXED:
+ return None
+ if not _native_variant_write_supported(table):
+ return None
native_table = create_native_write_table(table)
if native_table is None:
return None
diff --git a/paimon-python/pypaimon/read/read_dispatch.py
b/paimon-python/pypaimon/read/read_dispatch.py
index 6a78ae8fce..b5da4f36a0 100644
--- a/paimon-python/pypaimon/read/read_dispatch.py
+++ b/paimon-python/pypaimon/read/read_dispatch.py
@@ -249,6 +249,8 @@ def plan_scan(self, *, _file_scanner_base=False) -> Plan:
def configure_indexed_read(table):
"""Keep explicit preferences; otherwise prefer the available Native
reader."""
+ if not table.options.native_read_enabled():
+ return table
from pypaimon.common.options.core_options import CoreOptions
options = table.options.options
if not any(options.contains(option) for option in (
@@ -407,6 +409,9 @@ def create_streaming_scan(scan, poll_interval_ms=1000,
prefetch_enabled=True,
def native_plan_requested(scan) -> bool:
"""Resolve Native planning preference without loading a disabled
backend."""
+ from pypaimon.common.options.core_options import CoreOptions
+ if
scan.table.options.options.contains(CoreOptions.SCAN_NATIVE_PLAN_ENABLED):
+ return scan.table.options.native_plan_enabled()
if scan.table.options.native_plan_enabled():
return True
if not scan.table.options.native_read_enabled():
diff --git a/paimon-python/pypaimon/tests/binary_row_test.py
b/paimon-python/pypaimon/tests/binary_row_test.py
index d08171b16f..4dee550a87 100644
--- a/paimon-python/pypaimon/tests/binary_row_test.py
+++ b/paimon-python/pypaimon/tests/binary_row_test.py
@@ -51,10 +51,11 @@ class BinaryRowTest(unittest.TestCase):
('f2', pa.int64()),
])
cls.catalog.create_table('default.test_append',
Schema.from_pyarrow_schema(
- pa_schema, partition_keys=['f0'], options={'file.format':
_random_format()}), False)
+ pa_schema, partition_keys=['f0'], options={
+ 'file.format': _random_format(), 'write.native.enabled':
'false'}), False)
cls.catalog.create_table('default.test_pk', Schema.from_pyarrow_schema(
pa_schema, partition_keys=['f2'], primary_keys=['f0'],
- options={'bucket': '1', 'file.format': _random_format()}), False)
+ options={'bucket': '1', 'file.format': _random_format(),
'write.native.enabled': 'false'}), False)
cls.data = pa.Table.from_pydict({
'f0': [1, 2, 3, 4, 5],
'f1': ['abc', 'abbc', 'bc', 'd', None],
diff --git a/paimon-python/pypaimon/tests/commit_update_schema_identity_test.py
b/paimon-python/pypaimon/tests/commit_update_schema_identity_test.py
index 3fc9fd5bcc..e74eff9d4f 100644
--- a/paimon-python/pypaimon/tests/commit_update_schema_identity_test.py
+++ b/paimon-python/pypaimon/tests/commit_update_schema_identity_test.py
@@ -39,20 +39,29 @@ _ENGINES = [False, pytest.param(True,
marks=[pytest.mark.native_plan, pytest.mar
def _commit(table, messages, native=False):
commit = table.new_batch_write_builder().new_commit()
try:
- if native:
+ row_id_update = any(file.first_row_id is not None for message in
messages for file in message.new_files)
+ if native and not row_id_update:
with
patch('pypaimon.execution.python.write.file_store_commit.FileStoreCommit.commit',
side_effect=AssertionError('Python fallback')):
commit.commit(messages)
else:
- commit.commit(messages)
+ with
patch('pypaimon.execution.native.write.native_commit.create_native_commit',
+ side_effect=AssertionError('Row-ID publication requires
Python validation')):
+ commit.commit(messages)
+ if native:
+ assert commit._native_commit is None
+ assert commit._python_commit is not None
finally:
commit.close()
@pytest.mark.parametrize('native', _ENGINES)
[email protected]('evolution', ['rename', 'drop_readd', 'complete_row'])
[email protected]('evolution,stale_handle,keep_baseline', [
+ ('rename', False, True), ('drop_readd', False, True),
+ ('drop_readd', True, True), ('drop_readd', False, False), ('complete_row',
False, True)])
@pytest.mark.parametrize('action', ['THROW_ERROR', 'DROP_PARTITION_INDEX',
'IGNORE'])
-def
test_commit_resolves_updated_index_columns_by_file_schema(native_rest_catalog,
native, evolution, action):
+def test_commit_resolves_updated_index_columns_by_file_schema(
+ native_rest_catalog, native, evolution, stale_handle, keep_baseline,
action):
catalog = native_rest_catalog
schema = pa.schema([('id', pa.int32()), ('value', pa.int32())])
catalog.create_table('default.identity',
Schema.from_pyarrow_schema(schema, options={
@@ -95,7 +104,10 @@ def
test_commit_resolves_updated_index_columns_by_file_schema(native_rest_catalo
messages[0].new_files[0].write_cols = None
else:
assert messages[0].new_files[0].schema_id == original.table_schema.id
- target = latest.copy({'commit.native.enabled': str(native).lower()})
+ if not keep_baseline:
+ for message in messages:
+ message.check_from_snapshot = None
+ target = (original if stale_handle else
latest).copy({'commit.native.enabled': str(native).lower()})
# Reject updates to removed field IDs even when a new field has the same
name.
dropped_update = evolution == 'drop_readd'
if dropped_update or action == 'THROW_ERROR':
@@ -119,6 +131,12 @@ def
test_commit_resolves_updated_index_columns_by_file_schema(native_rest_catalo
assert rows == {'id': [1], index_field.name: [expected_value]}
if dropped_update:
assert all(latest.file_io.exists(file.file_path) for message in
messages for file in message.new_files)
+ commit = target.new_batch_write_builder().new_commit()
+ try:
+ commit.abort(messages)
+ finally:
+ commit.close()
+ assert all(not latest.file_io.exists(file.file_path) for message in
messages for file in message.new_files)
@pytest.mark.parametrize('native', _ENGINES)
diff --git a/paimon-python/pypaimon/tests/default_execution_test.py
b/paimon-python/pypaimon/tests/default_execution_test.py
new file mode 100644
index 0000000000..a9e809b7ed
--- /dev/null
+++ b/paimon-python/pypaimon/tests/default_execution_test.py
@@ -0,0 +1,81 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Default execution, explicit Python selection and missing-runtime
fallback."""
+
+import sys
+
+import pyarrow as pa
+import pytest
+
+from pypaimon import Schema
+from pypaimon.execution.native.runtime import native_runtime_available
+from pypaimon.write.write_dispatch import NativeTableWrite
+
+
+pytestmark = pytest.mark.execution_defaults
+
+
[email protected]('mode', ['append', 'primary-key', 'data-evolution'])
[email protected]('backend', [
+ pytest.param('native', marks=pytest.mark.skipif(
+ not native_runtime_available(), reason='pypaimon-rust not installed')),
+ 'python', 'missing-runtime',
+])
+def test_default_execution_roundtrip(native_rest_catalog, monkeypatch, mode,
backend):
+ options = {'bucket': '1' if mode == 'primary-key' else '-1'}
+ if mode == 'data-evolution':
+ options.update({'data-evolution.enabled': 'true',
'row-tracking.enabled': 'true'})
+ if backend == 'python':
+ options.update({key: 'false' for key in (
+ 'scan.native-plan.enabled', 'read.native.enabled',
+ 'write.native.enabled', 'commit.native.enabled')})
+ elif backend == 'missing-runtime':
+ monkeypatch.setitem(sys.modules, 'pypaimon_rust', None)
+ monkeypatch.setitem(sys.modules, 'pypaimon_rust.datafusion', None)
+
+ catalog = native_rest_catalog
+ schema = pa.schema([('id', pa.int64()), ('value', pa.string())])
+ catalog.create_table('default.t', Schema.from_pyarrow_schema(
+ schema, primary_keys=['id'] if mode == 'primary-key' else [],
options=options), False)
+ table = catalog.get_table('default.t')
+ data = pa.Table.from_pylist([{'id': 1, 'value': 'a'}, {'id': 2, 'value':
'b'}], schema=schema)
+ builder = table.new_batch_write_builder()
+ writer, commit = builder.new_write(), builder.new_commit()
+ native = backend == 'native'
+ try:
+ assert isinstance(writer, NativeTableWrite) == native
+ writer.write_arrow(data)
+ commit.commit(writer.prepare_commit())
+ assert (commit._native_commit is not None) == native
+ assert (commit._python_commit is None) == native
+ finally:
+ writer.close()
+ commit.close()
+
+ read_builder = table.new_read_builder()
+ scan = read_builder.new_scan()
+ splits = scan.plan().splits()
+ assert scan._execution._is_native == native
+ if native:
+ def reject_python_read(*args, **kwargs):
+ raise AssertionError('Default Native read fell back to Python')
+
+
monkeypatch.setattr('pypaimon.execution.python.read.table_read.PythonTableRead._materialize',
+ reject_python_read)
+ actual = read_builder.new_read().to_arrow(splits).to_pylist()
+ assert sorted(actual, key=lambda row: row['id']) == data.to_pylist()
diff --git a/paimon-python/pypaimon/tests/e2e/java_py_read_write_test.py
b/paimon-python/pypaimon/tests/e2e/java_py_read_write_test.py
index e042132fb1..363171f58a 100644
--- a/paimon-python/pypaimon/tests/e2e/java_py_read_write_test.py
+++ b/paimon-python/pypaimon/tests/e2e/java_py_read_write_test.py
@@ -355,7 +355,8 @@ class JavaPyReadWriteTest(unittest.TestCase):
table_read = read_builder.new_read()
result = table_read.to_pandas(table_scan.plan().splits())
print(f"Format: {file_format}, Result:\n{result}")
- self.assertEqual(initial_data.to_dict(), result.to_dict())
+ # Primary-key scans across partitions and buckets have no global row
order.
+ self.assertEqual(initial_data.to_dict(),
result.sort_values('id').reset_index(drop=True).to_dict())
from pypaimon.execution.python.write.row_key_extractor import
FixedBucketRowKeyExtractor
expected_bucket_first_row = 2
diff --git a/paimon-python/pypaimon/tests/execution_preference_test.py
b/paimon-python/pypaimon/tests/execution_preference_test.py
new file mode 100644
index 0000000000..dcbc2ec009
--- /dev/null
+++ b/paimon-python/pypaimon/tests/execution_preference_test.py
@@ -0,0 +1,62 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Explicit backend preferences survive the Native product defaults."""
+
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import pytest
+
+from pypaimon.common.options.core_options import CoreOptions
+from pypaimon.common.options.options import Options
+from pypaimon.read.plan import Plan
+from pypaimon.read.read_dispatch import configure_indexed_read,
native_plan_requested
+from pypaimon.write.backend_dispatch import create_row_id_plan_execution
+
+
[email protected]_defaults
[email protected]('enabled', ['false', 'true'])
+def test_explicit_planner_preference_wins_over_native_reader_default(enabled):
+ table =
SimpleNamespace(options=CoreOptions(Options({'scan.native-plan.enabled':
enabled})))
+ assert table.options.native_read_enabled()
+ assert native_plan_requested(SimpleNamespace(table=table)) == (enabled ==
'true')
+
+
[email protected]_read
+def test_indexed_read_preserves_python_lane_without_changing_table_options():
+ options = CoreOptions(Options({}))
+ assert not options.native_read_enabled()
+ table = SimpleNamespace(options=options, copy_without_time_travel=Mock(
+ side_effect=AssertionError('Indexed read overrode the selected Python
reader')))
+ with patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=True):
+ assert configure_indexed_read(table) is table
+ assert options.options.to_map() == {}
+
+
[email protected]_defaults
+def test_python_write_preference_keeps_row_id_routing_in_python():
+ from pypaimon.execution.python.write.row_id_plan import PythonRowIdPlan
+
+ table =
SimpleNamespace(options=CoreOptions(Options({'write.native.enabled': 'false'})))
+ assert table.options.native_read_enabled()
+ assert table.options.native_plan_enabled()
+ with
patch('pypaimon.execution.native.write.row_id_plan.create_native_row_id_plan',
+ side_effect=AssertionError('Python write preference selected
Native row-ID routing')):
+ execution = create_row_id_plan_execution(table, Plan([], 7))
+ assert isinstance(execution, PythonRowIdPlan)
+ assert not execution.groups
diff --git a/paimon-python/pypaimon/tests/lazy_read_execution_test.py
b/paimon-python/pypaimon/tests/lazy_read_execution_test.py
index efd4329f81..c242583f57 100644
--- a/paimon-python/pypaimon/tests/lazy_read_execution_test.py
+++ b/paimon-python/pypaimon/tests/lazy_read_execution_test.py
@@ -148,10 +148,10 @@ def
test_native_read_never_initializes_or_replays_python_read(table, end):
assert events == ['closed']
[email protected]('native_plan,native_read', [(True, False), (False,
True), (True, True)])
[email protected]('native_plan,native_read', [(True, False), (None,
True), (True, True)])
def test_native_stream_scan_does_not_construct_python_executors(table,
native_plan, native_read):
table = table.copy({
- 'scan.native-plan.enabled': str(native_plan).lower(),
+ 'scan.native-plan.enabled': None if native_plan is None else
str(native_plan).lower(),
'read.native.enabled': str(native_read).lower(),
})
with ExitStack() as stack:
@@ -172,11 +172,12 @@ def
test_native_stream_scan_does_not_construct_python_executors(table, native_pl
core.plan.assert_called_once()
[email protected]_plan
@pytest.mark.parametrize('runtime_available', [False, True])
def test_native_read_stream_falls_back_before_planning(table,
runtime_available):
from pypaimon.execution.python.read.streaming_table_scan import
AsyncStreamingTableScan
- table = table.copy({'scan.native-plan.enabled': 'false',
'read.native.enabled': 'true'})
+ table = table.copy({'scan.native-plan.enabled': None,
'read.native.enabled': 'true'})
with patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=runtime_available), \
patch('pypaimon.execution.native.read.streaming_table_scan.native_stream_scan',
side_effect=RuntimeError('prepare')) as native:
diff --git a/paimon-python/pypaimon/tests/lerobot_native_reader_test.py
b/paimon-python/pypaimon/tests/lerobot_native_reader_test.py
index 7b7612bc75..40e3f7e2aa 100644
--- a/paimon-python/pypaimon/tests/lerobot_native_reader_test.py
+++ b/paimon-python/pypaimon/tests/lerobot_native_reader_test.py
@@ -60,6 +60,7 @@ def reader(table, **options):
@pytest.mark.skipif(not native_runtime_available(), reason="native reader
required")
[email protected]_defaults
@pytest.mark.parametrize("option", [None, "read.native.enabled",
"scan.native-plan.enabled"])
def test_native_frame_lookup_keeps_residual_and_snapshot(frames, option):
# The index covers the original rows, not this append.
@@ -184,17 +185,16 @@ def test_explicit_python_lookup_is_preserved(frames,
options):
@pytest.mark.python_plan
@pytest.mark.python_read
@pytest.mark.parametrize("available", [False, True])
-def test_auto_native_uses_private_table_copy(frames, available):
+def test_indexed_reader_preserves_python_default_and_table_options(frames,
available):
original = dict(frames.raw_table.options.options.to_map())
with patch("pypaimon.execution.native.runtime.native_runtime_available",
return_value=available):
current = reader(frames)
try:
- assert current._table.options.native_read_enabled() == available
+ assert not current._table.options.native_read_enabled()
assert frames.raw_table.options.options.to_map() == original
- if not available:
- with patch.object(current._locator, "locate",
wraps=current._locator.locate) as locate:
- assert current.read_indices([30],
["value"])["value"].to_pylist() == [3]
- locate.assert_called_once_with([30])
+ with patch.object(current._locator, "locate",
wraps=current._locator.locate) as locate:
+ assert current.read_indices([30], ["value"])["value"].to_pylist()
== [3]
+ locate.assert_called_once_with([30])
finally:
current.close()
@@ -204,7 +204,8 @@ def
test_unsupported_native_plan_reuses_python_index_scanner(frames):
DataEvolutionGlobalIndexScanner)
frames.add(pa.table({"index": [40], "value": [4]}))
with patch("pypaimon.execution.native.runtime.native_runtime_available",
return_value=True):
- current = reader(frames)
+ current = reader(frames, **{
+ "scan.native-plan.enabled": "true", "read.native.enabled": "true"})
try:
assert current._table.options.native_read_enabled()
with
patch("pypaimon.execution.native.runtime.native_runtime_available",
return_value=True), \
@@ -230,7 +231,8 @@ def
test_unsupported_native_plan_reuses_python_index_scanner(frames):
@pytest.mark.parametrize("denied", [False, True])
def test_native_lookup_preserves_query_authorization(frames, denied):
from pypaimon.read.table_scan import TableScan
- current = reader(frames)
+ current = reader(frames, **{
+ "scan.native-plan.enabled": "true", "read.native.enabled": "true"})
calls = []
def authorize(*args, **kwargs):
diff --git a/paimon-python/pypaimon/tests/multimodal_lerobot_ray_test.py
b/paimon-python/pypaimon/tests/multimodal_lerobot_ray_test.py
index 902de82280..17917ae957 100644
--- a/paimon-python/pypaimon/tests/multimodal_lerobot_ray_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_lerobot_ray_test.py
@@ -387,20 +387,19 @@ class LeRobotRayImportTest(unittest.TestCase):
def prepare(*args):
from pypaimon.multimodal.lerobot.ray_loader import
_prepare_merged_source
from pypaimon.write.table_write import BatchTableWrite
-
- original_close = BatchTableWrite.close
-
- def fail_close(write):
- original_close(write)
- trace.write_text(json.dumps(
- [path.name for path in _bucket_files(args[0])]))
- raise error_type("injected writer close")
-
- BatchTableWrite.close = fail_close
- try:
+ from pypaimon.write.write_dispatch import
NativeBatchTableWrite
+
+ def failing_close(original):
+ def fail_close(write):
+ original(write)
+ trace.write_text(json.dumps(
+ [path.name for path in
_bucket_files(args[0])]))
+ raise error_type("injected writer close")
+ return fail_close
+
+ with patch.object(BatchTableWrite, 'close',
failing_close(BatchTableWrite.close)), \
+ patch.object(NativeBatchTableWrite, 'close',
failing_close(NativeBatchTableWrite.close)):
return _prepare_merged_source(*args)
- finally:
- BatchTableWrite.close = original_close
with
patch("pypaimon.multimodal.lerobot.ray_loader._prepare_merged_source",
prepare):
diff --git a/paimon-python/pypaimon/tests/native_branch_write_test.py
b/paimon-python/pypaimon/tests/native_branch_write_test.py
index dd6b14135d..f0af4e1ce5 100644
--- a/paimon-python/pypaimon/tests/native_branch_write_test.py
+++ b/paimon-python/pypaimon/tests/native_branch_write_test.py
@@ -58,19 +58,26 @@ def _prepare(builder, rows, checkpoint=None):
def _commit(builder, messages, checkpoint=None, overwrite=False):
commit = builder.new_commit()
+ retained_row_ids = builder.table.options.data_evolution_enabled() and any(
+ file.first_row_id is not None for message in messages for file in
message.new_files)
+ native_publication =
builder.table.catalog_environment.supports_version_management and not
retained_row_ids
try:
def publish():
if checkpoint is None:
commit.commit(messages)
else:
commit.commit(messages, checkpoint)
- if builder.table.catalog_environment.supports_version_management:
+ if native_publication:
with patch('pypaimon.execution.python.write.file_store_commit.'
'FileStoreCommit.' + ('overwrite' if overwrite else
'commit'),
side_effect=AssertionError('Python commit fallback')):
publish()
else:
- publish()
+ with
patch('pypaimon.execution.native.write.commit.NativeTableCommit.commit',
+ side_effect=AssertionError('Unexpected Native
publication')):
+ publish()
+ assert (commit._native_commit is not None) == native_publication
+ assert (commit._python_commit is None) == native_publication
finally:
commit.close()
diff --git a/paimon-python/pypaimon/tests/native_commit_test.py
b/paimon-python/pypaimon/tests/native_commit_test.py
index 51fb8030ac..8bbff2ead0 100644
--- a/paimon-python/pypaimon/tests/native_commit_test.py
+++ b/paimon-python/pypaimon/tests/native_commit_test.py
@@ -101,10 +101,10 @@ def _seed(table):
commit.close()
[email protected]_commit
-def test_native_commit_is_opt_in():
- assert not CoreOptions(Options({})).native_commit_enabled()
- assert CoreOptions(Options({'commit.native.enabled':
'true'})).native_commit_enabled()
[email protected]_defaults
+def test_native_commit_is_default_and_can_be_disabled():
+ assert CoreOptions(Options({})).native_commit_enabled()
+ assert not CoreOptions(Options({'commit.native.enabled':
'false'})).native_commit_enabled()
@pytest.mark.parametrize('backend', ['filesystem', 'path', 'jdbc'])
@@ -590,15 +590,20 @@ def
test_missing_runtime_falls_back_without_reconstructing_table(
resolve.assert_not_called()
-def test_preassigned_row_id_messages_use_native_validation(
- tmp_path, native_rest_catalog):
[email protected]('write_cols', [None, ['id']])
+def
test_preassigned_row_id_messages_keep_native_probes_but_use_python_publication(
+ tmp_path, native_rest_catalog, write_cols):
table = _table(tmp_path, 'de', catalog=native_rest_catalog)
assert native_messages_supported(table, [CommitMessage((), 0, [])])
assert native_messages_supported(table, [CommitMessage((), 0, [],
check_from_snapshot=7)])
messages = _prepare(table.new_batch_write_builder(), [{'id': 1, 'pt':
'a'}])
messages[0].new_files[0].first_row_id = 1
+ messages[0].new_files[0].write_cols = write_cols
messages[0].check_from_snapshot = 7
assert native_messages_supported(table, messages)
+ assert not native_messages_supported(table, messages, for_commit=True)
+ messages[0].check_from_snapshot = None
+ assert not native_messages_supported(table, messages, for_commit=True)
assert not native_messages_supported(table, [CommitMessage((), 0, [],
compact_after=[Mock()])])
diff --git a/paimon-python/pypaimon/tests/native_data_evolution_commit_test.py
b/paimon-python/pypaimon/tests/native_data_evolution_commit_test.py
index 8881681401..1c6d576ac5 100644
--- a/paimon-python/pypaimon/tests/native_data_evolution_commit_test.py
+++ b/paimon-python/pypaimon/tests/native_data_evolution_commit_test.py
@@ -60,13 +60,24 @@ def _prepare(builder, ids, partition='a', identifier=None):
def _commit(builder, messages, identifier=None, overwrite=False):
commit = builder.new_commit()
try:
- with patch('pypaimon.execution.python.write.file_store_commit.'
- 'FileStoreCommit.' + ('overwrite' if overwrite else
'commit'),
- side_effect=AssertionError('Python commit fallback')):
+ row_id_update = any(file.first_row_id is not None for message in
messages for file in message.new_files)
+ with ExitStack() as stack:
+ if row_id_update:
+ stack.enter_context(patch(
+
'pypaimon.execution.native.write.native_commit.create_native_commit',
+ side_effect=AssertionError('Row-ID publication requires
Python validation')))
+ else:
+ stack.enter_context(patch(
+ 'pypaimon.execution.python.write.file_store_commit.'
+ 'FileStoreCommit.' + ('overwrite' if overwrite else
'commit'),
+ side_effect=AssertionError('Python commit fallback')))
if identifier is None:
commit.commit(messages)
else:
commit.commit(messages, identifier)
+ if row_id_update:
+ assert commit._native_commit is None
+ assert commit._python_commit is not None
finally:
commit.close()
@@ -147,7 +158,7 @@ def
test_partial_column_update_keeps_row_ids_and_checks_conflicts(native_rest_ca
_commit(builder, first, 7 if stream else None)
# Give each logical transaction a separate commit identity.
other = table.new_stream_write_builder() if stream else
table.new_batch_write_builder()
- with pytest.raises(Exception, match='multiple MERGE INTO.*conflicts'):
+ with pytest.raises(Exception, match='multiple.*MERGE INTO.*conflicts'):
_commit(other, conflicting, 8 if stream else None)
assert table.snapshot_manager().get_latest_snapshot().id == 2
other = table.new_stream_write_builder() if stream else
table.new_batch_write_builder()
@@ -202,7 +213,7 @@ def
test_deletion_vector_commit_preserves_row_id_high_watermark(native_rest_cata
@pytest.mark.parametrize('rewrite_size', [None, '0 B', '256 MB'])
-def
test_preassigned_row_id_updates_use_native_java_validation(native_rest_catalog,
rewrite_size):
+def
test_preassigned_row_id_updates_retain_python_publication_validation(native_rest_catalog,
rewrite_size):
options = {} if rewrite_size is None else {
'data-evolution.row-id-conflict-rewrite.max-size': rewrite_size}
table = _table(native_rest_catalog, options)
@@ -347,7 +358,8 @@ def
test_native_blob_update_rejects_stale_range_before_publication(native_rest_c
stale = [CommitMessage(source.partition, source.bucket, [blob],
check_from_snapshot=1)]
assert native_messages_supported(table, stale)
before = table.snapshot_manager().get_latest_snapshot()
- with pytest.raises(Exception, match='Row ID existence conflict|not covered
by one data file range'):
+ with pytest.raises(Exception, match=(
+ 'Row ID existence conflict|not covered by one data file
range|spans multiple data file ranges')):
_commit(table.new_batch_write_builder(), stale)
assert table.snapshot_manager().get_latest_snapshot().id == before.id
assert table.snapshot_manager().get_latest_snapshot().next_row_id == 10
diff --git a/paimon-python/pypaimon/tests/native_file_scan_test.py
b/paimon-python/pypaimon/tests/native_file_scan_test.py
index 271edd5c37..37800af954 100644
--- a/paimon-python/pypaimon/tests/native_file_scan_test.py
+++ b/paimon-python/pypaimon/tests/native_file_scan_test.py
@@ -63,10 +63,10 @@ def _append(table, rows):
commit.close()
[email protected]('native_plan,native_read', [(True, False), (False,
True), (True, True)])
[email protected]('native_plan,native_read', [(True, False), (None,
True), (True, True)])
@pytest.mark.parametrize('method', ['scan', 'scan_with_stats', 'plan_files'])
def test_public_file_scanner_does_not_initialize_python(table, method,
native_plan, native_read):
- table = table.copy({'scan.native-plan.enabled': str(native_plan).lower(),
+ table = table.copy({'scan.native-plan.enabled': None if native_plan is
None else str(native_plan).lower(),
'read.native.enabled': str(native_read).lower()})
with ExitStack() as stack:
for target in ('FileScanner', 'ManifestListManager'):
@@ -90,6 +90,23 @@ def
test_public_file_scanner_does_not_initialize_python(table, method, native_pl
files.assert_not_called()
[email protected]('method', ['scan', 'scan_with_stats', 'plan_files'])
+def
test_file_scanner_respects_explicit_python_planning_with_native_reads(table,
method):
+ table = table.copy({'scan.native-plan.enabled': 'false',
'read.native.enabled': 'true'})
+ with patch('pypaimon.execution.native.runtime.native_runtime_available',
+ side_effect=AssertionError('Disabled planner probed Native
runtime')), \
+ patch.object(NativeTableScan, 'plan_files',
+ side_effect=AssertionError('Disabled planner used
Native files')), \
+ patch('pypaimon.execution.native.read.plan.native_plan',
+ side_effect=AssertionError('Disabled planner used Native
planning')):
+ result = getattr(table.new_read_builder().new_scan().file_scanner,
method)()
+ if method == 'plan_files':
+ assert result == []
+ else:
+ plan = result[0] if method == 'scan_with_stats' else result
+ assert plan.splits() == []
+
+
@pytest.mark.parametrize('skip_level0,only_real', [(False, False), (False,
True), (True, False), (True, True)])
def test_native_raw_file_planning_ignores_query_result_transforms(table,
skip_level0, only_real):
scan =
table.new_read_builder().with_projection(['id']).with_limit(1).new_scan()
diff --git a/paimon-python/pypaimon/tests/native_interop_compatibility_test.py
b/paimon-python/pypaimon/tests/native_interop_compatibility_test.py
new file mode 100644
index 0000000000..6590417706
--- /dev/null
+++ b/paimon-python/pypaimon/tests/native_interop_compatibility_test.py
@@ -0,0 +1,217 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Native defaults preserve the physical contracts shared with Java."""
+
+import json
+from unittest.mock import patch
+from types import SimpleNamespace
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+import pytest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.data.map_shared_shredding import is_shared_shredding
+from pypaimon.data.generic_variant import GenericVariant
+from pypaimon.execution.native.read.table_read import NativeTableRead,
native_read
+from pypaimon.execution.native.runtime import native_runtime_available
+
+
+pytestmark = [pytest.mark.execution_defaults, pytest.mark.skipif(
+ not native_runtime_available(), reason='pypaimon-rust is required')]
+_SCHEMA = pa.schema([('id', pa.int32()), ('metrics', pa.map_(pa.string(),
pa.int64()))])
+_ROWS = [{'id': 1, 'metrics': [('hot', 10), ('warm', 20), ('overflow', 30)]},
+ {'id': 2, 'metrics': [('hot', None), ('new', 40)]},
+ {'id': 3, 'metrics': []}, {'id': 4, 'metrics': None}]
+
+
+def _table(tmp_path, layout, **options):
+ catalog = CatalogFactory.create({'warehouse': str(tmp_path)})
+ catalog.create_database('default', True)
+ options.update({'fields.metrics.map.storage-layout': layout,
+ 'fields.metrics.map.shared-shredding.max-columns': '2'})
+ catalog.create_table('default.t', Schema.from_pyarrow_schema(_SCHEMA,
options=options), False)
+ return catalog.get_table('default.t')
+
+
+def _write(table):
+ builder = table.new_batch_write_builder()
+ writer, commit = builder.new_write(), builder.new_commit()
+ try:
+ writer.write_arrow(pa.Table.from_pylist(_ROWS, schema=_SCHEMA))
+ messages = writer.prepare_commit()
+ commit.commit(messages)
+ return messages
+ finally:
+ writer.close()
+ commit.close()
+
+
[email protected]('layout', ['default', 'shared-shredding'])
[email protected]('selected', [False, True])
+def test_native_defaults_read_python_physical_map_files(tmp_path, layout,
selected):
+ table = _table(tmp_path, layout, **{'write.native.enabled': 'false'})
+ messages = _write(table)
+ physical =
pq.read_schema(messages[0].new_files[0].file_path).field('metrics')
+ assert is_shared_shredding(physical) == (layout == 'shared-shredding')
+ builder = table.new_read_builder()
+ if selected:
+ builder.with_projection(['id', "metrics['hot']",
"metrics['overflow']"])
+ with patch('pypaimon.execution.native.read.table_read.native_read',
wraps=native_read) as native:
+ result =
builder.new_read().to_arrow(builder.new_scan().plan().splits(),
parallelism=1).sort_by('id')
+ native.assert_called_once()
+ if selected:
+ assert result.to_pydict() == {
+ 'id': [1, 2, 3, 4], 'metrics_hot': [10, None, None, None],
+ 'metrics_overflow': [30, None, None, None]}
+ else:
+ assert result.to_pylist() == _ROWS
+
+
[email protected]('layout', ['default', 'shared-shredding'])
+def test_native_default_writer_preserves_configured_map_layout(tmp_path,
layout):
+ table = _table(tmp_path, layout)
+ messages = _write(table)
+ physical =
pq.read_schema(messages[0].new_files[0].file_path).field('metrics')
+ assert is_shared_shredding(physical) == (layout == 'shared-shredding')
+
+
+def test_native_default_update_preserves_shared_shredding_map_layout(tmp_path):
+ table = _table(tmp_path, 'shared-shredding', **{
+ 'data-evolution.enabled': 'true', 'row-tracking.enabled': 'true'})
+ _write(table.copy({'write.native.enabled': 'false'}))
+ builder = table.new_batch_write_builder()
+ messages =
builder.new_update().with_update_type(['metrics']).update_by_arrow_with_row_id(
+ pa.table({'_ROW_ID': pa.array([0], type=pa.int64()),
+ 'metrics': pa.array([[('hot', 99)]],
type=_SCHEMA.field('metrics').type)}))
+ physical =
pq.read_schema(messages[0].new_files[0].file_path).field('metrics')
+ assert is_shared_shredding(physical)
+ commit = builder.new_commit()
+ try:
+ commit.commit(messages)
+ finally:
+ commit.close()
+ reader = table.new_read_builder()
+ actual =
reader.new_read().to_arrow(reader.new_scan().plan().splits()).sort_by('id').to_pylist()
+ assert actual == [dict(_ROWS[0], metrics=[('hot', 99)])] + _ROWS[1:]
+
+
[email protected]('layout', ['default', 'shared-shredding'])
[email protected]('overrides', [
+ {}, {'file.format': 'parquet'}, {'fields.metrics.map.storage-layout':
'default'}])
+def test_orc_shared_shredding_is_qualified_before_native_read(tmp_path,
layout, overrides):
+ table = _table(tmp_path, layout, **{'file.format': 'orc'}).copy(overrides)
+ split = SimpleNamespace(files=[SimpleNamespace(file_name='data.orc',
schema_id=0)], _native_split=object())
+ with patch('pypaimon.execution.native.read.table_read.native_read',
return_value=[]) as native:
+ result =
NativeTableRead(table.new_read_builder().new_read()).read_batches([split],
_SCHEMA)
+ if layout == 'shared-shredding':
+ assert result is None
+ native.assert_not_called()
+ else:
+ assert list(result) == []
+ native.assert_called_once()
+
+
[email protected]('stream', [False, True])
+def
test_native_default_bucketed_append_restores_advancing_sequence_ranges(native_rest_catalog,
stream):
+ catalog = native_rest_catalog
+ schema = pa.schema([('id', pa.int32()), ('seq', pa.int32())])
+ catalog.create_table('default.t', Schema.from_pyarrow_schema(
+ schema, options={'bucket': '1', 'bucket-key': 'id'}), False)
+ table = catalog.get_table('default.t')
+ ranges = []
+ for seq in range(6):
+ builder = table.new_stream_write_builder() if stream else
table.new_batch_write_builder()
+ writer, commit = builder.new_write(), builder.new_commit()
+ try:
+ writer.write_arrow(pa.Table.from_pydict({'id': [1], 'seq': [seq]},
schema=schema))
+ messages = writer.prepare_commit(seq) if stream else
writer.prepare_commit()
+ ranges.extend((f.min_sequence_number, f.max_sequence_number)
+ for message in messages for f in message.new_files)
+ commit.commit(messages, seq) if stream else commit.commit(messages)
+ assert commit._native_commit is not None
+ finally:
+ writer.close()
+ commit.close()
+ # Java compaction sorts ordinary append files by these ranges.
+ assert ranges == [(seq, seq) for seq in range(2, 8)]
+
+
[email protected]('kind', ['ordinary', 'fork', 'cause', 'context'])
+def
test_orc_schema_probe_selects_fallback_but_propagates_fork_errors(tmp_path,
kind):
+ from pypaimon_rust import ForkSafetyError
+
+ table = _table(tmp_path, 'default', **{'file.format': 'orc'})
+ split = SimpleNamespace(files=[SimpleNamespace(file_name='data.orc',
schema_id=0)], _native_split=object())
+ error = OSError('schema probe failed')
+ if kind != 'ordinary':
+ fork = ForkSafetyError('Native runtime cannot be reused after fork')
+ if kind == 'fork':
+ error = fork
+ elif kind == 'cause':
+ error.__cause__ = fork
+ else:
+ error.__context__ = fork
+ with patch.object(table.schema_manager, 'get_schema', side_effect=error), \
+ patch('pypaimon.execution.native.read.table_read.native_read') as
native:
+ read = NativeTableRead(table.new_read_builder().new_read())
+ if kind == 'ordinary':
+ assert read.read_batches([split], _SCHEMA) is None
+ else:
+ with pytest.raises(ForkSafetyError):
+ read.read_batches([split], _SCHEMA)
+ native.assert_not_called()
+
+
[email protected]('option', ['variant.shreddingSchema',
'parquet.variant.shreddingSchema'])
+def test_native_default_shredded_variant_retains_java_field_ids(tmp_path,
option):
+ catalog = CatalogFactory.create({'warehouse': str(tmp_path)})
+ catalog.create_database('default', True)
+ values = [GenericVariant.from_python({'age': 30, 'city': 'Beijing'}),
+ GenericVariant.from_python([1, 2, 3]), None]
+ payload = GenericVariant.to_arrow_array(values)
+ schema = pa.schema([('id', pa.int32()), ('payload', payload.type)])
+ shredding = json.dumps({'type': 'ROW', 'fields': [
+ {'name': 'payload', 'type': {'type': 'ROW', 'fields': [
+ {'name': 'age', 'type': 'BIGINT'}, {'name': 'city', 'type':
'STRING'}]}}]})
+ catalog.create_table('default.t', Schema.from_pyarrow_schema(schema,
options={
+ option: shredding, 'variant.shredding.enabled': 'false'}), False)
+ table = catalog.get_table('default.t')
+ builder = table.new_batch_write_builder()
+ writer, commit = builder.new_write(), builder.new_commit()
+ try:
+ writer.write_arrow(pa.Table.from_arrays([pa.array([1, 2, 3],
type=pa.int32()), payload], schema=schema))
+ messages = writer.prepare_commit()
+ commit.commit(messages)
+ finally:
+ writer.close()
+ commit.close()
+
+ def check_ids(fields):
+ for field in fields:
+ assert field.metadata and b'PARQUET:field_id' in field.metadata
+ if pa.types.is_struct(field.type):
+ check_ids(field.type)
+
+ physical =
pq.read_schema(messages[0].new_files[0].file_path).field('payload')
+ assert 'typed_value' in physical.type.names
+ check_ids(physical.type)
+ reader = table.new_read_builder()
+ actual =
reader.new_read().to_arrow(reader.new_scan().plan().splits()).sort_by('id')['payload'].to_pylist()
+ assert [None if value is None else
GenericVariant.from_arrow_struct(value).to_python()
+ for value in actual] == [{'age': 30, 'city': 'Beijing'}, [1, 2,
3], None]
diff --git a/paimon-python/pypaimon/tests/native_loaded_schema_io_test.py
b/paimon-python/pypaimon/tests/native_loaded_schema_io_test.py
index 5fa6825925..62a953928b 100644
--- a/paimon-python/pypaimon/tests/native_loaded_schema_io_test.py
+++ b/paimon-python/pypaimon/tests/native_loaded_schema_io_test.py
@@ -52,13 +52,15 @@ def _evolved(catalog, native):
def _commit(table, messages, native):
commit = table.new_batch_write_builder().new_commit()
+ retained_row_ids = any(file.first_row_id is not None for message in
messages for file in message.new_files)
+ native_publication = native and not retained_row_ids
try:
- guard = (patch('pypaimon.execution.python.write.file_store_commit.'
- 'FileStoreCommit.commit',
- side_effect=AssertionError('Python commit fallback'))
- if native else ExitStack())
- with guard:
+ forbidden =
('pypaimon.execution.python.write.file_store_commit.FileStoreCommit.commit'
+ if native_publication else
'pypaimon.execution.native.write.commit.NativeTableCommit.commit')
+ with patch(forbidden, side_effect=AssertionError('Unexpected
publication backend')):
commit.commit(messages)
+ assert (commit._native_commit is not None) == native_publication
+ assert (commit._python_commit is None) == native_publication
finally:
commit.close()
diff --git a/paimon-python/pypaimon/tests/native_plan_expanded_test.py
b/paimon-python/pypaimon/tests/native_plan_expanded_test.py
index 98697ba41c..8bd66eaed7 100644
--- a/paimon-python/pypaimon/tests/native_plan_expanded_test.py
+++ b/paimon-python/pypaimon/tests/native_plan_expanded_test.py
@@ -263,7 +263,8 @@ def
test_scored_result_requires_a_score_for_each_selected_row(catalog, native):
write(table, [{'id': 1}], schema)
result = ScoredGlobalIndexResult.create(
GlobalIndexResult.from_range(Range(0, 0)).results(), lambda _: None)
- builder = table.copy({'scan.native-plan.enabled':
str(native).lower()}).new_read_builder()
+ builder = table.copy({'scan.native-plan.enabled': str(native).lower(),
+ 'read.native.enabled':
str(native).lower()}).new_read_builder()
with pytest.raises(ValueError, match='score'):
builder.new_scan().with_global_index_result(result).plan()
diff --git a/paimon-python/pypaimon/tests/native_plan_incremental_test.py
b/paimon-python/pypaimon/tests/native_plan_incremental_test.py
index 62d90acf57..0261d3ff95 100644
--- a/paimon-python/pypaimon/tests/native_plan_incremental_test.py
+++ b/paimon-python/pypaimon/tests/native_plan_incremental_test.py
@@ -342,6 +342,7 @@ def
test_incremental_rejects_manifest_delete_before_reconciliation(catalog, nati
table.file_io.write_file(path, json.dumps(data), overwrite=True)
# Allow fallback here: both implementations must reject the malformed
input.
table = table.copy({'scan.native-plan.enabled': str(native).lower(),
+ 'read.native.enabled': str(native).lower(),
'incremental-between-timestamp': '0,200'})
with pytest.raises(ValueError, match='only ADD'):
table.new_read_builder().new_scan().plan()
diff --git a/paimon-python/pypaimon/tests/native_plan_integration_test.py
b/paimon-python/pypaimon/tests/native_plan_integration_test.py
index 46fd57779c..c47534a9c6 100644
--- a/paimon-python/pypaimon/tests/native_plan_integration_test.py
+++ b/paimon-python/pypaimon/tests/native_plan_integration_test.py
@@ -80,12 +80,20 @@ class NativePlanIntegrationTest(unittest.TestCase):
w.close()
c.close()
+ def _python_table(self, name):
+ return self.cat.get_table('default.%s' % name).copy({
+ 'scan.native-plan.enabled': 'false', 'read.native.enabled':
'false',
+ })
+
def _plan_and_read(self, name, native):
- t = self.cat.get_table('default.%s' % name)
+ t = self._python_table(name)
if native:
t = t.copy({'scan.native-plan.enabled': 'true'})
rb = t.new_read_builder()
- plan = rb.new_scan().plan()
+ scan = rb.new_scan()
+ plan = scan.plan()
+ if not native:
+ self.assertFalse(scan._execution._is_native)
rows = rb.new_read().to_arrow(plan.splits()).to_pylist()
return plan.snapshot_id, sorted(rows, key=lambda r: r['k'])
@@ -725,7 +733,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
def read(native, shard=None, slice_=None, limit=None):
table = self.cat.get_table('default.interleaved_t').copy(
- {'scan.native-plan.enabled': str(native).lower()})
+ {'scan.native-plan.enabled': str(native).lower(),
'read.native.enabled': 'false'})
builder = table.new_read_builder()
if limit is not None:
builder.with_limit(limit)
@@ -1362,7 +1370,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
for k in range(1, 4):
self._write('filter_t', [{'k': k, 'v': 'v%d' % k}])
- table = self.cat.get_table('default.filter_t')
+ table = self._python_table('filter_t')
normal_builder = table.new_read_builder()
predicate = normal_builder.new_predicate_builder().equal('k', 2)
normal_builder.with_filter(predicate)
@@ -1389,7 +1397,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
for k in range(1, 4):
self._write('limit_t', [{'k': k, 'v': 'v%d' % k}])
- table = self.cat.get_table('default.limit_t')
+ table = self._python_table('limit_t')
normal = table.new_read_builder().with_limit(1).new_scan().plan()
native_builder = table.copy(
{'scan.native-plan.enabled':
'true'}).new_read_builder().with_limit(1)
@@ -1408,7 +1416,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
self._write('travel_t', [{'k': 2, 'v': 'b'}])
options = {'scan.snapshot-id': '1'}
- normal_table = self.cat.get_table('default.travel_t').copy(options)
+ normal_table = self._python_table('travel_t').copy(options)
normal_builder = normal_table.new_read_builder()
normal_plan = normal_builder.new_scan().plan()
normal_rows = normal_builder.new_read().to_arrow(
@@ -1431,7 +1439,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
self._write('split_t', [{'k': 1, 'v': 'a'}])
self._write('split_t', [{'k': 2, 'v': 'b'}])
options = {'source.split.target-size': '1b'}
- normal_table = self.cat.get_table('default.split_t').copy(options)
+ normal_table = self._python_table('split_t').copy(options)
native_table = normal_table.copy({'scan.native-plan.enabled': 'true'})
normal = normal_table.new_read_builder().new_scan().plan()
@@ -1451,7 +1459,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
self._write('open_cost_t', [{'k': 1, 'v': 'a'}])
self._write('open_cost_t', [{'k': 2, 'v': 'b'}])
self._write('open_cost_t', [{'k': 3, 'v': 'c'}])
- base_table = self.cat.get_table('default.open_cost_t')
+ base_table = self._python_table('open_cost_t')
normal_table = base_table.copy({'source.split.open-file-cost': '64mb'})
native_table = normal_table.copy({'scan.native-plan.enabled': 'true'})
@@ -1477,7 +1485,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
'source.split.target-size': None,
'source.split.open-file-cost': None,
}
- normal_table =
self.cat.get_table('default.split_reset_t').copy(reset_options)
+ normal_table = self._python_table('split_reset_t').copy(reset_options)
native_table = normal_table.copy({'scan.native-plan.enabled': 'true'})
normal = normal_table.new_read_builder().new_scan().plan()
@@ -1525,7 +1533,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
self.cat.create_table(
'default.ex_t', Schema.from_pyarrow_schema(self.schema), False)
self._write('ex_t', [{'k': 1, 'v': 'a'}, {'k': 2, 'v': 'b'}])
- normal =
self.cat.get_table('default.ex_t').new_read_builder().explain()
+ normal = self._python_table('ex_t').new_read_builder().explain()
native = self.cat.get_table('default.ex_t').copy(
{'scan.native-plan.enabled': 'true'}).new_read_builder().explain()
self.assertFalse(normal.native_planned)
@@ -1569,7 +1577,7 @@ class NativePlanIntegrationTest(unittest.TestCase):
def test_empty_table_explain_preserves_native_metadata(self):
self.cat.create_table(
'default.empty_t', Schema.from_pyarrow_schema(self.schema), False)
- normal =
self.cat.get_table('default.empty_t').new_read_builder().explain()
+ normal = self._python_table('empty_t').new_read_builder().explain()
native = self.cat.get_table('default.empty_t').copy(
{'scan.native-plan.enabled': 'true'}).new_read_builder().explain()
diff --git a/paimon-python/pypaimon/tests/native_plan_rest_test.py
b/paimon-python/pypaimon/tests/native_plan_rest_test.py
index 8bf8f3646b..4bbce35a55 100644
--- a/paimon-python/pypaimon/tests/native_plan_rest_test.py
+++ b/paimon-python/pypaimon/tests/native_plan_rest_test.py
@@ -91,7 +91,8 @@ def
test_catalog_snapshot_failure_never_reads_disk(rest_source, code):
with pytest.raises(Exception, match='snapshot unavailable|does not
exist|permission'):
native_plan(table)
with pytest.raises(Exception):
- table.copy({'scan.native-plan.enabled':
'false'}).new_read_builder().new_scan().plan()
+ table.copy({'scan.native-plan.enabled': 'false',
+ 'read.native.enabled':
'false'}).new_read_builder().new_scan().plan()
@pytest.mark.parametrize('from_tag', [False, True], ids=['empty-branch',
'tagged-branch'])
diff --git a/paimon-python/pypaimon/tests/native_plan_test.py
b/paimon-python/pypaimon/tests/native_plan_test.py
index 321fcfc7fa..e78dd116c4 100644
--- a/paimon-python/pypaimon/tests/native_plan_test.py
+++ b/paimon-python/pypaimon/tests/native_plan_test.py
@@ -22,6 +22,7 @@ from types import ModuleType, SimpleNamespace
from unittest.mock import Mock, call, patch
import pyarrow
+import pytest
from pypaimon.execution.native.read.plan import NativeTableScan
from pypaimon.catalog.catalog_context import CatalogContext
from pypaimon.catalog.filesystem_catalog_loader import FileSystemCatalogLoader
@@ -296,14 +297,15 @@ class NativePlanTest(unittest.TestCase):
table.catalog_environment.catalog_loader = loader_type(context)
self.assertEqual(_resolved_schema_file_io_options(table), {})
- def test_switch_defaults_off(self):
+ @pytest.mark.execution_defaults
+ def test_switch_defaults_on_and_can_be_disabled(self):
defaults = CoreOptions(Options({}))
- self.assertFalse(defaults.native_plan_enabled())
- self.assertFalse(defaults.native_read_enabled())
- self.assertTrue(
- CoreOptions(Options({"scan.native-plan.enabled":
"true"})).native_plan_enabled())
- self.assertTrue(
- CoreOptions(Options({"read.native.enabled":
"true"})).native_read_enabled())
+ self.assertTrue(defaults.native_plan_enabled())
+ self.assertTrue(defaults.native_read_enabled())
+ self.assertFalse(
+ CoreOptions(Options({"scan.native-plan.enabled":
"false"})).native_plan_enabled())
+ self.assertFalse(
+ CoreOptions(Options({"read.native.enabled":
"false"})).native_read_enabled())
def test_catalogless_standard_file_io_options_are_preserved(self):
from pypaimon.catalog.catalog_environment import CatalogEnvironment
diff --git a/paimon-python/pypaimon/tests/native_precomputed_bucket_test.py
b/paimon-python/pypaimon/tests/native_precomputed_bucket_test.py
index bbe258ce64..cb7d08522e 100644
--- a/paimon-python/pypaimon/tests/native_precomputed_bucket_test.py
+++ b/paimon-python/pypaimon/tests/native_precomputed_bucket_test.py
@@ -168,13 +168,18 @@ def
test_precomputed_append_projects_full_or_selected_schema(tmp_path):
builder = table.new_batch_write_builder()
writer = builder.new_write()
try:
- with patch.object(writer, '_switch_to_python',
side_effect=AssertionError('Python fallback')):
+ assert table.options.native_write_enabled()
+ assert not isinstance(writer, NativeTableWrite)
+ with
patch('pypaimon.execution.native.write.native_write.NativeTableWrite.write_arrow_batch',
+ side_effect=AssertionError('Bucketed append requires
advancing Python sequence ranges')):
writer.with_write_type(['pt', 'id'])
writer.write_arrow(_batch([1], ['omitted']), bucket=3)
writer.write_arrow(_batch([2], ['omitted']).select(['pt', 'id']),
bucket=3)
messages = writer.prepare_commit()
assert {message.bucket for message in messages} == {3}
assert all(file.write_cols == ['pt', 'id'] for message in messages for
file in message.new_files)
+ assert [(file.min_sequence_number, file.max_sequence_number)
+ for message in messages for file in message.new_files] == [(2,
3)]
builder.new_commit().commit(messages)
finally:
writer.close()
diff --git a/paimon-python/pypaimon/tests/native_row_sidecar_test.py
b/paimon-python/pypaimon/tests/native_row_sidecar_test.py
index 5f514b9cf8..38f8075e90 100644
--- a/paimon-python/pypaimon/tests/native_row_sidecar_test.py
+++ b/paimon-python/pypaimon/tests/native_row_sidecar_test.py
@@ -256,7 +256,8 @@ def
test_sidecars_store_logical_nested_map_and_variant_values(tmp_path, layout):
data = pa.table(values, schema=schema)
builder = table.new_batch_write_builder()
writer = builder.new_write()
- assert isinstance(writer, NativeTableWrite)
+ assert table.options.native_write_enabled()
+ assert isinstance(writer, NativeTableWrite) == (layout != 'variant')
try:
writer.write_arrow(data)
messages = writer.prepare_commit()
diff --git a/paimon-python/pypaimon/tests/native_test_instrumentation_test.py
b/paimon-python/pypaimon/tests/native_test_instrumentation_test.py
index ef45aadf40..39d5f0bfdc 100644
--- a/paimon-python/pypaimon/tests/native_test_instrumentation_test.py
+++ b/paimon-python/pypaimon/tests/native_test_instrumentation_test.py
@@ -32,6 +32,40 @@ pytestmark = [pytest.mark.python_plan,
pytest.mark.python_read,
pytest.mark.python_write, pytest.mark.python_commit]
[email protected]_defaults
[email protected]('execution', ['python', 'native', ''])
[email protected]('python_markers', [False, True])
+def test_execution_lane_preserves_explicit_table_options(monkeypatch,
execution, python_markers):
+ from pypaimon.common.options.core_options import CoreOptions
+ from pypaimon.common.options.options import Options
+
+ path = Path(__file__).resolve().parents[2] / 'conftest.py'
+ spec = importlib.util.spec_from_file_location('execution_instrumentation',
str(path))
+ instrumentation = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(instrumentation)
+ monkeypatch.setenv('PYPAIMON_TEST_EXECUTION', execution)
+ for key in ('PLAN', 'READ', 'WRITE', 'COMMIT', 'UPDATE'):
+ monkeypatch.delenv('PYPAIMON_TEST_NATIVE_' + key, raising=False)
+ request = SimpleNamespace(
+ node=SimpleNamespace(
+ get_closest_marker=lambda name: True if python_markers and
name.startswith('python_') else None,
+ location=('table_read_test.py', 0, 'test_roundtrip')))
+ fixture = instrumentation.enable_native_backends.__wrapped__(request,
monkeypatch)
+ next(fixture)
+ try:
+ for key, accessor in (
+ ('scan.native-plan.enabled', 'native_plan_enabled'),
+ ('read.native.enabled', 'native_read_enabled'),
+ ('write.native.enabled', 'native_write_enabled'),
+ ('commit.native.enabled', 'native_commit_enabled')):
+ assert getattr(CoreOptions(Options({})), accessor)() == (execution
!= 'python' and not python_markers)
+ for value in (True, False):
+ assert getattr(CoreOptions(Options({key:
str(value).lower()})), accessor)() == value
+ finally:
+ with pytest.raises(StopIteration):
+ next(fixture)
+
+
def
test_native_write_tracking_preserves_signature_and_forwards_bucket(monkeypatch):
from pypaimon.execution.native.write.native_write import NativeTableWrite
diff --git
a/paimon-python/pypaimon/tests/native_update_inactive_vector_option_test.py
b/paimon-python/pypaimon/tests/native_update_inactive_vector_option_test.py
index b4de39de57..bf9f43f947 100644
--- a/paimon-python/pypaimon/tests/native_update_inactive_vector_option_test.py
+++ b/paimon-python/pypaimon/tests/native_update_inactive_vector_option_test.py
@@ -153,14 +153,17 @@ def
test_inactive_vector_option_preserves_parquet_blob_mutations(rest_catalog, n
files = [file for message in messages for file in message.new_files]
assert messages
assert all(file.file_name.endswith(('.parquet', '.blob')) and '.vector.'
not in file.file_name for file in files)
+ retained_row_ids = any(file.first_row_id is not None for file in files)
+ assert retained_row_ids == (not operation.endswith('delete'))
+ native_publication = native and not retained_row_ids
commit = builder.new_commit()
try:
- with ExitStack() as stack:
- if native:
-
stack.enter_context(patch('pypaimon.execution.python.write.file_store_commit.'
- 'FileStoreCommit.commit',
- side_effect=AssertionError('Python
commit fallback')))
+ forbidden =
('pypaimon.execution.python.write.file_store_commit.FileStoreCommit.commit'
+ if native_publication else
'pypaimon.execution.native.write.commit.NativeTableCommit.commit')
+ with patch(forbidden, side_effect=AssertionError('Unexpected
publication backend')):
commit.commit(messages, 7) if stream else commit.commit(messages)
+ assert (commit._native_commit is not None) == native_publication
+ assert (commit._python_commit is None) == native_publication
finally:
commit.close()
actual = [{key: value for key, value in row.items() if key != '_ROW_ID'}
for row in _read(table)]
diff --git a/paimon-python/pypaimon/tests/native_variant_update_test.py
b/paimon-python/pypaimon/tests/native_variant_update_test.py
index 6f0f5497c5..7c5856823e 100644
--- a/paimon-python/pypaimon/tests/native_variant_update_test.py
+++ b/paimon-python/pypaimon/tests/native_variant_update_test.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-"""Native partial updates retain Java's shredded VARIANT physical layout."""
+"""Native preferences retain Java-compatible shredded VARIANT files."""
from pypaimon.execution.python.write.table_update_by_row_id import
PythonTableUpdateByRowId
import json
@@ -30,7 +30,6 @@ from pypaimon import CatalogFactory, Schema
from pypaimon.common.predicate_builder import PredicateBuilder
from pypaimon.data.generic_variant import GenericVariant
from pypaimon.schema.data_types import PyarrowFieldParser
-from pypaimon.execution.native.write.native_update import
NativeTableUpdateByRowId
from pypaimon.write.write_dispatch import NativeTableWrite
from pypaimon.execution.python.write.table_update import PythonTableUpdate
from pypaimon.execution.python.write.table_upsert_by_key import
PythonTableUpsert
@@ -68,7 +67,8 @@ def _table(tmp_path, key, enabled, native_write=True):
'unchanged': _variants(unchanged), 'value': [10, 11, 12,
13]}, schema=schema)
builder = table.new_batch_write_builder()
writer, commit = builder.new_write(), builder.new_commit()
- assert isinstance(writer, NativeTableWrite) == native_write
+ assert table.options.native_write_enabled() == native_write
+ assert not isinstance(writer, NativeTableWrite)
try:
# Rolling occurs at batch boundaries. Keep the two incremental calls
# in distinct file groups, as required by the public updater contract.
@@ -105,12 +105,13 @@ def _read(table, native, projection=None):
@contextmanager
-def _native_only():
+def _selected_update(native):
with ExitStack() as stack:
- for cls, method in [(PythonTableUpdateByRowId,
'_load_existing_files_info'),
- (PythonTableUpdate,
'_build_predicate_update_table'),
- (PythonTableUpsert, '_upsert_partition')]:
- stack.enter_context(patch.object(cls, method,
side_effect=AssertionError('Python update fallback')))
+ if native:
+ for cls, method in [(PythonTableUpdateByRowId,
'_load_existing_files_info'),
+ (PythonTableUpdate,
'_build_predicate_update_table'),
+ (PythonTableUpsert, '_upsert_partition')]:
+ stack.enter_context(patch.object(cls, method,
side_effect=AssertionError('Python update fallback')))
yield
@@ -140,13 +141,13 @@ def test_native_variant_partial_updates(tmp_path, stream,
key, enabled, operatio
builder = table.new_stream_write_builder() if stream else
table.new_batch_write_builder()
update = builder.new_update().with_update_type(['payload'])
data = pa.table({'_ROW_ID': [ids[0], ids[2]], 'payload': changed})
- with _native_only():
+ with _selected_update(operation == 'ordinary_column'):
if operation == 'row_id':
messages = (update.update_by_arrow_with_row_id(data, 7) if stream
else update.update_by_arrow_with_row_id(data))
elif operation == 'incremental':
updater = update.new_update_by_row_id(7) if stream else
update.new_update_by_row_id()
- assert isinstance(updater._execution, NativeTableUpdateByRowId)
+ assert isinstance(updater._execution, PythonTableUpdateByRowId)
updater.update_columns(data.slice(0, 1), ['payload'])
updater.update_columns(data.slice(1), ['payload'])
messages = updater.commit_messages
@@ -178,6 +179,8 @@ def test_native_variant_partial_updates(tmp_path, stream,
key, enabled, operatio
if 'payload' in physical.names:
names = [field.name for field in
physical.field('payload').type]
assert 'typed_value' in names
+ assert all(field.metadata and b'PARQUET:field_id' in
field.metadata
+ for field in physical.field('payload').type)
if file.write_cols == ['value']:
assert physical.names == ['value']
commit = builder.new_commit()
@@ -196,3 +199,36 @@ def test_native_variant_partial_updates(tmp_path, stream,
key, enabled, operatio
assert [row['payload'] for row in rows] == expected_payload
assert [row['unchanged'] for row in rows] == untouched
assert [row['value'] for row in rows] == expected_values
+
+
[email protected]('operation', ['upsert', 'merge'])
+def
test_scalar_updates_with_unmatched_inserts_keep_variant_field_ids(tmp_path,
operation):
+ from pypaimon.table.data_evolution_merge_into import WhenMatched,
WhenNotMatched, source_col
+
+ table, schema, original, untouched = _table(tmp_path,
'variant.shreddingSchema', False)
+ source = pa.table({'id': [0, 4], 'payload': _variants([None, {'count': 4,
'name': 'inserted'}]),
+ 'unchanged': _variants([None, {'count': 14, 'name':
'untouched'}]),
+ 'value': [999, 14]}, schema=schema)
+ builder = table.new_batch_write_builder()
+ with _selected_update(False):
+ update = builder.new_update().with_update_type(['value'])
+ if operation == 'upsert':
+ messages = update.upsert_by_arrow_with_key(source, ['id'])
+ else:
+ messages = update.merge_into(source, on=['id'], when_matched=[
+ WhenMatched.update({'value': source_col('value')})],
when_not_matched=[WhenNotMatched('*')])
+ for message in messages:
+ for file in message.new_files:
+ physical = pq.read_schema(file.file_path)
+ if 'payload' in physical.names:
+ assert all(field.metadata and b'PARQUET:field_id' in
field.metadata
+ for field in physical.field('payload').type)
+ commit = builder.new_commit()
+ try:
+ commit.commit(messages)
+ finally:
+ commit.close()
+ rows = _read(table, True)
+ assert [row['payload'] for row in rows] == original + [{'count': 4,
'name': 'inserted'}]
+ assert [row['unchanged'] for row in rows] == untouched + [{'count': 14,
'name': 'untouched'}]
+ assert [row['value'] for row in rows] == [999, 11, 12, 13, 14]
diff --git a/paimon-python/pypaimon/tests/native_video_read_test.py
b/paimon-python/pypaimon/tests/native_video_read_test.py
index 2493055498..053e1aa6dd 100644
--- a/paimon-python/pypaimon/tests/native_video_read_test.py
+++ b/paimon-python/pypaimon/tests/native_video_read_test.py
@@ -133,8 +133,12 @@ def
test_native_update_of_normal_columns_keeps_packed_video_frames(tmp_path, nat
pa.table({'_ROW_ID': [0], 'id': [20]},
schema=pa.schema([('_ROW_ID', pa.int64()), ('id', pa.int32())]))]))
commit = builder.new_commit()
try:
- commit.commit(messages)
- assert commit._native_commit is not None
+ assert any(file.first_row_id is not None for message in messages for
file in message.new_files)
+ with
patch('pypaimon.execution.native.write.commit.NativeTableCommit.commit',
+ side_effect=AssertionError('Retained row IDs require Python
publication')):
+ commit.commit(messages)
+ assert commit._native_commit is None
+ assert commit._python_commit is not None
finally:
commit.close()
after = _read(table, True)[0].to_pylist()
diff --git a/paimon-python/pypaimon/tests/native_write_test.py
b/paimon-python/pypaimon/tests/native_write_test.py
index 2bcb5f3caf..ea9e65ae15 100644
--- a/paimon-python/pypaimon/tests/native_write_test.py
+++ b/paimon-python/pypaimon/tests/native_write_test.py
@@ -57,10 +57,10 @@ def _rows(table):
builder.new_scan().plan().splits()).to_pylist(), key=lambda row:
row['id'])
[email protected]_write
-def test_native_write_is_opt_in():
- assert not CoreOptions(Options({})).native_write_enabled()
- assert CoreOptions(Options({'write.native.enabled':
'true'})).native_write_enabled()
[email protected]_defaults
+def test_native_write_is_default_and_can_be_disabled():
+ assert CoreOptions(Options({})).native_write_enabled()
+ assert not CoreOptions(Options({'write.native.enabled':
'false'})).native_write_enabled()
@pytest.mark.parametrize('streaming', [False, True])
diff --git a/paimon-python/pypaimon/tests/native_write_type_test.py
b/paimon-python/pypaimon/tests/native_write_type_test.py
index 59fca4d726..1718f7710e 100644
--- a/paimon-python/pypaimon/tests/native_write_type_test.py
+++ b/paimon-python/pypaimon/tests/native_write_type_test.py
@@ -61,9 +61,13 @@ def _rows(table):
return
builder.new_read().to_arrow(builder.new_scan().plan().splits()).sort_by('value').to_pylist()
-def _native_only(stack, writer, use_native):
- assert isinstance(writer, NativeTableWrite) == use_native
- if use_native:
+def _check_writer(stack, writer, use_native):
+ assert writer.table.options.native_write_enabled() == use_native
+ # Rust 0.5.0 cannot retain bucketed append sequence ranges. Keep the
+ # Native preference enabled while verifying its pre-write Python selection.
+ native_selected = use_native and writer.table.options.bucket() == -1
+ assert isinstance(writer, NativeTableWrite) == native_selected
+ if native_selected:
stack.enter_context(patch.object(writer, '_switch_to_python',
side_effect=AssertionError('Python fallback')))
@@ -91,7 +95,7 @@ def
test_upstream_bucket_subset_omits_hash_columns_without_leaking_full_input(
writer = builder.new_write()
try:
with ExitStack() as stack:
- _native_only(stack, writer, use_native)
+ _check_writer(stack, writer, use_native)
writer.with_write_type(columns)
with pytest.raises(ValueError, match='missing.*not in table
schema|Column.*missing'):
writer.with_write_type(['missing'])
@@ -122,7 +126,7 @@ def
test_partial_upstream_groups_reject_invalid_buckets_and_mixed_partitions(res
data = pa.table({'value': [42, 43], 'pt': [7, 8]})
try:
with ExitStack() as stack:
- _native_only(stack, writer, use_native)
+ _check_writer(stack, writer, use_native)
writer.with_write_type(['value', 'pt'])
before = _files(table)
for bucket in (-1, 4):
@@ -153,7 +157,7 @@ def
test_complete_reordered_append_type_keeps_field_identity_and_copies_column_n
writer = builder.new_write()
try:
with ExitStack() as stack:
- _native_only(stack, writer, use_native)
+ _check_writer(stack, writer, use_native)
writer.with_write_type(columns)
columns.reverse()
writer.write_arrow(data)
@@ -180,7 +184,7 @@ def
test_full_input_routes_before_projecting_unwritten_routing_fields(
writer = builder.new_write()
try:
with ExitStack() as stack:
- _native_only(stack, writer, use_native)
+ _check_writer(stack, writer, use_native)
writer.with_write_type(list(columns))
before = _files(table)
writer.write_arrow(data.slice(0, 0))
@@ -216,7 +220,7 @@ def
test_rows_route_with_unwritten_columns_without_requiring_other_fields(
writer = builder.new_write()
try:
with ExitStack() as stack:
- _native_only(stack, writer, use_native)
+ _check_writer(stack, writer, use_native)
writer.with_write_type(['value'])
writer.write_row(row)
messages = _finish(builder, writer)
@@ -245,7 +249,7 @@ def
test_upstream_bucket_partial_overwrite_preserves_other_partitions(rest_catal
writer = builder.new_write()
try:
with ExitStack() as stack:
- _native_only(stack, writer, use_native)
+ _check_writer(stack, writer, use_native)
writer.with_write_type(['value', 'pt'])
writer.write_arrow(pa.table({'value': [42], 'pt': [7]}), bucket=2)
messages = _finish(builder, writer)
diff --git a/paimon-python/pypaimon/tests/parquet_row_range_test.py
b/paimon-python/pypaimon/tests/parquet_row_range_test.py
index 3450cd7973..af903ce4b0 100644
--- a/paimon-python/pypaimon/tests/parquet_row_range_test.py
+++ b/paimon-python/pypaimon/tests/parquet_row_range_test.py
@@ -54,6 +54,8 @@ class _LocalFileIO:
def _commit_with_row_groups(table, data):
+ # This fixture injects row groups through the Python FileIO writer below.
+ table = table.copy({"write.native.enabled": "false"})
original = table.file_io.write_parquet
def patched(path, arrow_table, **kwargs):
diff --git a/paimon-python/pypaimon/tests/public_streaming_table_scan_test.py
b/paimon-python/pypaimon/tests/public_streaming_table_scan_test.py
index 853d128e60..41624eadda 100644
--- a/paimon-python/pypaimon/tests/public_streaming_table_scan_test.py
+++ b/paimon-python/pypaimon/tests/public_streaming_table_scan_test.py
@@ -65,10 +65,10 @@ def
test_standard_constructor_arguments_and_defaults_remain_stable(public, execu
@pytest.mark.parametrize('entrypoint', [AsyncStreamingTableScan,
StreamTableScan, 'builder'])
[email protected]('native_plan,native_read', [(True, False), (False,
True), (True, True)])
[email protected]('native_plan,native_read', [(True, False), (None,
True), (True, True)])
def test_all_streaming_entrypoints_select_native_without_python_resources(
table, entrypoint, native_plan, native_read):
- selected = table.copy({'scan.native-plan.enabled':
str(native_plan).lower(),
+ selected = table.copy({'scan.native-plan.enabled': None if native_plan is
None else str(native_plan).lower(),
'read.native.enabled': str(native_read).lower()})
core = Mock()
expected = Plan([], 7)
@@ -91,10 +91,12 @@ def
test_all_streaming_entrypoints_select_native_without_python_resources(
core.plan.assert_called_once()
[email protected]_plan
@pytest.mark.parametrize('entrypoint', [AsyncStreamingTableScan,
StreamTableScan, 'builder'])
@pytest.mark.parametrize('failure', ['disabled', 'unavailable', 'preparation'])
def test_streaming_fallback_is_selected_before_planning(table, entrypoint,
failure):
- selected = table.copy({'read.native.enabled': str(failure !=
'disabled').lower()})
+ selected = table.copy({'scan.native-plan.enabled': 'false' if failure ==
'disabled' else None,
+ 'read.native.enabled': 'true'})
with patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=failure == 'preparation') as runtime, patch(
'pypaimon.execution.native.read.streaming_table_scan.native_stream_scan',
diff --git a/paimon-python/pypaimon/tests/ray_native_row_id_recovery_test.py
b/paimon-python/pypaimon/tests/ray_native_row_id_recovery_test.py
index 1c9f8cfae2..69d0db5834 100644
--- a/paimon-python/pypaimon/tests/ray_native_row_id_recovery_test.py
+++ b/paimon-python/pypaimon/tests/ray_native_row_id_recovery_test.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-"""Cross-schema Ray recovery keeps REST publication on the native backend."""
+"""Native-enabled Ray recovery publishes retained row IDs with Python
validation."""
from unittest.mock import patch
@@ -47,7 +47,7 @@ def
test_partition_scoped_recovery_with_native_plan(native_rest_catalog):
@pytest.mark.parametrize('logical_conflict', [False, True])
@pytest.mark.parametrize('rename', [False, True])
-def test_schema_recovery_preserves_native_rest_commit(native_rest_catalog,
logical_conflict, rename):
+def
test_schema_recovery_publishes_retained_row_ids_with_python(native_rest_catalog,
logical_conflict, rename):
ray = pytest.importorskip('ray')
initialized_here = not ray.is_initialized()
if initialized_here:
@@ -64,6 +64,7 @@ def
test_schema_recovery_preserves_native_rest_commit(native_rest_catalog, logic
table = native_rest_catalog.get_table(target)
messages =
table.new_batch_write_builder().new_update().update_by_arrow_with_row_id(
pa.table({'_ROW_ID': [0], 'age': [99]}))
+ assert any(file.first_row_id is not None for message in messages for
file in message.new_files)
baseline = table.snapshot_manager().get_latest_snapshot()
table = table.copy({'scan.snapshot-id': str(baseline.id)})
changes = [SchemaChange.add_column('extra', AtomicType('INT'))]
@@ -84,24 +85,26 @@ def
test_schema_recovery_preserves_native_rest_commit(native_rest_catalog, logic
commit.commit(concurrent)
finally:
commit.close()
- # Publish a physical compaction using the existing test fixture. The
- # recovery itself must keep the user's native publication route.
+ # Publish a physical compaction using the existing test fixture. Keep
+ # Native enabled while Python validates the recovered retained IDs.
tables._compact_all_data_files(current.copy({'commit.native.enabled':
'false'}))
latest = current.snapshot_manager().get_latest_snapshot()
assert baseline.schema_id != latest.schema_id
from pypaimon.execution.native.write.commit import NativeTableCommit
+ from pypaimon.execution.python.write.file_store_commit import
FileStoreCommit
from pypaimon.execution.python.write.commit.row_id_conflict import
check_row_id_conflicts
- native_calls = []
- original = NativeTableCommit.commit
+ python_calls = []
+ original = FileStoreCommit.commit
- def native_commit(commit, *args, **kwargs):
- native_calls.append(commit)
+ def python_commit(commit, *args, **kwargs):
+ assert commit.table.options.native_commit_enabled()
+ python_calls.append(commit)
return original(commit, *args, **kwargs)
- with patch.object(NativeTableCommit, 'commit', new=native_commit),
patch(
-
'pypaimon.execution.python.write.file_store_commit.FileStoreCommit.commit',
- side_effect=AssertionError('Native publication must not fall back
to Python'),
+ with patch.object(FileStoreCommit, 'commit', new=python_commit),
patch.object(
+ NativeTableCommit, 'commit',
+ side_effect=AssertionError('Retained row IDs require Python
publication'),
), patch.object(
NativeTableCommit, 'check_row_id_conflicts',
side_effect=AssertionError('Cross-schema checks are not supported
by the native checker'),
@@ -115,7 +118,7 @@ def
test_schema_recovery_preserves_native_rest_commit(native_rest_catalog, logic
else:
_commit_update_messages(table, messages, num_partitions=2)
logical_check.assert_called_once()
- assert len(native_calls) == (0 if logical_conflict else 1)
+ assert len(python_calls) == (0 if logical_conflict else 1)
read = current.copy({'scan.native-plan.enabled':
'true'}).new_read_builder()
rows =
read.new_read().to_arrow(read.new_scan().plan().splits()).sort_by('id').to_pydict()
assert rows[column] == ([10, 100, 10, 10] if logical_conflict else
[99, 10, 10, 10])
@@ -128,7 +131,7 @@ def
test_schema_recovery_preserves_native_rest_commit(native_rest_catalog, logic
@pytest.mark.parametrize('change', ['rename', 'recreate', 'add_child'])
-def test_nested_schema_recovery_with_native_rest_commit(native_rest_catalog,
change):
+def
test_nested_schema_recovery_publishes_retained_row_ids_with_python(native_rest_catalog,
change):
ray = pytest.importorskip('ray')
initialized_here = not ray.is_initialized()
if initialized_here:
@@ -138,6 +141,7 @@ def
test_nested_schema_recovery_with_native_rest_commit(native_rest_catalog, cha
tables.catalog = native_rest_catalog
target, table, messages, child_path, _ = tables._nested_update_fixture(
'row', {'commit.native.enabled': 'true'})
+ assert any(file.first_row_id is not None for message in messages for
file in message.new_files)
path = ['profile'] + child_path
changes = [SchemaChange.drop_column(path)] if change == 'recreate'
else [
SchemaChange.rename_column(path, 'renamed'),
@@ -149,17 +153,19 @@ def
test_nested_schema_recovery_with_native_rest_commit(native_rest_catalog, cha
tables._compact_all_data_files(current.copy({'commit.native.enabled':
'false'}))
before_snapshot = current.snapshot_manager().get_latest_snapshot().id
from pypaimon.execution.native.write.commit import NativeTableCommit
+ from pypaimon.execution.python.write.file_store_commit import
FileStoreCommit
- native_calls = []
- original = NativeTableCommit.commit
+ python_calls = []
+ original = FileStoreCommit.commit
- def native_commit(commit, *args, **kwargs):
- native_calls.append(commit)
+ def python_commit(commit, *args, **kwargs):
+ assert commit.table.options.native_commit_enabled()
+ python_calls.append(commit)
return original(commit, *args, **kwargs)
- with patch.object(NativeTableCommit, 'commit', new=native_commit),
patch(
-
'pypaimon.execution.python.write.file_store_commit.FileStoreCommit.commit',
- side_effect=AssertionError('Native publication must not fall back
to Python'),
+ with patch.object(FileStoreCommit, 'commit', new=python_commit),
patch.object(
+ NativeTableCommit, 'commit',
+ side_effect=AssertionError('Retained row IDs require Python
publication'),
):
if change != 'rename':
error = 'cannot restore a dropped field' if change ==
'recreate' else 'cannot expand ROW field'
@@ -167,7 +173,7 @@ def
test_nested_schema_recovery_with_native_rest_commit(native_rest_catalog, cha
_commit_update_messages(table, messages, num_partitions=2)
else:
_commit_update_messages(table, messages, num_partitions=2)
- assert len(native_calls) == (1 if change == 'rename' else 0)
+ assert len(python_calls) == (1 if change == 'rename' else 0)
assert current.snapshot_manager().get_latest_snapshot().id ==
before_snapshot + (1 if change == 'rename' else 0)
read = current.copy({'scan.native-plan.enabled':
'true'}).new_read_builder()
rows =
read.new_read().to_arrow(read.new_scan().plan().splits()).sort_by('id').to_pydict()
diff --git a/paimon-python/pypaimon/tests/torch_read_test.py
b/paimon-python/pypaimon/tests/torch_read_test.py
index 23cad98c3e..44902bb268 100644
--- a/paimon-python/pypaimon/tests/torch_read_test.py
+++ b/paimon-python/pypaimon/tests/torch_read_test.py
@@ -683,6 +683,8 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=2,
num_workers=2,
+ # Native row reads use Polars pools, which cannot be inherited
through fork.
+ multiprocessing_context='spawn',
shuffle=False
)
@@ -799,6 +801,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=3,
num_workers=2,
+ multiprocessing_context='spawn',
shuffle=True,
generator=torch.Generator().manual_seed(7),
)
@@ -1038,6 +1041,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=None,
num_workers=2,
+ multiprocessing_context='spawn',
shuffle=False,
)
@@ -1145,7 +1149,7 @@ class TorchReadTest(unittest.TestCase):
[],
)
batches = list(DataLoader(
- dataset, batch_size=None, num_workers=2
+ dataset, batch_size=None, num_workers=2,
multiprocessing_context='spawn'
))
user_ids = [
value
@@ -1549,7 +1553,7 @@ class TorchReadTest(unittest.TestCase):
]).to_torch(streaming=True)
rows = []
for batch in DataLoader(
- dataset, batch_size=2, num_workers=2, shuffle=False):
+ dataset, batch_size=2, num_workers=2, shuffle=False,
multiprocessing_context='spawn'):
rows.extend(zip(
batch['episode_id'].tolist(),
batch['video'],
@@ -1590,6 +1594,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=2,
num_workers=3,
+ multiprocessing_context='spawn',
shuffle=False
)
@@ -1673,6 +1678,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=1000,
num_workers=4,
+ multiprocessing_context='spawn',
shuffle=False
)
@@ -1765,6 +1771,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=1000,
num_workers=8,
+ multiprocessing_context='spawn',
shuffle=False
)
@@ -2140,6 +2147,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=8,
num_workers=2,
+ multiprocessing_context='spawn',
persistent_workers=True,
shuffle=False,
)
@@ -2316,6 +2324,7 @@ class TorchReadTest(unittest.TestCase):
dataset,
batch_size=8,
num_workers=num_workers,
+ multiprocessing_context='spawn' if num_workers else None,
shuffle=False,
)
all_user_ids = []
diff --git a/paimon-python/pypaimon/tests/variant_test.py
b/paimon-python/pypaimon/tests/variant_test.py
index 950eaea1cb..6184dcfd22 100644
--- a/paimon-python/pypaimon/tests/variant_test.py
+++ b/paimon-python/pypaimon/tests/variant_test.py
@@ -1532,7 +1532,7 @@ class TestVariantPaimonTable(unittest.TestCase):
builder = table.new_batch_write_builder()
writer = builder.new_write()
self.assertEqual(type(writer).__name__,
- 'NativeBatchTableWrite' if native else
'BatchTableWrite')
+ 'NativeBatchTableWrite' if native and not
shredded else 'BatchTableWrite')
commit = builder.new_commit()
try:
for start in range(0, len(gvs), 3):
diff --git a/paimon-python/pypaimon/write/backend_dispatch.py
b/paimon-python/pypaimon/write/backend_dispatch.py
index f25af5ab51..9f75fa3f28 100644
--- a/paimon-python/pypaimon/write/backend_dispatch.py
+++ b/paimon-python/pypaimon/write/backend_dispatch.py
@@ -350,8 +350,7 @@ def create_shard_update_execution(table, projection,
columns, commit_user, shard
def create_row_id_plan_execution(table, plan):
"""Select pure routing once; execution errors never replay another
backend."""
- if (table.options.native_write_enabled() or
table.options.native_read_enabled()
- or table.options.native_plan_enabled()):
+ if table.options.native_write_enabled():
from pypaimon.execution.native.write.row_id_plan import
create_native_row_id_plan, NativeRowIdPlan
native = create_native_row_id_plan(table, plan)
if native is not None:
diff --git a/paimon-python/pyproject.toml b/paimon-python/pyproject.toml
index 6358a9f835..6c396cb792 100644
--- a/paimon-python/pyproject.toml
+++ b/paimon-python/pyproject.toml
@@ -65,6 +65,7 @@ dependencies = [
"pyarrow>=6,<7; python_version < '3.7'",
"pyarrow>=7,<13; python_version >= '3.7' and python_version < '3.8'",
"pyarrow>=16,!=19.0.0,<23; python_version >= '3.8'",
+ "pypaimon-rust>=0.5.0; python_version >= '3.10'",
"pyroaring<=0.3.3; python_version < '3.7'",
"pyroaring<=0.4.5; python_version == '3.7'",
"pyroaring>=1.0.0,<=1.0.3; python_version == '3.8'",
@@ -162,7 +163,6 @@ datafusion = [
]
sql = [
"pypaimon[datafusion]; python_version >= '3.10'",
- "pypaimon-rust>=0.3.0; python_version >= '3.10'",
]
hdfs = [
"hdfs-native>=0.13,<1; python_version >= '3.10' and platform_system !=
'Windows'",
@@ -183,8 +183,7 @@ lint = [
"flake8>=4,<5; python_version < '3.8'",
"flake8>=7,<8; python_version >= '3.8'",
]
-# Ordinary Python and Torch CI must not install the released Rust wheel via
SQL.
-# Native CI builds the companion Rust main and uses the complete dev group.
+# Shared integration dependencies; Native CI also installs the SQL extra via
dev.
python-tests = [
{include-group = "test"},
{include-group = "lint"},
@@ -199,7 +198,7 @@ dev = [
"pypaimon[sql]",
]
torch = [
- {include-group = "python-tests"},
+ {include-group = "dev"},
"pypaimon[torch,lerobot]",
"torchdata>=0.11,<0.12; python_version >= '3.10'",
]
diff --git a/tools/ci/test_python_commands.py b/tools/ci/test_python_commands.py
new file mode 100644
index 0000000000..57cee5a37c
--- /dev/null
+++ b/tools/ci/test_python_commands.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Check Python CI command boundaries without running Java interoperability
tests."""
+
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+SCRIPT = Path(__file__).resolve().parents[2] / 'paimon-python' / 'dev' /
'lint-python.sh'
+NATIVE_STAGES = ('PLAN', 'READ', 'WRITE', 'UPDATE', 'COMMIT')
+
+
+class PythonCommandsTest(unittest.TestCase):
+ def
test_mixed_sessions_keep_execution_without_full_suite_coverage_gates(self):
+ for execution in ('native', 'python'):
+ for mixed_status in (0, 17):
+ with self.subTest(execution=execution, status=mixed_status),
tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ dev = root / 'dev'
+ dev.mkdir()
+ script = dev / SCRIPT.name
+ shutil.copyfile(str(SCRIPT), str(script))
+ capture = root / 'environment.json'
+ runner = dev / 'run_mixed_tests.sh'
+ runner.write_text(
+ '#!/usr/bin/env bash\n'
+ '"$CI_TEST_PYTHON" -c \'import json, os; '
+ 'print(json.dumps({k: v for k, v in os.environ.items()
'
+ 'if k.startswith("PYPAIMON_TEST_")}))\' >
"$CI_TEST_CAPTURE"\n'
+ 'exit "$CI_TEST_MIXED_STATUS"\n')
+ env = dict(
+ os.environ,
+ CI_TEST_PYTHON=sys.executable,
+ CI_TEST_CAPTURE=str(capture),
+ CI_TEST_MIXED_STATUS=str(mixed_status),
+ PYPAIMON_TEST_EXECUTION=execution,
+ )
+ env.update({'PYPAIMON_TEST_NATIVE_' + stage: '1' for stage
in NATIVE_STAGES})
+ result = subprocess.run(
+ ['bash', str(script), '-i', 'mixed'], env=env,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
+ self.assertEqual(0 if mixed_status == 0 else 1,
result.returncode, result.stdout)
+ child_env = json.loads(capture.read_text())
+ self.assertEqual(execution,
child_env['PYPAIMON_TEST_EXECUTION'])
+ for stage in NATIVE_STAGES:
+ self.assertEqual('0',
child_env.get('PYPAIMON_TEST_NATIVE_' + stage), stage)
+
+
+if __name__ == '__main__':
+ unittest.main()