This is an automated email from the ASF dual-hosted git repository. XiaoHongbo-Hope pushed a commit to branch codex/release-2.1-rust-writer-compat in repository https://gitbox.apache.org/repos/asf/paimon.git
commit a594d8ca9b2ea58d0af9460187558656d7b44cc5 Author: xiaohongbo <[email protected]> AuthorDate: Tue Nov 17 16:09:17 2026 +0800 [python] Constrain release-2.1 Rust wheels below 0.5.0 --- .github/workflows/ci-python.yml | 20 +- paimon-python/pypaimon/multimodal/query.py | 3 +- .../pypaimon/ray/data_evolution_merge_join.py | 11 +- .../pypaimon/read/reader/data_file_batch_reader.py | 3 +- .../read/reader/nested_leaf_batch_reader.py | 5 +- paimon-python/pypaimon/read/split_read.py | 5 +- paimon-python/pypaimon/read/table_read.py | 14 +- paimon-python/pypaimon/schema/arrow_schema.py | 74 +------ paimon-python/pypaimon/tests/binary_row_test.py | 3 - paimon-python/pypaimon/tests/blob_table_test.py | 8 +- .../pypaimon/tests/data_evolution_test.py | 15 +- .../tests/map_shared_shredding_write_test.py | 3 +- .../pypaimon/tests/native_system_columns_test.py | 1 + .../pypaimon/tests/ray_read_by_row_id_test.py | 1 + .../pypaimon/tests/reader_primary_key_test.py | 11 +- .../pypaimon/tests/rest/rest_read_write_test.py | 15 +- .../pypaimon/tests/rest/rest_simple_test.py | 5 +- .../pypaimon/tests/runtime_read_schema_test.py | 226 --------------------- paimon-python/pypaimon/tests/serializable_test.py | 3 +- paimon-python/pypaimon/tests/table_commit_test.py | 3 +- .../pypaimon/tests/table_upsert_by_key_test.py | 3 +- .../pypaimon/tests/write/table_write_test.py | 17 +- paimon-python/pypaimon/write/native_commit.py | 2 +- paimon-python/pypaimon/write/native_merge_into.py | 24 +-- paimon-python/pypaimon/write/native_update.py | 10 +- paimon-python/pypaimon/write/native_write.py | 12 +- .../pypaimon/write/table_update_by_row_id.py | 33 +-- paimon-python/pypaimon/write/table_write.py | 35 +--- paimon-python/pyproject.toml | 2 +- 29 files changed, 107 insertions(+), 460 deletions(-) diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml index a2252ac396..ff27ab248f 100644 --- a/.github/workflows/ci-python.yml +++ b/.github/workflows/ci-python.yml @@ -165,27 +165,33 @@ jobs: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal echo "$HOME/.cargo/bin" >> $GITHUB_PATH - - name: Install paimon-rust 0.5.0 - run: | - python -m pip install --upgrade pip - python -m pip install "pypaimon-rust==0.5.0" - - 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: Build paimon-rust from the verified 2.1 revision + run: | + # Install after the SQL extra, which constrains published wheels below 0.5.0. + # This verified source revision also reports 0.5.0, but predates that release. + python -m pip install --upgrade "git+https://github.com/apache/paimon-rust.git@ae62495d275ccf3811c38128788be8cf7e144177#subdirectory=bindings/python" + python -m pip check + - name: Verify native wheel provenance run: | python - <<'PY' import importlib.metadata as metadata + import json import pypaimon_rust.datafusion distribution = metadata.distribution('pypaimon-rust') - assert distribution.version == '0.5.0' - print('pypaimon-rust', distribution.version) + source = json.loads(distribution.read_text('direct_url.json')) + assert source['vcs_info']['commit_id'] == 'ae62495d275ccf3811c38128788be8cf7e144177' + print('pypaimon-rust', distribution.version, + 'commit', source['vcs_info']['commit_id']) PY - name: Run Python tests with native planning, reading, writing, updating and committing diff --git a/paimon-python/pypaimon/multimodal/query.py b/paimon-python/pypaimon/multimodal/query.py index 776691fcb9..d4d70267c8 100644 --- a/paimon-python/pypaimon/multimodal/query.py +++ b/paimon-python/pypaimon/multimodal/query.py @@ -20,7 +20,6 @@ from typing import Any, Callable, Dict, List, Optional, Tuple import pyarrow as pa -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.common.where_parser import parse_where_clause from pypaimon.multimodal.blob_read import fetch_blob_bodies from pypaimon.schema.data_types import is_array_blob_type, is_blob_type, is_map_blob_type @@ -530,7 +529,7 @@ class _PreFilterQuery(ScanQuery): added_row_id = projection is None or row_id_name not in projection if metadata_only: row_ids = pa.array(list(result.results()), type=pa.int64()) - fields = [read_arrow_schema([SpecialFields.ROW_ID]).field(row_id_name)] * (len(projection) or 1) + fields = [pa.field(row_id_name, pa.int64(), nullable=False)] * (len(projection) or 1) table = pa.Table.from_arrays( [row_ids] * len(fields), schema=pa.schema(fields)) else: diff --git a/paimon-python/pypaimon/ray/data_evolution_merge_join.py b/paimon-python/pypaimon/ray/data_evolution_merge_join.py index 6c9754ce46..c745db9e8e 100644 --- a/paimon-python/pypaimon/ray/data_evolution_merge_join.py +++ b/paimon-python/pypaimon/ray/data_evolution_merge_join.py @@ -877,11 +877,16 @@ def distributed_update_apply( def _read_output_schema(table, read_cols: Sequence[str]) -> "pa.Schema": """Result schema: each projected column's type plus int64 ``_ROW_ID``, in ``read_cols`` order. Shared by the empty-result paths so they can't drift.""" - from pypaimon.schema.arrow_schema import read_arrow_schema + from pypaimon.schema.data_types import PyarrowFieldParser from pypaimon.table.special_fields import SpecialFields - full = read_arrow_schema(table.table_schema.fields + [SpecialFields.ROW_ID]) - return pa.schema([full.field(col) for col in read_cols]) + rid = SpecialFields.ROW_ID.name + full = PyarrowFieldParser.from_paimon_schema(table.table_schema.fields) + # Keep each field's nullability so an empty result matches a non-empty read. + return pa.schema([ + pa.field(rid, pa.int64(), nullable=False) if col == rid else full.field(col) + for col in read_cols + ]) def distributed_read_by_row_id( diff --git a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py index 7370350e14..b50842299f 100644 --- a/paimon-python/pypaimon/read/reader/data_file_batch_reader.py +++ b/paimon-python/pypaimon/read/reader/data_file_batch_reader.py @@ -22,7 +22,6 @@ import pyarrow as pa import pyarrow.compute as pc from pyarrow import RecordBatch -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.common.file_io import FileIO from pypaimon.utils.arrow_utils import zero_column_batch from pypaimon.data.map_shared_shredding import ( @@ -199,7 +198,7 @@ class DataFileBatchReader(RecordBatchReader): self._file_data_field_map = { field.name: field for field in source_fields } - self.schema_map = {field.name: field for field in read_arrow_schema(fields)} + self.schema_map = {field.name: field for field in PyarrowFieldParser.from_paimon_schema(fields)} self.row_tracking_enabled = row_tracking_enabled self.first_row_id = first_row_id self.row_id_offsets = row_id_offsets diff --git a/paimon-python/pypaimon/read/reader/nested_leaf_batch_reader.py b/paimon-python/pypaimon/read/reader/nested_leaf_batch_reader.py index c28e285816..cb4c4f81c4 100644 --- a/paimon-python/pypaimon/read/reader/nested_leaf_batch_reader.py +++ b/paimon-python/pypaimon/read/reader/nested_leaf_batch_reader.py @@ -28,8 +28,7 @@ from pypaimon.read.reader.data_file_batch_reader import \ from pypaimon.read.reader.field_indices import ( blob_field_indices, descriptor_field_indices, vector_field_indices) from pypaimon.read.reader.iface.record_batch_reader import RecordBatchReader -from pypaimon.schema.arrow_schema import read_arrow_schema -from pypaimon.schema.data_types import DataField +from pypaimon.schema.data_types import DataField, PyarrowFieldParser from pypaimon.utils.arrow_utils import as_blob_data, is_blob_data @@ -62,7 +61,7 @@ class NestedLeafBatchReader(RecordBatchReader): len(name_paths), len(output_fields))) self._inner = inner self._paths = name_paths - self._schema = read_arrow_schema(output_fields) + self._schema = PyarrowFieldParser.from_paimon_schema(output_fields) self.file_io = inner.file_io self.blob_field_indices = blob_field_indices(output_fields) self.descriptor_field_indices = descriptor_field_indices( diff --git a/paimon-python/pypaimon/read/split_read.py b/paimon-python/pypaimon/read/split_read.py index 7007886f2b..97ee03b777 100644 --- a/paimon-python/pypaimon/read/split_read.py +++ b/paimon-python/pypaimon/read/split_read.py @@ -21,7 +21,6 @@ from copy import copy from functools import partial from typing import Callable, Dict, List, Optional, Tuple -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.common.merge_engine_dispatch import build_merge_function from pypaimon.common.options.core_options import CoreOptions, MergeEngine from pypaimon.common.predicate import Predicate @@ -1754,9 +1753,7 @@ class DataEvolutionSplitRead(SplitRead): if not field.type.nullable: raise ValueError(f"Field {field} is not null but can't find any file contains it.") - # Column-group readers return runtime nullability after schema evolution. - # Preserve those nested types when assembling the columns into one batch. - output_schema = read_arrow_schema(all_read_fields) + output_schema = PyarrowFieldParser.from_paimon_schema(all_read_fields) return DataEvolutionMergeReader(row_offsets, field_offsets, file_record_readers, schema=output_schema) def _create_file_reader( diff --git a/paimon-python/pypaimon/read/table_read.py b/paimon-python/pypaimon/read/table_read.py index 06d3cdad4c..e0e683d973 100644 --- a/paimon-python/pypaimon/read/table_read.py +++ b/paimon-python/pypaimon/read/table_read.py @@ -42,9 +42,8 @@ from pypaimon.read.read_type import (adapter_output_paths, extract_array, output from pypaimon.read.split_read import (DataEvolutionSplitRead, MergeFileSplitRead, RawFileSplitRead, SplitRead, deferred_blob_field_names) -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.schema.data_types import ( - DataField, MapType, is_blob_file_field, is_map_blob_type) + DataField, MapType, PyarrowFieldParser, is_blob_file_field, is_map_blob_type) from pypaimon.table.row.offset_row import OffsetRow from pypaimon.utils.arrow_utils import zero_column_batch @@ -461,7 +460,7 @@ class TableRead: return projected if predicate_field_names(self.predicate) & extra_names else adapter def _output_arrow_schema(self): - return output_schema(read_arrow_schema(self.read_type), self.output_projection) + return output_schema(PyarrowFieldParser.from_paimon_schema(self.read_type), self.output_projection) @staticmethod def _apply_output_projection_to_schema(schema, projection): @@ -832,7 +831,7 @@ class TableRead: def _flatten_native_nested_batch(self, batch, schema): _, paths = self._reader_adapter() arrays = [extract_array(batch, path) for path in paths] - fields = list(read_arrow_schema(self._adapter_read_type)) + fields = list(PyarrowFieldParser.from_paimon_schema(self._adapter_read_type)) if self.include_row_kind: arrays.insert(0, batch.column(ROW_KIND_COLUMN)) fields.insert(0, batch.schema.field(ROW_KIND_COLUMN)) @@ -1140,13 +1139,12 @@ class TableRead: yield from self._convert_rows_to_arrow_batches_with_row_kind( row_tuples, row_kinds, schema) return - physical_schema = read_arrow_schema(self._adapter_read_type) + physical_schema = PyarrowFieldParser.from_paimon_schema(self._adapter_read_type) if self.include_row_kind: physical_schema = self._add_row_kind_to_schema(physical_schema) for batch in self._convert_rows_to_arrow_batches_with_row_kind( row_tuples, row_kinds, physical_schema): - yield self._try_to_pad_batch_by_schema( - self._project_batch_to_output(batch), schema, allow_type_cast=True) + yield self._project_batch_to_output(batch) def _convert_rows_to_arrow_batches_with_row_kind( self, @@ -1840,7 +1838,7 @@ class TableRead: needs_convert_back = False if not isinstance(reader, RecordBatchReader): - schema = read_arrow_schema(effective_read_type) + schema = PyarrowFieldParser.from_paimon_schema(effective_read_type) reader = RecordReaderToBatchAdapter(reader, schema, include_row_kind=self.include_row_kind) if getattr(reader, 'blob_field_indices', None) is None: from pypaimon.read.reader.field_indices import ( diff --git a/paimon-python/pypaimon/schema/arrow_schema.py b/paimon-python/pypaimon/schema/arrow_schema.py index 7ff1ac162a..98a232033b 100644 --- a/paimon-python/pypaimon/schema/arrow_schema.py +++ b/paimon-python/pypaimon/schema/arrow_schema.py @@ -19,46 +19,15 @@ import pyarrow as pa -from pypaimon.schema.data_types import ArrayType, MapType, PyarrowFieldParser, RowType - - -def _read_arrow_type(data_type): - if isinstance(data_type, RowType): - return pa.struct([pa.field(field.name, _read_arrow_type(field.type)) for field in data_type.fields]) - if isinstance(data_type, ArrayType): - return pa.list_(pa.field('element', _read_arrow_type(data_type.element))) - if isinstance(data_type, MapType): - return pa.map_(pa.field('key', _read_arrow_type(data_type.key), nullable=False), - pa.field('value', _read_arrow_type(data_type.value))) - return PyarrowFieldParser.from_paimon_type(data_type) - - -def read_arrow_schema(fields): - """Use runtime NULL transport without changing logical write constraints. - - Preserve the legacy schema when the optional native runtime is absent. - Construct the schema locally, as on master, so Python-only types such as - VECTOR do not need to pass through the Rust schema JSON parser. - """ - try: - from pypaimon_rust.data import normalize_array_for_write # noqa: F401 - except ImportError: - return PyarrowFieldParser.from_paimon_schema(fields) - return pa.schema([pa.field(field.name, _read_arrow_type(field.type)) for field in fields]) - - -def _normalize_string_type(data_type, ignore_child_nullability=False): - def child(field): - field = field.with_type(_normalize_string_type(field.type, ignore_child_nullability)) - return field.with_nullable(True) if ignore_child_nullability else field +def _normalize_string_type(data_type): if pa.types.is_large_string(data_type): return pa.string() if pa.types.is_struct(data_type): - return pa.struct([child(field) for field in data_type]) + return pa.struct([field.with_type(_normalize_string_type(field.type)) for field in data_type]) if (pa.types.is_list(data_type) or pa.types.is_large_list(data_type) or pa.types.is_fixed_size_list(data_type)): - field = child(data_type.value_field) + field = data_type.value_field.with_type(_normalize_string_type(data_type.value_type)) if pa.types.is_large_list(data_type): return pa.large_list(field) if pa.types.is_fixed_size_list(data_type): @@ -69,14 +38,13 @@ def _normalize_string_type(data_type, ignore_child_nullability=False): # includes the sorting flag. Preserve it along with the child fields. sorted_keys = data_type == pa.map_(data_type.key_field, data_type.item_field, keys_sorted=True) return pa.map_( - data_type.key_field.with_type(_normalize_string_type(data_type.key_type, ignore_child_nullability)), - child(data_type.item_field), + data_type.key_field.with_type(_normalize_string_type(data_type.key_type)), + data_type.item_field.with_type(_normalize_string_type(data_type.item_type)), keys_sorted=sorted_keys) return data_type -def arrow_schemas_compatible(source, target, check_top_level_nullability=True, allow_binary_compatibility=False, - check_nested_nullability=True): +def arrow_schemas_compatible(source, target, check_top_level_nullability=True, allow_binary_compatibility=False): """Compare ordered fields, ignoring metadata and STRING offset width. The writer opts into its existing top-level nullability and binary / @@ -87,9 +55,7 @@ def arrow_schemas_compatible(source, target, check_top_level_nullability=True, a for actual, expected in zip(source, target): if check_top_level_nullability and actual.nullable != expected.nullable: return False - if (actual.type == expected.type - or _normalize_string_type(actual.type, not check_nested_nullability) - == _normalize_string_type(expected.type, not check_nested_nullability)): + if actual.type == expected.type or _normalize_string_type(actual.type) == _normalize_string_type(expected.type): continue if allow_binary_compatibility and all( pa.types.is_binary(t) or pa.types.is_fixed_size_binary(t) @@ -99,32 +65,6 @@ def arrow_schemas_compatible(source, target, check_top_level_nullability=True, a return True -def normalize_arrow_write_nullability(data, target): - """Validate read-result NULLs in core before restoring writer child fields.""" - try: - from pypaimon_rust.data import normalize_array_for_write - except ImportError: - return data - options = dict(check_top_level_nullability=False, allow_binary_compatibility=True) - if (arrow_schemas_compatible(data.schema, target, **options) - or not arrow_schemas_compatible(data.schema, target, check_nested_nullability=False, **options)): - return data - arrays, fields = [], [] - for column, field, expected in zip(data.columns, data.schema, target): - if column.type != expected.type: - if isinstance(column, pa.ChunkedArray): - column = pa.chunked_array( - [normalize_array_for_write(chunk, expected.type) for chunk in column.chunks], type=expected.type) - else: - column = normalize_array_for_write(column, expected.type) - arrays.append(column) - fields.append(field.with_type(column.type)) - schema = pa.schema(fields, metadata=data.schema.metadata) - if isinstance(data, pa.RecordBatch): - return pa.RecordBatch.from_arrays(arrays, schema=schema) - return pa.Table.from_arrays(arrays, schema=schema) - - def normalize_arrow_strings(data): """Safely normalize large_string input before routing or buffering rows. diff --git a/paimon-python/pypaimon/tests/binary_row_test.py b/paimon-python/pypaimon/tests/binary_row_test.py index ab18654c7e..5e8420e9eb 100644 --- a/paimon-python/pypaimon/tests/binary_row_test.py +++ b/paimon-python/pypaimon/tests/binary_row_test.py @@ -26,7 +26,6 @@ import pyarrow as pa import pytest from pypaimon import CatalogFactory, Schema -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.manifest.schema.manifest_entry import ManifestEntry from pypaimon.manifest.schema.simple_stats import SimpleStats from pypaimon.read.scanner.file_scanner import FileScanner @@ -79,8 +78,6 @@ class BinaryRowTest(unittest.TestCase): write.close() commit.close() - cls.data = cls.data.cast(read_arrow_schema(append_table.fields)) - @classmethod def tearDownClass(cls): shutil.rmtree(cls.tempdir, ignore_errors=True) diff --git a/paimon-python/pypaimon/tests/blob_table_test.py b/paimon-python/pypaimon/tests/blob_table_test.py index c839a0b238..3a1ad88a38 100755 --- a/paimon-python/pypaimon/tests/blob_table_test.py +++ b/paimon-python/pypaimon/tests/blob_table_test.py @@ -1716,6 +1716,7 @@ class DedicatedFormatWriterTest(unittest.TestCase): read_builder = table.new_read_builder() result = read_builder.new_read().to_arrow( read_builder.new_scan().plan().splits()) + self.assertFalse(result.schema.field('payloads').type.item_field.nullable) self.assertEqual( { row['id']: None if row['payloads'] is None else dict(row['payloads']) @@ -1738,7 +1739,7 @@ class DedicatedFormatWriterTest(unittest.TestCase): 'payloads': pa.array([[('bad', None)]], type=nullable_map_type), }, schema=incompatible_schema) incompatible_writer = table.new_batch_write_builder().new_write() - with self.assertRaisesRegex(ValueError, "Input schema isn't consistent|non-nullable"): + with self.assertRaisesRegex(ValueError, "Input schema isn't consistent"): incompatible_writer.write_arrow(incompatible_data) incompatible_writer.abort() @@ -1786,6 +1787,9 @@ class DedicatedFormatWriterTest(unittest.TestCase): read_builder = table.new_read_builder() result = read_builder.new_read().to_arrow( read_builder.new_scan().plan().splits()) + self.assertFalse( + result.schema.field('payloads').type.value_field.nullable + ) self.assertEqual( { row['id']: row['payloads'] @@ -1808,7 +1812,7 @@ class DedicatedFormatWriterTest(unittest.TestCase): 'payloads': pa.array([[b'bad', None]], type=nullable_array_type), }, schema=incompatible_schema) incompatible_writer = table.new_batch_write_builder().new_write() - with self.assertRaisesRegex(ValueError, "Input schema isn't consistent|[Nn]on-nullable"): + with self.assertRaisesRegex(ValueError, "Input schema isn't consistent"): incompatible_writer.write_arrow(incompatible_data) incompatible_writer.abort() diff --git a/paimon-python/pypaimon/tests/data_evolution_test.py b/paimon-python/pypaimon/tests/data_evolution_test.py index f86ce9097a..99af2e4933 100644 --- a/paimon-python/pypaimon/tests/data_evolution_test.py +++ b/paimon-python/pypaimon/tests/data_evolution_test.py @@ -28,7 +28,6 @@ import pyarrow.dataset as ds import pytest from pypaimon import CatalogFactory, Schema -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.common.predicate import Predicate from pypaimon.manifest.manifest_list_manager import ManifestListManager from pypaimon.table.row.offset_row import OffsetRow @@ -1050,8 +1049,14 @@ class DataEvolutionTest(unittest.TestCase): table_scan = read_builder.new_scan() table_read = read_builder.new_read() actual_with_meta = table_read.to_arrow(table_scan.plan().splits()) - self.assertEqual(actual_with_meta.column('_ROW_ID').null_count, 0) - self.assertEqual(actual_with_meta.column('_SEQUENCE_NUMBER').null_count, 0) + self.assertFalse( + actual_with_meta.schema.field('_ROW_ID').nullable, + '_ROW_ID must be non-nullable per SpecialFields', + ) + self.assertFalse( + actual_with_meta.schema.field('_SEQUENCE_NUMBER').nullable, + '_SEQUENCE_NUMBER must be non-nullable per SpecialFields', + ) rb_with_row_id = table.new_read_builder().with_projection(['f0', 'f1', 'f2', '_ROW_ID']) pb = rb_with_row_id.new_predicate_builder() @@ -1241,7 +1246,6 @@ class DataEvolutionTest(unittest.TestCase): ('f1', pa.int16()), pa.field('_SEQUENCE_NUMBER', pa.int64(), nullable=False), ])) - expect_data = expect_data.cast(read_arrow_schema(read_builder.read_type())) self.assertEqual(actual_data, expect_data) self.assertEqual(len(actual_data.schema), len(expect_data.schema), 'Read output column count must match schema') @@ -1265,6 +1269,8 @@ class DataEvolutionTest(unittest.TestCase): table_scan = read_builder.new_scan() table_read = read_builder.new_read() actual_data = table_read.to_arrow(table_scan.plan().splits()) + self.assertFalse(actual_data.schema.field('_ROW_ID').nullable) + self.assertFalse(actual_data.schema.field('_SEQUENCE_NUMBER').nullable) expect_data = pa.Table.from_pydict({ 'f0': [3, 4], 'f1': [-1001, 1002], @@ -1276,7 +1282,6 @@ class DataEvolutionTest(unittest.TestCase): pa.field('_ROW_ID', pa.int64(), nullable=False), pa.field('_SEQUENCE_NUMBER', pa.int64(), nullable=False), ])) - expect_data = expect_data.cast(read_arrow_schema(read_builder.read_type())) self.assertEqual(actual_data, expect_data) self.assertEqual(len(actual_data.schema), len(expect_data.schema), 'Read output column count must match schema') diff --git a/paimon-python/pypaimon/tests/map_shared_shredding_write_test.py b/paimon-python/pypaimon/tests/map_shared_shredding_write_test.py index 4195431680..2cbc44cace 100644 --- a/paimon-python/pypaimon/tests/map_shared_shredding_write_test.py +++ b/paimon-python/pypaimon/tests/map_shared_shredding_write_test.py @@ -170,8 +170,7 @@ class MapSharedShreddingWriteTest(unittest.TestCase): reader = table.new_read_builder() result = reader.new_read().to_arrow(reader.new_scan().plan().splits()) # Arrow 6 cannot convert non-nullable MAP values to scalars. - read_value_type = result.schema.field('metrics').type.item_type - actual = result.column('metrics').cast(pa.map_(pa.string(), read_value_type)) + actual = result.column('metrics').cast(pa.map_(pa.string(), value_type)) self.assertEqual(expected, actual.to_pylist()) def test_nested_non_nullable_map_values_in_subprocess(self): diff --git a/paimon-python/pypaimon/tests/native_system_columns_test.py b/paimon-python/pypaimon/tests/native_system_columns_test.py index 9c6fceb4e6..8ba62eab7a 100644 --- a/paimon-python/pypaimon/tests/native_system_columns_test.py +++ b/paimon-python/pypaimon/tests/native_system_columns_test.py @@ -92,6 +92,7 @@ def test_partial_column_updates_keep_latest_metadata_provider(tmp_path, native, ['_SEQUENCE_NUMBER', 'w', '_ROW_ID', 'v', 'id']): result = _read(table, native, projection) assert result.column_names == projection + assert not result.schema.field('_SEQUENCE_NUMBER').nullable assert result['_SEQUENCE_NUMBER'].null_count == 0 if 'id' in projection: result = result.sort_by('id') diff --git a/paimon-python/pypaimon/tests/ray_read_by_row_id_test.py b/paimon-python/pypaimon/tests/ray_read_by_row_id_test.py index 1627acc0c5..9257c8fd4d 100644 --- a/paimon-python/pypaimon/tests/ray_read_by_row_id_test.py +++ b/paimon-python/pypaimon/tests/ray_read_by_row_id_test.py @@ -530,6 +530,7 @@ class RayReadByRowIdTest(unittest.TestCase): target, pa.table({"_ROW_ID": pa.array([], pa.int64())}), self.catalog_options, projection=proj) self.assertTrue(real_schema.equals(empty.schema().base_schema)) + self.assertFalse(empty.schema().base_schema.field("_ROW_ID").nullable) def test_custom_row_id_col(self): target = self._create() diff --git a/paimon-python/pypaimon/tests/reader_primary_key_test.py b/paimon-python/pypaimon/tests/reader_primary_key_test.py index c22bc512de..4a1d59043b 100644 --- a/paimon-python/pypaimon/tests/reader_primary_key_test.py +++ b/paimon-python/pypaimon/tests/reader_primary_key_test.py @@ -24,7 +24,6 @@ import unittest import pyarrow as pa from pypaimon import CatalogFactory, Schema -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.common.options.core_options import CoreOptions @@ -49,7 +48,7 @@ class PkReaderTest(unittest.TestCase): 'item_id': [1001, 1002, 1003, 1004, 1005, 1007, 1008], 'behavior': ['a', 'b-new', 'c', None, 'e', 'g', 'h'], 'dt': ['p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2'], - }, schema=read_arrow_schema(Schema.from_pyarrow_schema(cls.pa_schema).fields)) + }, schema=cls.pa_schema) @classmethod def tearDownClass(cls): @@ -277,7 +276,7 @@ class PkReaderTest(unittest.TestCase): 'item_id': [1001, 1002, 1003, 1004, 1005, 1007, 1008], 'behavior': ['a', 'b-new', 'c', None, 'e', 'g', 'h'], 'dt': ['p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2'], - }, schema=read_arrow_schema(table.fields)) + }, schema=self.pa_schema) self.assertEqual(actual, expected) def test_nullable_primary_key(self): @@ -482,7 +481,7 @@ class PkReaderTest(unittest.TestCase): 'item_id': [1001, 1002, 1002, 1003, 1004, 1005, 1007, 1008], 'behavior': ['a', 'b', 'b-new', 'c', None, 'e', 'g', 'h'], 'dt': ['p1', 'p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2'], - }, schema=read_arrow_schema(table.fields)) + }, schema=self.pa_schema) self.assertEqual(expected, actual) # test 3 table = table.copy({CoreOptions.INCREMENTAL_BETWEEN_TIMESTAMP.key(): str(t1) + ',' + str(t2)}) @@ -493,7 +492,7 @@ class PkReaderTest(unittest.TestCase): "item_id": [1002, 1005, 1007, 1008], "behavior": ["b-new", "e", "g", "h"], "dt": ["p1", "p2", "p1", "p2"] - }, schema=read_arrow_schema(table.fields)) + }, schema=self.pa_schema) self.assertEqual(expected, actual) def test_incremental_read_multi_snapshots(self): @@ -531,7 +530,7 @@ class PkReaderTest(unittest.TestCase): 'item_id': [1000 + i for i in range(11, 21)], 'behavior': [f'snap{i}' for i in range(11, 21)], 'dt': ['p1' if i % 2 == 1 else 'p2' for i in range(11, 21)], - }, schema=read_arrow_schema(table.fields)).sort_by('user_id') + }, schema=self.pa_schema).sort_by('user_id') self.assertEqual(expected, actual) def test_manifest_creation_time_timestamp(self): diff --git a/paimon-python/pypaimon/tests/rest/rest_read_write_test.py b/paimon-python/pypaimon/tests/rest/rest_read_write_test.py index eef4854434..eb5d4b4594 100644 --- a/paimon-python/pypaimon/tests/rest/rest_read_write_test.py +++ b/paimon-python/pypaimon/tests/rest/rest_read_write_test.py @@ -22,7 +22,6 @@ import pyarrow as pa from pypaimon.common.options import Options from pypaimon.catalog.catalog_context import CatalogContext -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon import CatalogFactory from pypaimon.catalog.catalog_exception import TableNotExistException from pypaimon.catalog.rest.rest_catalog import RESTCatalog @@ -328,7 +327,7 @@ class RESTTableReadWriteTest(RESTBaseTest): read_builder = table.new_read_builder() actual = self._read_test_table(read_builder).sort_by('user_id') - self.assertEqual(actual, self.pk_expected.cast(read_arrow_schema(table.fields))) + self.assertEqual(actual, self.pk_expected) def test_pk_orc_reader(self): schema = Schema.from_pyarrow_schema(self.pa_schema, @@ -366,7 +365,7 @@ class RESTTableReadWriteTest(RESTBaseTest): read_builder = table.new_read_builder() actual = self._read_test_table(read_builder).sort_by('user_id') - self.assertEqual(actual, expected.cast(read_arrow_schema(table.fields))) + self.assertEqual(actual, expected) def test_pk_lance_reader(self): schema = Schema.from_pyarrow_schema(self.pa_schema, @@ -386,7 +385,7 @@ class RESTTableReadWriteTest(RESTBaseTest): read_builder = table.new_read_builder() actual = self._read_test_table(read_builder).sort_by('user_id') - self.assertEqual(actual, self.pk_expected.cast(read_arrow_schema(table.fields))) + self.assertEqual(actual, self.pk_expected) def test_lance_ao_reader_with_filter(self): schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['dt'], options={'file.format': 'lance'}) @@ -434,7 +433,7 @@ class RESTTableReadWriteTest(RESTBaseTest): self.pk_expected.slice(1, 1), # 2/b self.pk_expected.slice(5, 1) # 7/g ]) - self.assertEqual(actual, expected.cast(read_arrow_schema(table.fields))) + self.assertEqual(actual, expected) def test_pk_lance_reader_no_bucket(self): """Test Lance format with PrimaryKey table without specifying bucket.""" @@ -451,7 +450,7 @@ class RESTTableReadWriteTest(RESTBaseTest): read_builder = table.new_read_builder() actual = self._read_test_table(read_builder).sort_by('user_id') - self.assertEqual(actual, self.pk_expected.cast(read_arrow_schema(table.fields))) + self.assertEqual(actual, self.pk_expected) def test_pk_reader_with_filter(self): schema = Schema.from_pyarrow_schema(self.pa_schema, @@ -473,7 +472,7 @@ class RESTTableReadWriteTest(RESTBaseTest): self.pk_expected.slice(1, 1), # 2/b self.pk_expected.slice(5, 1) # 7/g ]) - self.assertEqual(actual, expected.cast(read_arrow_schema(table.fields))) + self.assertEqual(actual, expected) def test_pk_reader_with_projection(self): schema = Schema.from_pyarrow_schema(self.pa_schema, @@ -486,7 +485,7 @@ class RESTTableReadWriteTest(RESTBaseTest): read_builder = table.new_read_builder().with_projection(['dt', 'user_id', 'behavior']) actual = self._read_test_table(read_builder).sort_by('user_id') - expected = self.pk_expected.cast(read_arrow_schema(table.fields)).select(['dt', 'user_id', 'behavior']) + expected = self.pk_expected.select(['dt', 'user_id', 'behavior']) self.assertEqual(actual, expected) def test_write_wrong_schema(self): diff --git a/paimon-python/pypaimon/tests/rest/rest_simple_test.py b/paimon-python/pypaimon/tests/rest/rest_simple_test.py index 008419fede..1217661c29 100644 --- a/paimon-python/pypaimon/tests/rest/rest_simple_test.py +++ b/paimon-python/pypaimon/tests/rest/rest_simple_test.py @@ -21,7 +21,6 @@ import pyarrow as pa import pytest from pypaimon import Schema -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.catalog.catalog_exception import DatabaseAlreadyExistException, TableAlreadyExistException, \ DatabaseNotExistException, TableNotExistException from pypaimon.schema.data_types import AtomicType, DataField @@ -628,7 +627,7 @@ class RESTSimpleTest(RESTBaseTest): splits.extend(read_builder.new_scan().with_shard(2, 3).plan().splits()) table_read = read_builder.new_read() actual = table_read.to_arrow(splits) - expected_sorted = table_sort_by(self.expected.cast(read_arrow_schema(table.fields)), 'user_id') + expected_sorted = table_sort_by(self.expected.cast(self.pk_pa_schema), 'user_id') actual_sorted = table_sort_by(actual, 'user_id') self.assertEqual(actual_sorted, expected_sorted) @@ -665,7 +664,7 @@ class RESTSimpleTest(RESTBaseTest): 'behavior': ['b', 'c', 'a', 'd', 'e'], 'dt': ['2025-08-10', '2025-08-11', '2000-10-10', '2025-08-12', '2025-08-13'] } - expected = pa.Table.from_pydict(data_expected, schema=read_arrow_schema(table.fields)) + expected = pa.Table.from_pydict(data_expected, schema=table_pa_schema) self.assertEqual(actual.combine_chunks(), expected.combine_chunks()) def test_with_shard_uniform_division(self): diff --git a/paimon-python/pypaimon/tests/runtime_read_schema_test.py b/paimon-python/pypaimon/tests/runtime_read_schema_test.py deleted file mode 100644 index 1b5733e3c2..0000000000 --- a/paimon-python/pypaimon/tests/runtime_read_schema_test.py +++ /dev/null @@ -1,226 +0,0 @@ -# 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. - -"""Read transport nullability must preserve write constraints.""" - -import sys -from unittest.mock import patch - -import pyarrow as pa -import pytest - -from pypaimon.schema.arrow_schema import read_arrow_schema, normalize_arrow_write_nullability -from pypaimon.schema.data_types import ArrayType, AtomicType, DataField, PyarrowFieldParser - - -def test_no_native_runtime_preserves_legacy_schema_and_writer_input(): - fields = [DataField(0, 'values', ArrayType(True, AtomicType('INT', nullable=False)))] - declared = PyarrowFieldParser.from_paimon_schema(fields) - data = pa.table({'values': [[1]]}, schema=declared) - with patch.dict(sys.modules, {'pypaimon_rust.data': None}): - assert read_arrow_schema(fields).equals(declared) - assert normalize_arrow_write_nullability(data, declared) is data - - [email protected]('native', [False, True]) [email protected]('record_batch', [False, True]) -def test_read_write_roundtrip_and_visible_null_rejection(tmp_path, native, record_batch): - pytest.importorskip('pypaimon_rust.data') - from pypaimon.tests.native_blob_collection_write_test import _table - - table = _table(tmp_path, native, not_null=True) - fields_before = [field.to_dict() for field in table.fields] - declared = PyarrowFieldParser.from_paimon_schema(table.fields) - rows = [dict(id=1, items=[b'abc'], attrs=[('key', b'value')]), - dict(id=2, items=None, attrs=None), dict(id=3, items=[], attrs=[])] - data = pa.Table.from_pylist(rows, schema=declared) - - def write(data): - builder = table.new_batch_write_builder() - writer, commit = builder.new_write(), builder.new_commit() - try: - assert (type(writer).__name__ == 'NativeTableWrite') == native - if record_batch: - for batch in data.to_batches(): - writer.write_arrow_batch(batch) - else: - writer.write_arrow(data) - commit.commit(writer.prepare_commit()) - finally: - writer.close() - commit.close() - - def read(): - builder = table.copy({'read.native.enabled': 'true'}).new_read_builder() - return builder.new_read().to_arrow(builder.new_scan().plan().splits()) - - write(data) - result = read() - assert result.schema.field('items').type.value_field.nullable - assert result.schema.field('attrs').type.item_field.nullable - assert sorted(result.to_pylist(), key=lambda row: row['id']) == rows - write(result) - assert sorted(read().to_pylist(), key=lambda row: row['id']) == sorted(rows * 2, key=lambda row: row['id']) - snapshot = table.snapshot_manager().get_latest_snapshot().id - for bad_row in (dict(id=4, items=[None], attrs=[]), - dict(id=4, items=[], attrs=[('key', None)])): - with pytest.raises((ValueError, TypeError)): - write(pa.Table.from_pylist([bad_row], schema=result.schema)) - assert table.snapshot_manager().get_latest_snapshot().id == snapshot - assert [field.to_dict() for field in table.fields] == fields_before - - -def test_normalizer_handles_empty_chunks_and_hidden_row_children(): - pytest.importorskip('pypaimon_rust.data') - actual = pa.struct([pa.field('value', pa.int32())]) - required = pa.struct([pa.field('value', pa.int32(), nullable=False)]) - source = pa.schema([('row', actual)]) - target = pa.schema([('row', required)]) - hidden = pa.StructArray.from_arrays([pa.array([None, 1], type=pa.int32())], - fields=list(actual), mask=pa.array([True, False])) - data = pa.Table.from_arrays([pa.chunked_array([hidden.slice(0, 0), hidden])], schema=source) - result = normalize_arrow_write_nullability(data, target) - assert result.to_pylist() == [{'row': None}, {'row': {'value': 1}}] - assert result.schema == target - empty = pa.Table.from_arrays([pa.chunked_array([], type=actual)], schema=source) - assert normalize_arrow_write_nullability(empty, target).schema == target - bad = pa.Table.from_pylist([{'row': {'value': None}}], schema=source) - with pytest.raises((ValueError, TypeError)): - normalize_arrow_write_nullability(bad, target) - - -def test_runtime_read_schema_matches_rust_for_nested_fields(): - import json - rust = pytest.importorskip('pypaimon_rust.data') - from pypaimon.schema.data_types import MapType, RowType - fields = [DataField(0, 'row', RowType(False, [ - DataField(1, 'items', ArrayType(False, AtomicType('INT', nullable=False))), - DataField(2, 'attrs', MapType(False, AtomicType('STRING'), AtomicType('BLOB', nullable=False))), - ]))] - expected = rust.read_arrow_schema(json.dumps([field.to_dict() for field in fields])) - assert read_arrow_schema(fields).equals(expected, check_metadata=False) - - [email protected]('native', [False, True]) -def test_row_id_update_rejects_null_in_declared_not_null_column(tmp_path, native): - if native: - pytest.importorskip('pypaimon_rust.data') - from pypaimon import CatalogFactory, Schema - catalog = CatalogFactory.create({'warehouse': str(tmp_path)}) - catalog.create_database('db', True) - declared = pa.schema([pa.field('id', pa.int32(), nullable=False), - pa.field('score', pa.int32(), nullable=False)]) - catalog.create_table('db.t', Schema.from_pyarrow_schema(declared, options={ - 'row-tracking.enabled': 'true', 'data-evolution.enabled': 'true', - 'write.native.enabled': str(native).lower(), - }), False) - table = catalog.get_table('db.t') - builder = table.new_batch_write_builder() - writer, commit = builder.new_write(), builder.new_commit() - try: - writer.write_arrow(pa.Table.from_pylist([{'id': 1, 'score': 2}], schema=declared)) - commit.commit(writer.prepare_commit()) - finally: - writer.close() - commit.close() - snapshot = table.snapshot_manager().get_latest_snapshot().id - updater = table.new_batch_write_builder().new_update().with_update_type(['score']) - bad = pa.table({'_ROW_ID': pa.array([0], type=pa.int64()), - 'score': pa.array([None], type=pa.int32())}) - with pytest.raises((ValueError, TypeError), match='[Nn]ull'): - updater.update_by_arrow_with_row_id(bad) - assert table.snapshot_manager().get_latest_snapshot().id == snapshot - read = table.new_read_builder() - assert read.new_read().to_arrow(read.new_scan().plan().splits()).to_pylist() == [{'id': 1, 'score': 2}] - - [email protected]('native_write', [False, True]) [email protected]('data_type,values', [ - (pa.struct([pa.field('n', pa.int32(), nullable=False)]), - [{'n': 1}, None, {'n': 3}, None]), - (pa.list_(pa.struct([pa.field('n', pa.int32(), nullable=False)])), - [[{'n': 1}], [], None, [{'n': 4}]]), - (pa.map_(pa.string(), pa.field('value', pa.int32(), nullable=False)), - [[('a', 1)], [], None, [('d', 4)]]), -]) -def test_de_column_group_merge_uses_runtime_nested_schema(tmp_path, native_write, data_type, values): - pytest.importorskip('pypaimon_rust.data') - from pypaimon.tests.native_nested_update_test import _table - table, _ = _table(tmp_path, data_type, native_write) - field_before = table.fields[1].to_dict() - builder = table.new_batch_write_builder() - updater = builder.new_update().with_update_type(['value']) - changes = pa.table({'_ROW_ID': pa.array(range(4), type=pa.int64()), - 'value': pa.array(values, type=data_type)}) - messages = updater.update_by_arrow_with_row_id(changes) - commit = builder.new_commit() - try: - commit.commit(messages) - finally: - commit.close() - for native_read in (False, True): - copy = table.copy({'scan.native-plan.enabled': str(native_read).lower(), - 'read.native.enabled': str(native_read).lower()}) - reader = copy.new_read_builder() - result = reader.new_read().to_arrow(reader.new_scan().plan().splits()).sort_by('id') - assert result['id'].to_pylist() == [0, 1, 2, 3] - assert result['value'].to_pylist() == values - assert result['untouched'].to_pylist() == [10, 11, 12, 13] - assert table.fields[1].to_dict() == field_before - - [email protected]('native_write', [False, True]) -def test_partial_row_update_preserves_hidden_null_children(tmp_path, native_write): - pytest.importorskip('pypaimon_rust.data') - from pypaimon.tests.native_nested_update_test import _table - data_type = pa.struct([pa.field('value', pa.int32(), nullable=False)]) - table, _ = _table(tmp_path, data_type, native_write) - seed = table.new_batch_write_builder() - writer, commit = seed.new_write(), seed.new_commit() - try: - writer.write_arrow(pa.Table.from_pylist( - [{'id': i, 'value': None, 'untouched': i + 10} for i in range(4, 8)], - schema=read_arrow_schema(table.fields))) - commit.commit(writer.prepare_commit()) - finally: - writer.close() - commit.close() - fields_before = [field.to_dict() for field in table.fields] - builder = table.new_batch_write_builder() - updater = builder.new_update().with_update_type(['value']) - changes = pa.table({'_ROW_ID': pa.array([5], type=pa.int64()), - 'value': pa.array([{'value': 7}], type=data_type)}) - messages = updater.update_by_arrow_with_row_id(changes) - commit = builder.new_commit() - try: - commit.commit(messages) - finally: - commit.close() - for native_read in (False, True): - copy = table.copy({'read.native.enabled': str(native_read).lower(), - 'scan.native-plan.enabled': str(native_read).lower()}) - reader = copy.new_read_builder() - result = reader.new_read().to_arrow(reader.new_scan().plan().splits()).sort_by('id') - assert result['value'].to_pylist() == [None] * 5 + [{'value': 7}, None, None] - assert result['untouched'].to_pylist() == list(range(10, 18)) - assert [field.to_dict() for field in table.fields] == fields_before - snapshot = table.snapshot_manager().get_latest_snapshot().id - bad = pa.table({'_ROW_ID': pa.array([5], type=pa.int64()), - 'value': pa.array([{'value': None}], type=pa.struct([('value', pa.int32())]))}) - with pytest.raises((ValueError, TypeError), match='[Nn]ull'): - table.new_batch_write_builder().new_update().with_update_type(['value']).update_by_arrow_with_row_id(bad) - assert table.snapshot_manager().get_latest_snapshot().id == snapshot diff --git a/paimon-python/pypaimon/tests/serializable_test.py b/paimon-python/pypaimon/tests/serializable_test.py index c5a8067eea..0222c0a6b0 100644 --- a/paimon-python/pypaimon/tests/serializable_test.py +++ b/paimon-python/pypaimon/tests/serializable_test.py @@ -24,7 +24,6 @@ import unittest import pyarrow as pa from pypaimon import CatalogFactory -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon import Schema @@ -55,7 +54,7 @@ class SerializableTest(unittest.TestCase): 'item_id': [1001, 1002, 1003, 1004, 1005, 1007, 1008], 'behavior': ['a', 'b-new', 'c', None, 'e', 'g', 'h'], 'dt': ['p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2'], - }, schema=read_arrow_schema(Schema.from_pyarrow_schema(cls.pk_pa_schema).fields)) + }, schema=cls.pk_pa_schema) @classmethod def tearDownClass(cls): diff --git a/paimon-python/pypaimon/tests/table_commit_test.py b/paimon-python/pypaimon/tests/table_commit_test.py index 74758eda17..d606a94331 100644 --- a/paimon-python/pypaimon/tests/table_commit_test.py +++ b/paimon-python/pypaimon/tests/table_commit_test.py @@ -96,7 +96,6 @@ class TestTableCommit(unittest.TestCase): def test_empty_append_snapshot_is_opt_in_and_can_be_tagged(self): import pyarrow as pa import pypaimon.multimodal as pmm - from pypaimon.schema.arrow_schema import read_arrow_schema with TemporaryDirectory(prefix="paimon-empty-commit-") as warehouse: connection = pmm.connect(options={"warehouse": warehouse}) @@ -127,7 +126,7 @@ class TestTableCommit(unittest.TestCase): table.raw_table.create_tag("empty") tagged = table.scan(tag_name="empty").to_arrow() self.assertEqual(0, tagged.num_rows) - self.assertEqual(read_arrow_schema(table.raw_table.fields), tagged.schema) + self.assertEqual(schema, tagged.schema) table.add([{"feature": "state_imu_body"}]) table.add(empty) diff --git a/paimon-python/pypaimon/tests/table_upsert_by_key_test.py b/paimon-python/pypaimon/tests/table_upsert_by_key_test.py index 93181f6fd1..63ebe839e1 100644 --- a/paimon-python/pypaimon/tests/table_upsert_by_key_test.py +++ b/paimon-python/pypaimon/tests/table_upsert_by_key_test.py @@ -24,7 +24,6 @@ import pyarrow as pa import pyarrow.parquet as pq import pytest -from pypaimon.schema.arrow_schema import read_arrow_schema from pypaimon.read.table_read import TableRead from pypaimon.table.special_fields import SpecialFields from pypaimon.write.table_update_by_row_id import _RowIdUpdateFileWriter @@ -1271,7 +1270,7 @@ class _TableUpsertByKeyTestBase(DataEvolutionTestBase): schema.field('score'), pa.array([0, 1, 99, 3], type=pa.int32()), ) - self.assertTrue(self._read_all(table).equals(expected.cast(read_arrow_schema(table.fields)))) + self.assertTrue(self._read_all(table).equals(expected)) files = [file for message in messages for file in message.new_files] self.assertEqual(len(files), 1) self.assertFalse(pq.read_schema(files[0].file_path).field('score').nullable) diff --git a/paimon-python/pypaimon/tests/write/table_write_test.py b/paimon-python/pypaimon/tests/write/table_write_test.py index b9dd802869..5b48d2ef3b 100644 --- a/paimon-python/pypaimon/tests/write/table_write_test.py +++ b/paimon-python/pypaimon/tests/write/table_write_test.py @@ -25,7 +25,6 @@ from contextlib import contextmanager from unittest.mock import Mock, patch from pypaimon import CatalogFactory, Schema -from pypaimon.schema.arrow_schema import read_arrow_schema import pyarrow as pa import pytest from parameterized import parameterized @@ -103,8 +102,7 @@ class TableWriteTest(unittest.TestCase): commit.close() actual = self._read_sorted(table, [('id', 'ascending')]) self.assertEqual(actual.to_pylist(), expected) - expected_schema = read_arrow_schema(Schema.from_pyarrow_schema(arrow_schema(pa.string())).fields) - self.assertEqual(actual.schema.remove_metadata(), expected_schema) + self.assertEqual(actual.schema.remove_metadata(), arrow_schema(pa.string())) @classmethod def setUpClass(cls): @@ -230,7 +228,6 @@ class TableWriteTest(unittest.TestCase): def _mock_table_write(partitions, buckets): table_write = object.__new__(TableWrite) table_write.table = Mock(is_primary_key_table=False) - table_write.table_pyarrow_schema = pa.schema([('id', pa.int64()), ('payload', pa.binary())]) table_write._validate_pyarrow_schema = Mock() table_write.row_key_extractor = Mock() table_write.file_store_write = Mock() @@ -306,7 +303,6 @@ class TableWriteTest(unittest.TestCase): }) table_write = object.__new__(TableWrite) table_write.table = Mock(is_primary_key_table=False) - table_write.table_pyarrow_schema = pa.schema([('id', pa.int64()), ('payload', pa.binary())]) table_write._validate_pyarrow_schema = Mock() table_write.file_store_write = Mock() table_write.row_key_extractor = Mock() @@ -332,7 +328,6 @@ class TableWriteTest(unittest.TestCase): }) table_write = object.__new__(TableWrite) table_write.table = Mock(is_primary_key_table=False) - table_write.table_pyarrow_schema = pa.schema([('id', pa.int64()), ('payload', pa.binary())]) table_write._validate_pyarrow_schema = Mock() table_write.file_store_write = Mock() table_write.row_key_extractor = Mock() @@ -566,7 +561,7 @@ class TableWriteTest(unittest.TestCase): 'item_id': [1001, 1002], 'behavior': ['a', 'b'], 'dt': ['p1', 'p2'], - }, schema=read_arrow_schema(table.fields)) + }, schema=self.pk_pa_schema) sort_keys = [('user_id', 'ascending'), ('dt', 'ascending')] self.assertEqual( expected.sort_by(sort_keys), self._read_sorted(table, sort_keys)) @@ -596,7 +591,7 @@ class TableWriteTest(unittest.TestCase): 'item_id': [1001, 1002], 'behavior': ['a', 'b'], 'dt': ['p1', 'p2'], - }, schema=read_arrow_schema(table.fields)) + }, schema=self.pk_pa_schema) sort_keys = [('user_id', 'ascending'), ('dt', 'ascending')] self.assertEqual( expected.sort_by(sort_keys), self._read_sorted(table, sort_keys)) @@ -776,7 +771,7 @@ class TableWriteTest(unittest.TestCase): table_read = read_builder.new_read() splits = read_builder.new_scan().plan().splits() actual = table_read.to_arrow(splits).sort_by('user_id') - self.assertEqual(self.pk_expected.cast(read_arrow_schema(table.fields)), actual) + self.assertEqual(self.pk_expected, actual) def test_postpone_read_write(self): table = self._create_postpone_table( @@ -830,7 +825,7 @@ class TableWriteTest(unittest.TestCase): table_read = read_builder.new_read() splits = read_builder.new_scan().plan().splits() actual = table_read.to_arrow(splits) - self.assertEqual(expect.cast(read_arrow_schema(table.fields)), actual) + self.assertEqual(expect, actual) def test_postpone_file_store_write_validates_runtime_bucket_count(self): from pypaimon.write.file_store_write import ( @@ -1891,7 +1886,7 @@ class TableWriteTest(unittest.TestCase): actual = table_read.to_arrow(splits) sort_keys = [('user_id', 'ascending'), ('dt', 'ascending')] self.assertEqual( - self.pk_expected.cast(read_arrow_schema(table.fields)).sort_by(sort_keys), + self.pk_expected.sort_by(sort_keys), actual.sort_by(sort_keys), ) diff --git a/paimon-python/pypaimon/write/native_commit.py b/paimon-python/pypaimon/write/native_commit.py index 12548de66c..91716cc357 100644 --- a/paimon-python/pypaimon/write/native_commit.py +++ b/paimon-python/pypaimon/write/native_commit.py @@ -65,7 +65,7 @@ def create_native_commit(table, commit_user, overwrite_partition=None): return None if overwrite_partition is not None: return (native_table.new_batch_write_builder() - .with_commit_user(commit_user) + ._with_commit_user(commit_user) .with_overwrite(overwrite_partition).new_commit()) # Append commits use the stream committer with the Python writer's identity; # Python enforces each mode's lifecycle and empty-commit rules. diff --git a/paimon-python/pypaimon/write/native_merge_into.py b/paimon-python/pypaimon/write/native_merge_into.py index cd1e8c5d44..8652079f15 100644 --- a/paimon-python/pypaimon/write/native_merge_into.py +++ b/paimon-python/pypaimon/write/native_merge_into.py @@ -79,31 +79,25 @@ def create_native_merge_into(table, source, on, matched, not_matched, commit_use if source_type != target_type or not _supported_upsert_key_type(target_type): return None - from pypaimon_rust.datafusion import MergeAssignment, WhenMatched, WhenNotMatched - - def encode(clause, not_matched=False): - values = {} + def encode(clause): + values = [] for name, value in clause.spec.items(): if isinstance(value, SourceColumnRef): - values[name] = MergeAssignment.source_column(value.column) + values.append((name, 'source', value.column)) elif isinstance(value, TargetColumnRef): - values[name] = MergeAssignment.target_column(value.column) + values.append((name, 'target', value.column)) elif isinstance(value, LiteralValue): - values[name] = MergeAssignment.literal(value.value) + values.append((name, 'literal', value.value)) else: return None - condition = None if clause.condition is None else rewrite_condition(clause.condition) - if not_matched: - return WhenNotMatched(values, condition) - if clause.delete: - return WhenMatched.delete(condition) - return WhenMatched.update(values, condition) + condition = None if clause.condition is None else dict(sql=rewrite_condition(clause.condition)) + return dict(assignments=values, condition=condition, delete=clause.delete) encoded_matched = [encode(clause) for clause in matched] - encoded_not_matched = [encode(clause, not_matched=True) for clause in not_matched] + encoded_not_matched = [encode(clause) for clause in not_matched] if any(clause is None for clause in encoded_matched + encoded_not_matched): return None - builder = (native_table.new_batch_write_builder().with_commit_user(commit_user) + builder = (native_table.new_batch_write_builder()._with_commit_user(commit_user) if commit_identifier == BATCH_COMMIT_IDENTIFIER else native_table.new_stream_write_builder().with_commit_user(commit_user)) writer = builder.new_update() diff --git a/paimon-python/pypaimon/write/native_update.py b/paimon-python/pypaimon/write/native_update.py index 1d80af544c..3175d30226 100644 --- a/paimon-python/pypaimon/write/native_update.py +++ b/paimon-python/pypaimon/write/native_update.py @@ -59,7 +59,7 @@ def create_native_update(table, commit_user, columns): if native_table is None: return None writer = (native_table.new_batch_write_builder() - .with_commit_user(commit_user) + ._with_commit_user(commit_user) .new_update()) if columns is not None: writer.with_update_type(columns) @@ -77,7 +77,7 @@ def create_native_update_by_row_id(table, commit_user, commit_identifier): if native_table is None: return None if commit_identifier == BATCH_COMMIT_IDENTIFIER: - writer = (native_table.new_batch_write_builder().with_commit_user(commit_user) + writer = (native_table.new_batch_write_builder()._with_commit_user(commit_user) .new_update().new_update_by_row_id()) else: writer = (native_table.new_stream_write_builder().with_commit_user(commit_user) @@ -154,7 +154,7 @@ def create_native_upsert(table, commit_user, data, keys, columns): for name in data.column_names)): return None writer = (native_table.new_batch_write_builder() - .with_commit_user(commit_user) + ._with_commit_user(commit_user) .new_update() .with_update_type(columns)) return NativeTableUpsert(table, writer, keys, data) @@ -174,7 +174,7 @@ def create_native_predicate_update(table, commit_user, predicate, columns=None): # reading and callback execution belong to the core operation below. native_table.new_read_builder().with_filter(native_predicate) writer = (native_table.new_batch_write_builder() - .with_commit_user(commit_user).new_update()) + ._with_commit_user(commit_user).new_update()) return NativePredicateTableUpdate(table, writer, native_predicate) @@ -204,7 +204,7 @@ def create_native_delete(table, commit_user): if native_table is None: return None writer = (native_table.new_batch_write_builder() - .with_commit_user(commit_user) + ._with_commit_user(commit_user) .new_update()) return NativeBatchTableUpdate(table, writer) diff --git a/paimon-python/pypaimon/write/native_write.py b/paimon-python/pypaimon/write/native_write.py index bd86a1a39e..bdc7a98518 100644 --- a/paimon-python/pypaimon/write/native_write.py +++ b/paimon-python/pypaimon/write/native_write.py @@ -21,8 +21,7 @@ from importlib import import_module import pyarrow as pa from pypaimon.common.options.core_options import MergeEngine -from pypaimon.schema.arrow_schema import ( - arrow_schemas_compatible, normalize_arrow_strings, normalize_arrow_write_nullability) +from pypaimon.schema.arrow_schema import arrow_schemas_compatible, normalize_arrow_strings from pypaimon.schema.data_types import PyarrowFieldParser, is_blob_file_field from pypaimon.table.bucket_mode import BucketMode from pypaimon.write.native_commit import ( @@ -71,7 +70,7 @@ def create_native_write(table, commit_user, static_partition=None, stream=False, if native_table is None: return None if fixed_bucket: - builder = native_table.new_postpone_fixed_bucket_write_builder().with_commit_user(commit_user) + builder = native_table.new_postpone_fixed_bucket_write_builder()._with_commit_user(commit_user) if bucket_plan is not None: builder = builder.with_bucket_plan(bucket_plan.to_arrow(table)) if static_partition is not None: @@ -81,7 +80,7 @@ def create_native_write(table, commit_user, static_partition=None, stream=False, if stream: builder = native_table.new_stream_write_builder().with_commit_user(commit_user) else: - builder = native_table.new_batch_write_builder().with_commit_user(commit_user) + builder = native_table.new_batch_write_builder()._with_commit_user(commit_user) if static_partition is not None: builder = builder.with_overwrite(static_partition) if restore_snapshot_id is not None: @@ -214,9 +213,6 @@ class NativeTableWrite: self._native_writer.write_arrow(data, bucket) def _prepare_native_arrow_data(self, data): - data = normalize_arrow_strings(data) - target = self._table_schema if data.schema.names == self._table_schema.names else self._schema - data = normalize_arrow_write_nullability(data, target) if self._write_cols is not None and arrow_schemas_compatible( data.schema, self._table_schema, check_top_level_nullability=False, allow_binary_compatibility=True): @@ -230,7 +226,7 @@ class NativeTableWrite: "Input schema isn't consistent with table schema and write cols. " f"Input schema is: {data.schema} Table schema is: {self._schema} " f"Write cols is: {self._write_cols}") - return data + return normalize_arrow_strings(data) def write_pandas(self, dataframe): if self._python_writer is not None: diff --git a/paimon-python/pypaimon/write/table_update_by_row_id.py b/paimon-python/pypaimon/write/table_update_by_row_id.py index acfda44911..307e4e9cde 100644 --- a/paimon-python/pypaimon/write/table_update_by_row_id.py +++ b/paimon-python/pypaimon/write/table_update_by_row_id.py @@ -28,7 +28,6 @@ from pypaimon.manifest.schema.data_file_meta import DataFileMeta from pypaimon.manifest.schema.simple_stats import SimpleStats from pypaimon.read.split import DataSplit from pypaimon.read.table_read import TableRead -from pypaimon.schema.arrow_schema import normalize_arrow_write_nullability from pypaimon.schema.data_types import ( DataField, PyarrowFieldParser, @@ -539,8 +538,7 @@ class TableUpdateByRowId: def _write_group_streaming(self, partition, first_row_id, data, column_names): writer = _RowIdUpdateFileWriter( self.table, tuple(partition.values), column_names) - merged_batches = self._merged_batches(first_row_id, data, column_names) - batches = (self._normalize_write_data(batch) for batch in merged_batches) + batches = self._merged_batches(first_row_id, data, column_names) try: files = writer.write_batches(batches) self._assign_update_file_metadata(files, first_row_id, column_names, {}) @@ -553,10 +551,7 @@ class TableUpdateByRowId: raise finally: batches.close() - try: - merged_batches.close() - finally: - writer.close() + writer.close() def _merge_update_with_original( self, @@ -666,29 +661,6 @@ class TableUpdateByRowId: return merged_table, blob_columns - def _normalize_write_data(self, data): - write_schema = PyarrowFieldParser.from_paimon_schema( - [self.table.field_dict[name] for name in data.schema.names]) - # Validate visible children against the declared write constraints. - # Keep the input nested types for Parquet: hidden NULL children under - # a NULL parent are legal and still need nullable transport fields. - normalize_arrow_write_nullability(data, write_schema) - for field, column in zip(write_schema, data.columns): - self._check_write_not_null(field.name, column.null_count > 0) - fields = [pa.field(actual.name, actual.type, nullable=expected.nullable, - metadata=expected.metadata) - for actual, expected in zip(data.schema, write_schema)] - schema = pa.schema(fields, metadata=write_schema.metadata) - if data.schema.equals(schema, check_metadata=True): - return data - if isinstance(data, pa.RecordBatch): - return pa.RecordBatch.from_arrays(data.columns, schema=schema) - return pa.Table.from_arrays(data.columns, schema=schema) - - def _check_write_not_null(self, column_name, has_null): - if not self.table.field_dict[column_name].type.nullable and has_null: - raise ValueError('Cannot write null to non-null column(%s)' % column_name) - @classmethod def _merge_chunked_column( cls, @@ -952,7 +924,6 @@ class TableUpdateByRowId: success = False try: if merged_data is not None: - merged_data = self._normalize_write_data(merged_data) file_store_write = FileStoreWrite(self.table, self.commit_user) file_store_write.disable_rolling() file_store_write.write_cols = list(merged_data.column_names) diff --git a/paimon-python/pypaimon/write/table_write.py b/paimon-python/pypaimon/write/table_write.py index 17668095f6..04e7b4df01 100644 --- a/paimon-python/pypaimon/write/table_write.py +++ b/paimon-python/pypaimon/write/table_write.py @@ -20,8 +20,7 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional import pyarrow as pa from pypaimon.common.options.core_options import ChangelogProducer -from pypaimon.schema.arrow_schema import ( - arrow_schemas_compatible, normalize_arrow_strings, normalize_arrow_write_nullability) +from pypaimon.schema.arrow_schema import arrow_schemas_compatible, normalize_arrow_strings from pypaimon.schema.data_types import PyarrowFieldParser from pypaimon.snapshot.snapshot import BATCH_COMMIT_IDENTIFIER from pypaimon.table.row.blob import BlobConsumer @@ -73,7 +72,7 @@ class TableWrite: def write_arrow(self, data, bucket: Optional[int] = None): """Write Arrow data, optionally to a bucket assigned upstream.""" - data = self._prepare_arrow_schema(data) + self._validate_pyarrow_schema(data.schema) if isinstance(data, pa.RecordBatch): return self.write_arrow_batch(data, bucket) for batch in data.to_batches(): @@ -309,7 +308,8 @@ class TableWrite: release() def _prepare_arrow_data(self, data): - data = self._prepare_arrow_schema(data) + self._validate_pyarrow_schema(data.schema) + data = normalize_arrow_strings(data) # Schema-only writers can normalize input without table options. table = getattr(self, 'table', None) if table is None: @@ -317,33 +317,6 @@ class TableWrite: from pypaimon.write.row_kind import filter_write_batch return filter_write_batch(table, data) - def _prepare_arrow_schema(self, data): - data = normalize_arrow_strings(data) - target = self.table_pyarrow_schema - if data.schema.names != target.names and self.file_store_write.write_cols is not None: - target = self._write_cols_pyarrow_schema(self.file_store_write.write_cols) - validated = normalize_arrow_write_nullability(data, target) - self._validate_pyarrow_schema(validated.schema) - # Validate visible children, but retain transport nullability for Parquet: - # hidden NULL children under NULL parents are not constraint violations. - return self._normalize_arrow_write_schema(data) - - def _normalize_arrow_write_schema(self, data): - # Compatible input batches may differ in top-level nullability or - # metadata. Buffered writes and row-to-Arrow conversion must use the - # same declared fields, while keeping normalized Arrow array types. - fields = [] - for field in data.schema: - declared = self.table_pyarrow_schema.field(field.name) - fields.append(pa.field(field.name, field.type, nullable=declared.nullable, - metadata=declared.metadata)) - schema = pa.schema(fields, metadata=self.table_pyarrow_schema.metadata) - if data.schema.equals(schema, check_metadata=True): - return data - if isinstance(data, pa.RecordBatch): - return pa.RecordBatch.from_arrays(data.columns, schema=schema) - return pa.Table.from_arrays(data.columns, schema=schema) - def _validate_pyarrow_schema(self, data_schema: pa.Schema): if self._is_compatible_pyarrow_schema(data_schema, self.table_pyarrow_schema): return diff --git a/paimon-python/pyproject.toml b/paimon-python/pyproject.toml index f8e97020f1..b80759f2e7 100644 --- a/paimon-python/pyproject.toml +++ b/paimon-python/pyproject.toml @@ -163,7 +163,7 @@ datafusion = [ ] sql = [ "pypaimon[datafusion]; python_version >= '3.10'", - "pypaimon-rust>=0.5.0; python_version >= '3.10'", + "pypaimon-rust>=0.3.0,<0.5.0; python_version >= '3.10'", ] hdfs = [ "hdfs-native>=0.13,<1; python_version >= '3.10' and platform_system != 'Windows'",
