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 c4cdcdd1e6 [python] Use filesystem snapshots for REST external tables 
(#11136)
c4cdcdd1e6 is described below

commit c4cdcdd1e69280c10ae63e086eee9bb1f2c08dbe
Author: zhoulii <[email protected]>
AuthorDate: Fri Nov 13 18:52:06 2026 +0800

    [python] Use filesystem snapshots for REST external tables (#11136)
---
 .../pypaimon/catalog/catalog_environment.py        |  14 +-
 .../pypaimon/catalog/rest/rest_catalog.py          |   5 +-
 paimon-python/pypaimon/execution/native/table.py   |  15 +-
 .../execution/native/write/native_commit.py        |   2 +-
 .../execution/python/read/blob_view_lookup.py      |  17 +-
 .../read/reader/blob_descriptor_convert_reader.py  |  13 +-
 paimon-python/pypaimon/multimodal/lance_export.py  |   2 +-
 paimon-python/pypaimon/tests/blob_test.py          |   3 +
 .../pypaimon/tests/catalog_environment_test.py     | 115 +++++++++++-
 paimon-python/pypaimon/tests/native_read_test.py   |  38 ++++
 .../tests/rest/rest_external_table_test.py         | 193 +++++++++++++++++++++
 11 files changed, 399 insertions(+), 18 deletions(-)

diff --git a/paimon-python/pypaimon/catalog/catalog_environment.py 
b/paimon-python/pypaimon/catalog/catalog_environment.py
index 039cc41e98..b24732ee1b 100644
--- a/paimon-python/pypaimon/catalog/catalog_environment.py
+++ b/paimon-python/pypaimon/catalog/catalog_environment.py
@@ -40,13 +40,15 @@ class CatalogEnvironment:
             uuid: Optional[str] = None,
             catalog_loader: Optional[CatalogLoader] = None,
             supports_version_management: bool = False,
-            rest_table_response: Optional[str] = None
+            rest_table_response: Optional[str] = None,
+            catalog_context: Optional[CatalogContext] = None
     ):
         self.identifier = identifier
         self.uuid = uuid
         self.catalog_loader = catalog_loader
         self.supports_version_management = supports_version_management
         self.rest_table_response = rest_table_response
+        self._catalog_context = catalog_context
 
     def snapshot_commit(self, snapshot_manager) -> Optional[SnapshotCommit]:
         """
@@ -96,6 +98,8 @@ class CatalogEnvironment:
         return None
 
     def catalog_context(self) -> Optional[CatalogContext]:
+        if self._catalog_context is not None:
+            return self._catalog_context
         if self.catalog_loader is None:
             return None
         context = getattr(self.catalog_loader, "context", None)
@@ -111,8 +115,13 @@ class CatalogEnvironment:
 
         from pypaimon.catalog.rest.rest_catalog_loader import RESTCatalogLoader
 
+        # External REST tables intentionally have no snapshot loader, and a 
directly
+        # constructed RESTCatalog may omit `metastore=rest` from 
CatalogContext.
+        # For those cases, the resolved GetTable response is the remaining
+        # provenance proving that dependency reads must still use the REST 
transport.
         rest_catalog = (
             isinstance(self.catalog_loader, RESTCatalogLoader)
+            or self.rest_table_response is not None
             or context.options.get(CatalogOptions.METASTORE) == "rest"
         )
         if not rest_catalog:
@@ -143,7 +152,8 @@ class CatalogEnvironment:
             uuid=self.uuid if identifier == self.identifier else None,
             catalog_loader=self.catalog_loader,
             supports_version_management=self.supports_version_management,
-            rest_table_response=getattr(self, 'rest_table_response', None)
+            rest_table_response=getattr(self, 'rest_table_response', None),
+            catalog_context=self._catalog_context
         )
 
     @staticmethod
diff --git a/paimon-python/pypaimon/catalog/rest/rest_catalog.py 
b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
index 990828db43..6caf66564a 100644
--- a/paimon-python/pypaimon/catalog/rest/rest_catalog.py
+++ b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
@@ -875,9 +875,10 @@ class RESTCatalog(Catalog):
         catalog_env = CatalogEnvironment(
             identifier=identifier,
             uuid=metadata.uuid,
-            catalog_loader=self.catalog_loader(),
+            catalog_loader=None if metadata.is_external else 
self.catalog_loader(),
             supports_version_management=True,
-            rest_table_response=getattr(metadata, 'rest_table_response', None)
+            rest_table_response=getattr(metadata, 'rest_table_response', None),
+            catalog_context=self.context
         )
         # Use the path from server response directly (do not trim scheme)
         table_path = schema.options.get(CoreOptions.PATH.key())
diff --git a/paimon-python/pypaimon/execution/native/table.py 
b/paimon-python/pypaimon/execution/native/table.py
index ba3831bf7d..f218bb9b7b 100644
--- a/paimon-python/pypaimon/execution/native/table.py
+++ b/paimon-python/pypaimon/execution/native/table.py
@@ -28,13 +28,20 @@ from pypaimon.common.options.options_utils import 
OptionsUtils
 
 
 def _native_blob_view_supported(table, read_names) -> bool:
-    """Resolve Blob views natively only with the REST catalog environment."""
+    """Resolve Blob views natively only when Python itself can resolve them."""
     if (not (table.options.blob_view_fields() & set(read_names))
             or not table.options.blob_view_resolve_enabled()):
         return True
-    loader = getattr(getattr(table, 'catalog_environment', None), 
'catalog_loader', None)
-    # Python also leaves view structs unresolved without a loader.
-    return loader is None or _catalog_metastore(loader) == 'rest'
+    environment = getattr(table, 'catalog_environment', None)
+    loader = getattr(environment, 'catalog_loader', None)
+    if loader is not None:
+        return _catalog_metastore(loader) == 'rest'
+    # A catalogless resolved table has no context to resolve views, so native 
and
+    # Python both retain the view struct values. If a catalog context is 
retained
+    # without a loader, Python can resolve through it but Rust 
from_resolved_schema
+    # cannot, so fall back.
+    catalog_context = getattr(environment, 'catalog_context', None)
+    return catalog_context() is None if callable(catalog_context) else True
 
 
 def _partition_fields(table):
diff --git a/paimon-python/pypaimon/execution/native/write/native_commit.py 
b/paimon-python/pypaimon/execution/native/write/native_commit.py
index 6bf4910d87..1ba1a67bc0 100644
--- a/paimon-python/pypaimon/execution/native/write/native_commit.py
+++ b/paimon-python/pypaimon/execution/native/write/native_commit.py
@@ -165,7 +165,7 @@ def create_native_write_table(table):
         table.options.data_evolution_row_sidecar_enabled())
     options['query-auth.enabled'] = 
_option_value_to_string(table.options.query_auth_enabled)
     schema_json = JSON.to_json(table.table_schema.copy(new_options=options))
-    if environment.supports_version_management:
+    if environment.catalog_loader is not None and 
environment.supports_version_management:
         if not _rest_catalog_supported(table):
             return None
         return _native_rest_table(table, schema_json)
diff --git a/paimon-python/pypaimon/execution/python/read/blob_view_lookup.py 
b/paimon-python/pypaimon/execution/python/read/blob_view_lookup.py
index 989816803a..1e7863d710 100644
--- a/paimon-python/pypaimon/execution/python/read/blob_view_lookup.py
+++ b/paimon-python/pypaimon/execution/python/read/blob_view_lookup.py
@@ -20,6 +20,7 @@ from typing import Dict, List, Set, Tuple
 
 from pypaimon.common.identifier import Identifier
 from pypaimon.common.uri_reader import UriReader, UriReaderFactory
+from pypaimon.common.options.config import CatalogOptions
 from pypaimon.common.options.core_options import CoreOptions
 from pypaimon.table.row.blob import Blob, BlobDescriptor, BlobViewStruct
 from pypaimon.table.special_fields import SpecialFields
@@ -310,11 +311,25 @@ class BlobViewLookup:
     def _load_table(self, identifier: Identifier):
         catalog_environment = self._table.catalog_environment
         catalog_loader = catalog_environment.catalog_loader
+        catalog_context = catalog_environment.catalog_context()
         dependency_context = catalog_environment.dependency_read_context()
-        if dependency_context is catalog_environment.catalog_context():
+        if catalog_loader is not None and dependency_context is 
catalog_context:
             catalog = catalog_loader.load()
         else:
             from pypaimon.catalog.catalog_factory import CatalogFactory
+            # A nested external REST table may already carry Read-Via, which 
makes
+            # dependency_read_context() return the original context unchanged. 
Such
+            # a table has no catalog loader, and the REST response is the 
provenance
+            # proving dependency reads must still use REST. Ensure its context 
selects
+            # the REST catalog before reconstructing the dependency catalog.
+            if (
+                    catalog_loader is None
+                    and dependency_context is not None
+                    and catalog_environment.rest_table_response is not None):
+                dependency_options = dependency_context.options.copy()
+                if not dependency_options.contains(CatalogOptions.METASTORE):
+                    dependency_options.set(CatalogOptions.METASTORE, "rest")
+                dependency_context = 
dependency_context.with_options(dependency_options)
             catalog = CatalogFactory.create_from_context(
                 dependency_context, config_required=False)
         return catalog.get_table(identifier)
diff --git 
a/paimon-python/pypaimon/execution/python/read/reader/blob_descriptor_convert_reader.py
 
b/paimon-python/pypaimon/execution/python/read/reader/blob_descriptor_convert_reader.py
index 188119abd3..0948dc9cb6 100644
--- 
a/paimon-python/pypaimon/execution/python/read/reader/blob_descriptor_convert_reader.py
+++ 
b/paimon-python/pypaimon/execution/python/read/reader/blob_descriptor_convert_reader.py
@@ -86,9 +86,12 @@ class BlobInlineConvertReader(RecordBatchReader):
         self._adopt_metadata(inner)
         # Preserve original BlobViewStruct bytes when resolve disabled: skip 
both
         # view resolution (Stage 1) and descriptor-to-data resolution (Stage 
2).
-        resolve_enabled = CoreOptions.blob_view_resolve_enabled(
-            table.options) and self._table.catalog_environment.catalog_loader 
is not None
-        self._view_fields = CoreOptions.blob_view_fields(table.options) if 
resolve_enabled else set()
+        view_fields = CoreOptions.blob_view_fields(table.options)
+        resolve_enabled = (
+            CoreOptions.blob_view_resolve_enabled(table.options)
+            and (not view_fields
+                 or self._table.catalog_environment.catalog_context() is not 
None))
+        self._view_fields = view_fields if resolve_enabled else set()
         self._descriptor_fields = 
CoreOptions.blob_descriptor_fields(table.options)
         self._blob_as_descriptor = 
CoreOptions.blob_as_descriptor(table.options)
         if not self._blob_as_descriptor:
@@ -99,7 +102,9 @@ class BlobInlineConvertReader(RecordBatchReader):
         self._blob_view_lookup = None
 
     def read_arrow_batch(self) -> Optional[RecordBatch]:
-        # Align with Java: only enter blob view resolution when catalog_loader 
is available.
+        # Align with Java: only enter blob view resolution when a catalog 
context
+        # is available. External REST tables have no catalog loader but retain 
their
+        # catalog context for dependency reads.
         if self._view_fields and not self._prescan_done:
             self._prescan_view_structs()
 
diff --git a/paimon-python/pypaimon/multimodal/lance_export.py 
b/paimon-python/pypaimon/multimodal/lance_export.py
index a4eb931790..86985e565b 100644
--- a/paimon-python/pypaimon/multimodal/lance_export.py
+++ b/paimon-python/pypaimon/multimodal/lance_export.py
@@ -159,7 +159,7 @@ def _blob_reference_columns(table, fields, splits, 
materialized):
     video_fields = table.options.video_frame_fields()
     unresolved_views = (table.options.blob_view_fields()
                         if (not table.options.blob_view_resolve_enabled()
-                            or table.catalog_environment.catalog_loader is 
None) else set())
+                            or table.catalog_environment.catalog_context() is 
None) else set())
     # Plans normally share one captured policy. Compare provenance if a
     # planner returns multiple policies rather than guessing from masked bytes.
     policies = {id(getattr(split, "auth_result", None)): getattr(split, 
"auth_result", None) for split in splits}
diff --git a/paimon-python/pypaimon/tests/blob_test.py 
b/paimon-python/pypaimon/tests/blob_test.py
index ed840c256f..76761ad5e5 100644
--- a/paimon-python/pypaimon/tests/blob_test.py
+++ b/paimon-python/pypaimon/tests/blob_test.py
@@ -2785,6 +2785,9 @@ class BlobTest(unittest.TestCase):
         class _CatalogEnvironment:
             catalog_loader = _CatalogLoader()
 
+            def catalog_context(self):
+                return self.catalog_loader
+
         class _Table:
             options = CoreOptions(Options({
                 "blob-as-descriptor": "true",
diff --git a/paimon-python/pypaimon/tests/catalog_environment_test.py 
b/paimon-python/pypaimon/tests/catalog_environment_test.py
index c295892929..1dae4686f0 100644
--- a/paimon-python/pypaimon/tests/catalog_environment_test.py
+++ b/paimon-python/pypaimon/tests/catalog_environment_test.py
@@ -160,15 +160,35 @@ class CatalogEnvironmentTest(unittest.TestCase):
         self.assertFalse(context.options.contains_key(self._READ_VIA_OPTION))
 
     def test_dependency_read_context_for_external_rest_table(self):
+        # Direct RESTCatalog construction is allowed without `metastore=rest` 
in
+        # CatalogContext; URI and warehouse are the options RESTCatalog itself 
requires.
         context = CatalogContext.create_from_options(Options({
-            CatalogOptions.METASTORE.key(): "rest",
+            CatalogOptions.URI.key(): "http://127.0.0.1:1";,
+            CatalogOptions.WAREHOUSE.key(): "warehouse",
         }))
         environment = CatalogEnvironment(
             identifier=Identifier.create("db", "external"),
-            catalog_loader=FileSystemCatalogLoader(context),
+            catalog_context=context,
+            rest_table_response="{}",
         )
 
-        self.assertIsNot(environment.dependency_read_context(), context)
+        copied = environment.copy(environment.identifier)
+        self.assertIsNone(copied.catalog_loader)
+        self.assertIs(copied.catalog_context(), context)
+        self.assertIs(copied.blob_index_cache(), context.blob_index_cache)
+        dependency_context = copied.dependency_read_context()
+        self.assertIsNot(dependency_context, context)
+        self.assertIs(dependency_context.blob_index_cache, 
context.blob_index_cache)
+        
self.assertEqual(dependency_context.options.get(CatalogOptions.METASTORE), 
"rest")
+        self.assertFalse(context.options.contains(CatalogOptions.METASTORE))
+        self.assertEqual(
+            context.options.get(CatalogOptions.METASTORE), "filesystem")
+        self.assertFalse(context.options.contains_key(self._READ_VIA_OPTION))
+        self.assertEqual(
+            JSON.from_json(RESTUtil.decode_string(
+                dependency_context.options.to_map()[self._READ_VIA_OPTION]), 
Identifier),
+            environment.identifier,
+        )
 
     def test_filesystem_catalog_loader_preserves_context_cache(self):
         context = CatalogContext.create_from_options(Options({
@@ -263,6 +283,95 @@ class CatalogEnvironmentTest(unittest.TestCase):
         dependency_catalog.get_table.assert_called_once_with(target)
         self.assertIs(result, dependency_table)
 
+    def test_blob_view_lookup_reconstructs_nested_external_rest_catalog(self):
+        target = Identifier.create("db", "target")
+        outermost = Identifier.create("db", "outermost")
+        read_via = RESTUtil.encode_string(
+            JSON.to_json(outermost, separators=(",", ":")))
+        context = CatalogContext.create_from_options(Options({
+            CatalogOptions.URI.key(): "http://127.0.0.1:1";,
+            CatalogOptions.WAREHOUSE.key(): "warehouse",
+            self._READ_VIA_OPTION: read_via,
+        }))
+        environment = CatalogEnvironment(
+            identifier=Identifier.create("db", "intermediate"),
+            catalog_context=context,
+            rest_table_response="{}",
+        )
+        table = SimpleNamespace(catalog_environment=environment)
+        dependency_catalog = mock.MagicMock()
+        dependency_table = mock.sentinel.dependency_table
+        dependency_catalog.get_table.return_value = dependency_table
+
+        with mock.patch.object(
+                CatalogFactory,
+                "create_from_context",
+                return_value=dependency_catalog) as create_catalog:
+            result = BlobViewLookup(table)._load_table(target)
+
+        dependency_context = create_catalog.call_args.args[0]
+        create_catalog.assert_called_once_with(
+            dependency_context, config_required=False)
+        self.assertEqual(
+            dependency_context.options.get(CatalogOptions.METASTORE), "rest")
+        self.assertEqual(
+            dependency_context.options.to_map()[self._READ_VIA_OPTION], 
read_via)
+        dependency_catalog.get_table.assert_called_once_with(target)
+        self.assertIs(result, dependency_table)
+
+    def test_blob_view_lookup_does_not_default_unproven_context_to_rest(self):
+        target = Identifier.create("db", "target")
+        context = CatalogContext.create_from_options(Options({
+            CatalogOptions.WAREHOUSE.key(): "warehouse",
+        }))
+        environment = CatalogEnvironment(
+            identifier=Identifier.create("db", "table"),
+            catalog_context=context,
+        )
+        table = SimpleNamespace(catalog_environment=environment)
+        dependency_catalog = mock.MagicMock()
+        dependency_table = mock.sentinel.dependency_table
+        dependency_catalog.get_table.return_value = dependency_table
+
+        with mock.patch.object(
+                CatalogFactory,
+                "create_from_context",
+                return_value=dependency_catalog) as create_catalog:
+            result = BlobViewLookup(table)._load_table(target)
+
+        dependency_context = create_catalog.call_args.args[0]
+        create_catalog.assert_called_once_with(
+            dependency_context, config_required=False)
+        self.assertIs(dependency_context, context)
+        
self.assertEqual(dependency_context.options.get(CatalogOptions.METASTORE), 
"filesystem")
+        dependency_catalog.get_table.assert_called_once_with(target)
+        self.assertIs(result, dependency_table)
+
+    def test_blob_inline_reader_resolves_views_with_external_context(self):
+        from pypaimon.common.options.core_options import CoreOptions
+        from 
pypaimon.execution.python.read.reader.blob_descriptor_convert_reader import (
+            BlobInlineConvertReader)
+        from pypaimon.read.reader.iface.record_batch_reader import 
EmptyRecordBatchReader
+
+        class ExternalEnvironment:
+            catalog_loader = None
+
+            def catalog_context(self):
+                return mock.sentinel.catalog_context
+
+        table = SimpleNamespace(
+            options=CoreOptions(Options({
+                "blob-view-field": "picture",
+                "blob-as-descriptor": "true",
+            })),
+            catalog_environment=ExternalEnvironment(),
+        )
+
+        reader = BlobInlineConvertReader(EmptyRecordBatchReader(), table)
+
+        self.assertEqual(reader._view_fields, {"picture"})
+        reader.close()
+
     def test_blob_view_lookup_preserves_custom_rest_catalog(self):
         target = Identifier.create("db", "target")
         dependency_table = mock.sentinel.dependency_table
diff --git a/paimon-python/pypaimon/tests/native_read_test.py 
b/paimon-python/pypaimon/tests/native_read_test.py
index 794a69e1e7..08e887b870 100644
--- a/paimon-python/pypaimon/tests/native_read_test.py
+++ b/paimon-python/pypaimon/tests/native_read_test.py
@@ -855,6 +855,44 @@ def 
test_native_read_blob_view_keeps_filesystem_fallback(limit):
     native.assert_not_called()
 
 
+def test_native_blob_view_support_keeps_catalogless_tables_native():
+    from pypaimon.catalog.catalog_environment import CatalogEnvironment
+    from pypaimon.execution.native.table import _native_blob_view_supported
+    options = Mock()
+    options.blob_view_fields.return_value = {'payload'}
+    options.blob_view_resolve_enabled.return_value = True
+    table = Mock(
+        options=options,
+        catalog_environment=CatalogEnvironment.empty())
+    assert _native_blob_view_supported(table, ['payload'])
+
+
+def test_native_read_blob_view_falls_back_without_rest_loader():
+    from pypaimon.catalog.catalog_context import CatalogContext
+    from pypaimon.catalog.catalog_environment import CatalogEnvironment
+    from pypaimon.common.identifier import Identifier
+    from pypaimon.common.options import Options
+    read = _blob_table_read()
+    read.table.catalog_environment = CatalogEnvironment(
+        identifier=Identifier.create('default', 'view'),
+        catalog_context=CatalogContext.create_from_options(Options({
+            'metastore': 'rest',
+        })),
+        rest_table_response='{}')
+    read.table.options.blob_view_fields.return_value = {'payload'}
+    read.table.options.blob_view_resolve_enabled.return_value = True
+    split = _Split('payload.parquet')
+    split._native_split = object()
+    split.merged_row_count = Mock(return_value=2)
+
+    with patch(
+            'pypaimon.execution.native.read.table_read.native_read') as native:
+        assert NativeTableRead(read).read_batches(
+            [split], pa.schema([('payload', pa.large_binary())])) is None
+
+    native.assert_not_called()
+
+
 def test_native_read_pruning_descriptor_limit_allows_non_blob_predicate():
     read = _blob_table_read(limit=1)
     read.table.options.data_evolution_enabled.return_value = True
diff --git a/paimon-python/pypaimon/tests/rest/rest_external_table_test.py 
b/paimon-python/pypaimon/tests/rest/rest_external_table_test.py
new file mode 100644
index 0000000000..2146122ea0
--- /dev/null
+++ b/paimon-python/pypaimon/tests/rest/rest_external_table_test.py
@@ -0,0 +1,193 @@
+# 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.
+
+import json
+from contextlib import ExitStack
+from types import ModuleType
+from unittest.mock import Mock, patch
+
+import pyarrow as pa
+import pytest
+
+from pypaimon import Schema
+from pypaimon.api.api_response import ConfigResponse
+from pypaimon.api.auth import BearTokenAuthProvider
+from pypaimon.catalog.catalog_context import CatalogContext
+from pypaimon.catalog.rest.rest_catalog import RESTCatalog
+from pypaimon.catalog.rest.table_metadata import TableMetadata
+from pypaimon.common.file_io import FileIO
+from pypaimon.common.options import Options
+from pypaimon.execution.native.runtime import native_runtime_available
+from pypaimon.execution.native.write.native_commit import 
create_native_write_table
+from pypaimon.schema.schema_manager import SchemaManager
+from pypaimon.snapshot.catalog_snapshot_commit import CatalogSnapshotCommit
+from pypaimon.snapshot.renaming_snapshot_commit import RenamingSnapshotCommit
+from pypaimon.table.file_store_table import FileStoreTable
+from pypaimon.tests.rest.rest_server import RESTCatalogServer
+from pypaimon.write.write_dispatch import NativeTableWrite
+
+
+pytestmark = pytest.mark.python_commit
+_BACKENDS = [False, pytest.param(True, marks=[pytest.mark.native_plan, 
pytest.mark.skipif(
+    not native_runtime_available(), reason='pypaimon-rust not installed')])]
+
+
[email protected](params=['append', 'primary-key', 'data-evolution'])
+def external_table(tmp_path, request):
+    path = (tmp_path / 'warehouse' / 'default' / 'external').as_uri()
+    options = {'bucket': '-1', 'write-only': 'true',
+               'scan.native-plan.enabled': 'false', 'read.native.enabled': 
'false',
+               'write.native.enabled': 'false', 'commit.native.enabled': 
'false'}
+    primary_keys = []
+    if request.param == 'primary-key':
+        options['bucket'] = '1'
+        primary_keys = ['id']
+    elif request.param == 'data-evolution':
+        options.update({'data-evolution.enabled': 'true', 
'row-tracking.enabled': 'true'})
+    schema = Schema.from_pyarrow_schema(
+        pa.schema([('id', pa.int64())]), primary_keys=primary_keys, 
options=options)
+    SchemaManager(FileIO.get(path), path).create_table(schema)
+    filesystem = FileStoreTable.from_path(path)
+    metadata = TableMetadata(schema=filesystem.schema(), is_external=True, 
uuid='external-uuid')
+    server = RESTCatalogServer(str(tmp_path), 
BearTokenAuthProvider('test-token'),
+                               ConfigResponse(defaults={'prefix': 
'external-test'}), 'warehouse')
+    server.database_store['default'] = server.mock_database('default', {})
+    server.table_metadata_store['default.external'] = metadata
+    server.start()
+    try:
+        catalog = RESTCatalog(CatalogContext.create_from_options(Options({
+            'metastore': 'rest', 'uri': server.get_url(), 'warehouse': 
'warehouse',
+            'token.provider': 'bear', 'token': 'test-token', 
'data-token.enabled': 'true',
+            'opaque.file-io.option': 'preserved',
+        })))
+        yield catalog, filesystem, server
+    finally:
+        server.shutdown()
+
+
+def _write(table, values, native=False):
+    builder = table.new_batch_write_builder()
+    writer, commit = builder.new_write(), builder.new_commit()
+    try:
+        assert isinstance(writer, NativeTableWrite) == native
+        writer.write_arrow(pa.table({'id': pa.array(values, pa.int64())}))
+        commit.commit(writer.prepare_commit())
+    finally:
+        writer.close()
+        commit.close()
+
+
+def _rows(table, native=False):
+    builder = table.new_read_builder()
+    with ExitStack() as stack:
+        if native:
+            stack.enter_context(patch(
+                
'pypaimon.execution.python.read.table_scan.PythonTableScan.plan',
+                side_effect=AssertionError('Unexpected Python plan fallback')))
+            stack.enter_context(patch(
+                
'pypaimon.execution.python.read.table_read.PythonTableRead._create_split_read',
+                side_effect=AssertionError('Unexpected Python read fallback')))
+        plan = builder.new_scan().plan()
+        return sorted(row['id'] for row in 
builder.new_read().to_arrow(plan.splits()).to_pylist())
+
+
[email protected]('native', _BACKENDS, ids=['python', 'native'])
[email protected]('existing_snapshot', [False, True], ids=['empty', 
'populated'])
[email protected]('by_id', [False, True], ids=['by-name', 'by-id'])
+def test_external_snapshots_use_filesystem(external_table, native, 
existing_snapshot, by_id):
+    catalog, filesystem, server = external_table
+    expected = [0] if existing_snapshot else []
+    if expected:
+        _write(filesystem, expected)
+    with patch.object(server, '_table_snapshot_handle', 
side_effect=AssertionError(
+            'External snapshots must be read from the filesystem')) as 
load_snapshot, \
+            patch.object(server, '_table_commit_handle', 
side_effect=AssertionError(
+                'External snapshots must be committed to the filesystem')) as 
commit_snapshot:
+        table = (catalog.get_table_by_id('external-uuid') if by_id
+                 else catalog.get_table('default.external'))
+        environment = table.catalog_environment
+        assert environment.identifier == table.identifier
+        assert environment.uuid == 'external-uuid'
+        assert environment.catalog_loader is None
+        assert environment.supports_version_management
+        assert environment.catalog_context() is catalog.context
+        assert json.loads(environment.rest_table_response)['isExternal'] is 
True
+        assert table.file_io.properties.to_map()['opaque.file-io.option'] == 
'preserved'
+        assert isinstance(table.new_snapshot_commit(), RenamingSnapshotCommit)
+        assert _rows(table) == expected
+        latest = table.snapshot_manager().get_latest_snapshot()
+        assert (latest.id if latest else None) == (1 if existing_snapshot else 
None)
+        if native:
+            table = table.copy({'scan.native-plan.enabled': 'true', 
'read.native.enabled': 'true',
+                                'write.native.enabled': 'true', 
'commit.native.enabled': 'true'})
+
+        _write(filesystem, [1])
+        expected.append(1)
+        assert _rows(table, native) == expected
+
+        _write(table, [2], native)
+        expected.append(2)
+        assert _rows(filesystem) == expected
+
+        _write(filesystem, [3])
+        expected.append(3)
+        assert _rows(table, native) == expected
+        latest = table.snapshot_manager().get_latest_snapshot()
+        assert latest.id == 3 + int(existing_snapshot)
+        assert latest.uuid == 
filesystem.snapshot_manager().get_latest_snapshot().uuid
+        load_snapshot.assert_not_called()
+        commit_snapshot.assert_not_called()
+
+
+def test_internal_tables_keep_rest_snapshots(external_table):
+    catalog, filesystem, server = external_table
+    server.table_metadata_store['default.external'] = TableMetadata(
+        schema=filesystem.schema(), is_external=False, uuid='internal-uuid')
+    catalog.data_token_enabled = False
+    table = catalog.get_table('default.external')
+    assert 'path' in table.schema().options
+    assert table.catalog_environment.catalog_loader is not None
+    assert isinstance(table.new_snapshot_commit(), CatalogSnapshotCommit)
+
+    with patch.object(server, '_table_snapshot_handle', 
wraps=server._table_snapshot_handle) as load_snapshot, \
+            patch.object(server, '_table_commit_handle', 
wraps=server._table_commit_handle) as commit_snapshot:
+        _write(table, [1])
+        assert _rows(table) == [1]
+        assert table.snapshot_manager().get_latest_snapshot().id == 1
+        assert load_snapshot.call_count > 0
+        commit_snapshot.assert_called_once()
+
+    with patch.object(server, '_table_snapshot_handle', return_value=('{}', 
200)):
+        assert table.snapshot_manager().get_latest_snapshot() is None
+        assert _rows(table) == []
+    assert filesystem.snapshot_manager().get_latest_snapshot().id == 1
+
+
+def 
test_external_native_writer_uses_resolved_filesystem_schema(external_table):
+    catalog, filesystem, _ = external_table
+    table = catalog.get_table('default.external')
+    module = ModuleType('pypaimon_rust.datafusion')
+    module.Table = Mock()
+    with patch.dict('sys.modules', {'pypaimon_rust.datafusion': module}):
+        assert create_native_write_table(table) is 
module.Table.from_resolved_schema.return_value
+    args, kwargs = module.Table.from_resolved_schema.call_args
+    assert args[0] == table.table_path
+    assert json.loads(args[1])['fields'] == json.loads(
+        table.catalog_environment.rest_table_response)['schema']['fields']
+    assert kwargs['options']['opaque.file-io.option'] == 'preserved'
+    assert kwargs['database'] == 'default'
+    assert kwargs['table'] == 'external'

Reply via email to