You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@paimon.apache.org by lz...@apache.org on 2026/05/20 09:23:14 UTC
(paimon) branch master updated: [python] Add system tables (#7908)
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 817174a145 [python] Add system tables (#7908)
817174a145 is described below
commit 817174a1455d73c9467c39983e69235541047be6
Author: chaoyang <ch...@apache.org>
AuthorDate: Wed May 20 17:23:09 2026 +0800
[python] Add system tables (#7908)
Adds native PyPaimon access to eight core system tables, matching the
Java implementation column for column.
- New \`pypaimon.table.system\` package: \`SystemTable\` base +
\`SystemTableLoader\` registry + in-memory read pipeline
(\`SystemReadBuilder\` / \`SystemTableScan\` / \`SystemTableRead\`).
- \`FilesystemCatalog.get_table\` and \`RESTCatalog.get_table\` route
\`\$\`-suffixed identifiers to the loader; non-system requests are
unchanged.
- Tables implemented: \`snapshots\`, \`schemas\`, \`options\`,
\`manifests\`, \`files\`, \`partitions\`, \`tags\`, \`branches\`.
Schema, nullability and primary keys match Java's \`TABLE_TYPE\`.
- Manager helpers added where needed:
\`SnapshotManager.list_snapshots\`, \`SchemaManager.list_all\`,
\`BranchManager.branch_create_time\`.
- Predicate pushdown is not implemented yet: \`with_filter\` raises
\`NotImplementedError\` rather than dropping the filter silently. A few
columns are emitted as NULL/0 placeholders (documented).
- User docs: \`docs/content/pypaimon/system-tables.md\`.
---
docs/content/pypaimon/system-tables.md | 235 ++++++++++++++++
.../pypaimon/catalog/filesystem_catalog.py | 21 ++
.../pypaimon/catalog/rest/rest_catalog.py | 21 ++
paimon-python/pypaimon/schema/schema_manager.py | 14 +
.../pypaimon/snapshot/snapshot_manager.py | 33 +++
paimon-python/pypaimon/table/system/__init__.py | 20 ++
.../pypaimon/table/system/branches_table.py | 96 +++++++
paimon-python/pypaimon/table/system/files_table.py | 297 +++++++++++++++++++++
.../pypaimon/table/system/manifests_table.py | 115 ++++++++
.../pypaimon/table/system/options_table.py | 54 ++++
.../pypaimon/table/system/partitions_table.py | 162 +++++++++++
.../pypaimon/table/system/schemas_table.py | 97 +++++++
.../pypaimon/table/system/snapshots_table.py | 125 +++++++++
.../pypaimon/table/system/system_table.py | 157 +++++++++++
.../pypaimon/table/system/system_table_loader.py | 83 ++++++
.../pypaimon/table/system/system_table_read.py | 127 +++++++++
.../pypaimon/table/system/system_table_scan.py | 74 +++++
paimon-python/pypaimon/table/system/tags_table.py | 89 ++++++
paimon-python/pypaimon/tests/system/__init__.py | 16 ++
.../pypaimon/tests/system/branches_table_test.py | 121 +++++++++
.../pypaimon/tests/system/files_table_test.py | 153 +++++++++++
.../tests/system/list_tables_no_system_test.py | 69 +++++
.../tests/system/manager_extensions_test.py | 140 ++++++++++
.../pypaimon/tests/system/manifests_table_test.py | 112 ++++++++
.../pypaimon/tests/system/options_table_test.py | 88 ++++++
.../pypaimon/tests/system/partitions_table_test.py | 132 +++++++++
.../pypaimon/tests/system/schemas_table_test.py | 115 ++++++++
.../pypaimon/tests/system/snapshots_table_test.py | 165 ++++++++++++
.../tests/system/system_read_pipeline_test.py | 159 +++++++++++
.../system/system_table_catalog_dispatch_test.py | 194 ++++++++++++++
.../tests/system/system_table_loader_test.py | 84 ++++++
.../pypaimon/tests/system/system_table_test.py | 112 ++++++++
.../pypaimon/tests/system/tags_table_test.py | 132 +++++++++
33 files changed, 3612 insertions(+)
diff --git a/docs/content/pypaimon/system-tables.md b/docs/content/pypaimon/system-tables.md
new file mode 100644
index 0000000000..37c51c5f69
--- /dev/null
+++ b/docs/content/pypaimon/system-tables.md
@@ -0,0 +1,235 @@
+---
+title: "System Tables"
+weight: 6
+type: docs
+aliases:
+ - /pypaimon/system-tables.html
+---
+
+<!--
+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.
+-->
+
+# System Tables
+
+PyPaimon exposes `table$<name>` system tables through the existing
+catalog and read-builder APIs. The supported short names are:
+`snapshots`, `schemas`, `options`, `manifests`, `files`, `partitions`,
+`tags`, and `branches`. Global tables under the `sys` database
+(`sys.all_tables`, `sys.catalog_options`, ...) and the streaming
+`audit_log` / `binlog` family are not exposed yet.
+
+## Basic Usage
+
+Reuse a single read builder for both the scan and the read so that any
+projection or limit set on it is honoured by both sides:
+
+```python
+from pypaimon import CatalogFactory
+
+catalog = CatalogFactory.create({'warehouse': '/path/to/warehouse'})
+snapshots = catalog.get_table('default.my_table$snapshots')
+
+read_builder = snapshots.new_read_builder()
+splits = read_builder.new_scan().plan().splits()
+print(read_builder.new_read().to_pandas(splits))
+```
+
+`with_projection` and `with_limit` chain on the same builder:
+
+```python
+read_builder = (
+ snapshots.new_read_builder()
+ .with_projection(['snapshot_id', 'commit_user', 'commit_time'])
+ .with_limit(10)
+)
+splits = read_builder.new_scan().plan().splits()
+arrow_table = read_builder.new_read().to_arrow(splits)
+```
+
+The returned object exposes the regular `Table` surface, so the same
+read builder works with `to_pandas`, `to_arrow`, `to_iterator`,
+`to_record_batch_iterator`, and `to_duckdb`. Writes raise
+`NotImplementedError` — system tables are read-only.
+
+## Available Tables
+
+Each system table is listed below with its column layout (including
+nullability) and primary-key choice. Tables are listed in the order
+they appear in `SystemTableLoader`.
+
+### `$snapshots`
+
+One row per persisted snapshot.
+
+| Column | Type | Notes |
+|---------------------------|-----------------|--------------------------------|
+| `snapshot_id` | BIGINT NOT NULL | Primary key |
+| `schema_id` | BIGINT NOT NULL | |
+| `commit_user` | STRING NOT NULL | |
+| `commit_identifier` | BIGINT NOT NULL | |
+| `commit_kind` | STRING NOT NULL | `APPEND`, `COMPACT`, ... |
+| `commit_time` | TIMESTAMP(3) NOT NULL | |
+| `base_manifest_list` | STRING NOT NULL | |
+| `delta_manifest_list` | STRING NOT NULL | |
+| `changelog_manifest_list` | STRING | |
+| `total_record_count` | BIGINT | |
+| `delta_record_count` | BIGINT | |
+| `changelog_record_count` | BIGINT | |
+| `watermark` | BIGINT | |
+| `next_row_id` | BIGINT | |
+
+### `$schemas`
+
+Every committed schema version, with `fields` / `partition_keys` /
+`primary_keys` / `options` encoded as compact JSON strings.
+
+| Column | Type | Notes |
+|------------------|-----------------|--------------|
+| `schema_id` | BIGINT NOT NULL | Primary key |
+| `fields` | STRING NOT NULL | JSON |
+| `partition_keys` | STRING NOT NULL | JSON list |
+| `primary_keys` | STRING NOT NULL | JSON list |
+| `options` | STRING NOT NULL | JSON map |
+| `comment` | STRING | |
+| `update_time` | TIMESTAMP(3) NOT NULL | |
+
+### `$options`
+
+Two columns echoing the active table options.
+
+| Column | Type | Notes |
+|---------|-----------------|--------------|
+| `key` | STRING NOT NULL | Primary key |
+| `value` | STRING NOT NULL | |
+
+### `$manifests`
+
+Manifest list for the latest snapshot.
+
+| Column | Type | Notes |
+|-----------------------|-----------------|-------------------------------|
+| `file_name` | STRING NOT NULL | Primary key |
+| `file_size` | BIGINT NOT NULL | |
+| `num_added_files` | BIGINT NOT NULL | |
+| `num_deleted_files` | BIGINT NOT NULL | |
+| `schema_id` | BIGINT NOT NULL | |
+| `min_partition_stats` | STRING | Placeholder (see Limitations) |
+| `max_partition_stats` | STRING | Placeholder (see Limitations) |
+| `min_row_id` | BIGINT | |
+| `max_row_id` | BIGINT | |
+
+### `$files`
+
+One row per ADD entry surviving the latest snapshot. Stats columns are
+compact JSON dictionaries keyed by column name. The wire name
+`deleteRowCount` is intentionally camelCase.
+
+| Column | Type | Notes |
+|-------------------------|---------------------|-----------------------------|
+| `partition` | STRING | `pt=v/pt2=v2` |
+| `bucket` | INT NOT NULL | |
+| `file_path` | STRING NOT NULL | Primary key |
+| `file_format` | STRING NOT NULL | |
+| `schema_id` | BIGINT NOT NULL | |
+| `level` | INT NOT NULL | |
+| `record_count` | BIGINT NOT NULL | |
+| `file_size_in_bytes` | BIGINT NOT NULL | |
+| `min_key` | STRING | JSON list (PK tables only) |
+| `max_key` | STRING | JSON list (PK tables only) |
+| `null_value_counts` | STRING NOT NULL | JSON map |
+| `min_value_stats` | STRING NOT NULL | JSON map |
+| `max_value_stats` | STRING NOT NULL | JSON map |
+| `min_sequence_number` | BIGINT | |
+| `max_sequence_number` | BIGINT | |
+| `creation_time` | TIMESTAMP(3) | |
+| `deleteRowCount` | BIGINT | camelCase wire name |
+| `file_source` | STRING | |
+| `first_row_id` | BIGINT | |
+| `write_cols` | ARRAY<STRING> | |
+
+### `$partitions`
+
+Aggregated partition statistics for the latest snapshot.
+
+| Column | Type | Notes |
+|-----------------------|-----------------------|--------------------------------|
+| `partition` | STRING | `pt=v/pt2=v2`; primary key |
+| `record_count` | BIGINT NOT NULL | |
+| `file_size_in_bytes` | BIGINT NOT NULL | |
+| `file_count` | BIGINT NOT NULL | |
+| `last_update_time` | TIMESTAMP(3) | |
+| `created_at` | TIMESTAMP(3) | Filesystem path returns `NULL` |
+| `created_by` | STRING | Filesystem path returns `NULL` |
+| `updated_by` | STRING | Filesystem path returns `NULL` |
+| `options` | STRING | Filesystem path returns `NULL` |
+| `total_buckets` | INT NOT NULL | |
+| `done` | BOOLEAN NOT NULL | Filesystem path returns `False`|
+
+### `$tags`
+
+Snapshot metadata for every tag.
+
+| Column | Type | Notes |
+|-----------------|-----------------------|--------------------------------|
+| `tag_name` | STRING NOT NULL | Primary key |
+| `snapshot_id` | BIGINT NOT NULL | |
+| `schema_id` | BIGINT NOT NULL | |
+| `commit_time` | TIMESTAMP(3) NOT NULL | |
+| `record_count` | BIGINT | |
+| `create_time` | TIMESTAMP(3) | Currently emitted as `NULL` |
+| `time_retained` | STRING | Currently emitted as `NULL` |
+
+### `$branches`
+
+Every named branch with the branch directory's modification time.
+
+| Column | Type | Notes |
+|---------------|-----------------------|--------------|
+| `branch_name` | STRING NOT NULL | Primary key |
+| `create_time` | TIMESTAMP(3) NOT NULL | |
+
+## Limitations
+
+* **Predicate pushdown is not yet implemented.** Calling
+ `with_filter(...)` is accepted, but invoking `new_read()` later will
+ raise `NotImplementedError` rather than silently dropping the
+ predicate. Filter the resulting Arrow table / DataFrame on the
+ client side instead.
+* **`min_partition_stats` / `max_partition_stats` in `$manifests`**
+ are emitted as `NULL`. PyPaimon does not yet ship a helper that casts
+ a partition row to its string form.
+* **`tag.time_retained` and `tag.create_time` are `NULL`.** PyPaimon's
+ `Tag` dataclass does not yet carry these fields — matching
+ `FileSystemCatalog.get_tag`'s current behaviour.
+* **`branch.create_time` falls back to epoch 0** when the underlying
+ store cannot provide an mtime (some remote object stores via
+ `PyArrowFileIO`). Local filesystem catalogs always populate the
+ real time.
+* **`partitions.created_at / created_by / updated_by / options / done`**
+ are filled with placeholders for the filesystem path. REST-managed
+ catalogs that expose those fields will be wired in a follow-up.
+* **`list_tables` does not enumerate system tables.** System tables
+ remain accessible through `get_table('db.t$name')`.
+
+## Supported via Catalogs
+
+* `FilesystemCatalog` — fully supported.
+* `RESTCatalog` — fully supported; columns that depend on catalog
+ metadata (such as `$partitions.created_by`) are populated via the
+ REST API where the server exposes them.
diff --git a/paimon-python/pypaimon/catalog/filesystem_catalog.py b/paimon-python/pypaimon/catalog/filesystem_catalog.py
index 56fe394483..6be4f67d53 100644
--- a/paimon-python/pypaimon/catalog/filesystem_catalog.py
+++ b/paimon-python/pypaimon/catalog/filesystem_catalog.py
@@ -131,6 +131,11 @@ class FileSystemCatalog(Catalog):
def get_table(self, identifier: Union[str, Identifier]) -> Table:
if not isinstance(identifier, Identifier):
identifier = Identifier.from_string(identifier)
+ if identifier.is_system_table():
+ return self._load_system_table(identifier)
+ return self._load_data_table(identifier)
+
+ def _load_data_table(self, identifier: Identifier) -> FileStoreTable:
if self.catalog_options.contains(CoreOptions.SCAN_FALLBACK_BRANCH):
raise ValueError(f"Unsupported CoreOption {CoreOptions.SCAN_FALLBACK_BRANCH}")
table_path = self.get_table_path(identifier)
@@ -147,6 +152,22 @@ class FileSystemCatalog(Catalog):
return FileStoreTable(self.file_io, identifier, table_path, table_schema, catalog_environment)
+ def _load_system_table(self, identifier: Identifier) -> Table:
+ from pypaimon.table.system import system_table_loader
+
+ base_identifier = Identifier.create(
+ identifier.get_database_name(),
+ identifier.get_table_name(),
+ branch=identifier.get_branch_name(),
+ )
+ base_table = self._load_data_table(base_identifier)
+ sys_table = system_table_loader.load(
+ identifier.get_system_table_name(), base_table
+ )
+ if sys_table is None:
+ raise TableNotExistException(identifier)
+ return sys_table
+
def create_table(self, identifier: Union[str, Identifier], schema: 'Schema', ignore_if_exists: bool):
if schema.options and schema.options.get(CoreOptions.AUTO_CREATE.key()):
raise ValueError(f"The value of {CoreOptions.AUTO_CREATE.key()} property should be False.")
diff --git a/paimon-python/pypaimon/catalog/rest/rest_catalog.py b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
index a3d6a665ff..fe1fab1b63 100644
--- a/paimon-python/pypaimon/catalog/rest/rest_catalog.py
+++ b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
@@ -221,6 +221,11 @@ class RESTCatalog(Catalog):
def get_table(self, identifier: Union[str, Identifier]):
if not isinstance(identifier, Identifier):
identifier = Identifier.from_string(identifier)
+ if identifier.is_system_table():
+ return self._load_system_table(identifier)
+ return self._load_data_table(identifier)
+
+ def _load_data_table(self, identifier: Identifier):
return self.load_table(
identifier,
lambda path: self.file_io_for_data(path, identifier),
@@ -228,6 +233,22 @@ class RESTCatalog(Catalog):
self.load_table_metadata,
)
+ def _load_system_table(self, identifier: Identifier):
+ from pypaimon.table.system import system_table_loader
+
+ base_identifier = Identifier.create(
+ identifier.get_database_name(),
+ identifier.get_table_name(),
+ branch=identifier.get_branch_name(),
+ )
+ base_table = self._load_data_table(base_identifier)
+ sys_table = system_table_loader.load(
+ identifier.get_system_table_name(), base_table
+ )
+ if sys_table is None:
+ raise TableNotExistException(identifier)
+ return sys_table
+
def create_table(self, identifier: Union[str, Identifier], schema: Schema, ignore_if_exists: bool):
if not isinstance(identifier, Identifier):
identifier = Identifier.from_string(identifier)
diff --git a/paimon-python/pypaimon/schema/schema_manager.py b/paimon-python/pypaimon/schema/schema_manager.py
index 3ce4310899..3880bcd15c 100644
--- a/paimon-python/pypaimon/schema/schema_manager.py
+++ b/paimon-python/pypaimon/schema/schema_manager.py
@@ -259,6 +259,20 @@ class SchemaManager:
except Exception as e:
raise RuntimeError(f"Failed to load schema from path: {self.schema_path}") from e
+ def list_all(self) -> List['TableSchema']:
+ """Return every committed schema in ascending ID order.
+
+ Missing IDs (deleted on disk after expiry, for instance) are
+ skipped.
+ """
+ ids = sorted(self._list_versioned_files())
+ schemas: List['TableSchema'] = []
+ for schema_id in ids:
+ schema = self.get_schema(schema_id)
+ if schema is not None:
+ schemas.append(schema)
+ return schemas
+
def create_table(self, schema: Schema) -> TableSchema:
while True:
latest = self.latest()
diff --git a/paimon-python/pypaimon/snapshot/snapshot_manager.py b/paimon-python/pypaimon/snapshot/snapshot_manager.py
index e40a7d78c8..c8f1f4818e 100644
--- a/paimon-python/pypaimon/snapshot/snapshot_manager.py
+++ b/paimon-python/pypaimon/snapshot/snapshot_manager.py
@@ -224,6 +224,39 @@ class SnapshotManager:
return final_snapshot
+ def list_snapshots(self) -> List[Snapshot]:
+ """Return every persisted snapshot in ascending ID order.
+
+ Scans ``snapshot_dir`` for ``snapshot-N`` files and decodes
+ each. IDs whose file is missing (because a previous expire
+ cleaned them) are skipped silently, so the result reflects
+ only snapshots that can still be inspected.
+ """
+ import re
+
+ if not self.file_io.exists(self.snapshot_dir):
+ return []
+
+ file_infos = self.file_io.list_status(self.snapshot_dir)
+ if file_infos is None:
+ return []
+
+ pattern = re.compile(r'^snapshot-(\d+)$')
+ ids = []
+ for file_info in file_infos:
+ name = file_info.path.split('/')[-1]
+ match = pattern.match(name)
+ if match:
+ ids.append(int(match.group(1)))
+ ids.sort()
+
+ snapshots: List[Snapshot] = []
+ for snapshot_id in ids:
+ snapshot = self.get_snapshot_by_id(snapshot_id)
+ if snapshot is not None:
+ snapshots.append(snapshot)
+ return snapshots
+
def get_snapshot_by_id(self, snapshot_id: int) -> Optional[Snapshot]:
"""
Get a snapshot by its ID.
diff --git a/paimon-python/pypaimon/table/system/__init__.py b/paimon-python/pypaimon/table/system/__init__.py
new file mode 100644
index 0000000000..1dd3611e3c
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/__init__.py
@@ -0,0 +1,20 @@
+# 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.
+
+from pypaimon.table.system.system_table import SystemTable
+
+__all__ = ["SystemTable"]
diff --git a/paimon-python/pypaimon/table/system/branches_table.py b/paimon-python/pypaimon/table/system/branches_table.py
new file mode 100644
index 0000000000..227e30ba0b
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/branches_table.py
@@ -0,0 +1,96 @@
+# 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.
+
+"""The ``$branches`` system table — every named branch and its mtime."""
+
+from typing import List, Optional
+
+import pyarrow
+
+from pypaimon.branch.branch_manager import BranchManager
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "branch_name", AtomicType("STRING", nullable=False)),
+ DataField(1, "create_time", AtomicType("TIMESTAMP(3)", nullable=False)),
+])
+
+
+_TIMESTAMP_TYPE = pyarrow.timestamp("ms")
+
+
+class BranchesTable(SystemTable):
+ """The ``$branches`` system table."""
+
+ def system_table_name(self) -> str:
+ return "branches"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["branch_name"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ branch_manager = self.base_table.branch_manager()
+ names = list(branch_manager.branches())
+ create_times: List[int] = []
+ for name in names:
+ branch_path = BranchManager.branch_path(
+ self.base_table.table_path, name)
+ ms = _read_mtime_ms(self.base_table.file_io, branch_path)
+ # ``create_time`` is declared NOT NULL. When the backing
+ # store cannot return an mtime (some remote object stores
+ # via PyArrowFileIO) fall back to epoch 0 so the schema
+ # contract holds.
+ create_times.append(0 if ms is None else int(ms))
+ return pyarrow.table({
+ "branch_name": pyarrow.array(names, type=pyarrow.string()),
+ "create_time": pyarrow.array(create_times, type=_TIMESTAMP_TYPE),
+ })
+
+
+def _read_mtime_ms(file_io, path: str) -> Optional[int]:
+ """Read the modification time of ``path`` as epoch milliseconds.
+
+ Returns ``None`` when the path is missing or the file-status object
+ does not carry a usable timestamp. Handles both
+ ``mtime_ns`` (PyArrow's ``FileInfo``) and ``mtime`` (LocalFileStatus's
+ seconds-since-epoch float or a ``datetime``).
+ """
+ try:
+ if not file_io.exists(path):
+ return None
+ file_status = file_io.get_file_status(path)
+ except Exception:
+ return None
+
+ mtime_ns = getattr(file_status, "mtime_ns", None)
+ if mtime_ns is not None:
+ return int(mtime_ns // 1_000_000)
+ mtime = getattr(file_status, "mtime", None)
+ if mtime is None:
+ return None
+ try:
+ return int(mtime.timestamp() * 1000)
+ except AttributeError:
+ try:
+ return int(float(mtime) * 1000)
+ except (TypeError, ValueError):
+ return None
diff --git a/paimon-python/pypaimon/table/system/files_table.py b/paimon-python/pypaimon/table/system/files_table.py
new file mode 100644
index 0000000000..1b3bb4bb10
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/files_table.py
@@ -0,0 +1,297 @@
+# 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.
+
+"""The ``$files`` system table — per-data-file detail of the latest snapshot."""
+
+import json
+from typing import Any, List, Optional
+
+import pyarrow
+
+from pypaimon.manifest.manifest_file_manager import ManifestFileManager
+from pypaimon.manifest.manifest_list_manager import ManifestListManager
+from pypaimon.schema.data_types import (ArrayType, AtomicType, DataField,
+ RowType)
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "partition", AtomicType("STRING", nullable=True)),
+ DataField(1, "bucket", AtomicType("INT", nullable=False)),
+ DataField(2, "file_path", AtomicType("STRING", nullable=False)),
+ DataField(3, "file_format", AtomicType("STRING", nullable=False)),
+ DataField(4, "schema_id", AtomicType("BIGINT", nullable=False)),
+ DataField(5, "level", AtomicType("INT", nullable=False)),
+ DataField(6, "record_count", AtomicType("BIGINT", nullable=False)),
+ DataField(7, "file_size_in_bytes", AtomicType("BIGINT", nullable=False)),
+ DataField(8, "min_key", AtomicType("STRING", nullable=True)),
+ DataField(9, "max_key", AtomicType("STRING", nullable=True)),
+ DataField(10, "null_value_counts", AtomicType("STRING", nullable=False)),
+ DataField(11, "min_value_stats", AtomicType("STRING", nullable=False)),
+ DataField(12, "max_value_stats", AtomicType("STRING", nullable=False)),
+ DataField(13, "min_sequence_number", AtomicType("BIGINT", nullable=True)),
+ DataField(14, "max_sequence_number", AtomicType("BIGINT", nullable=True)),
+ DataField(15, "creation_time", AtomicType("TIMESTAMP(3)", nullable=True)),
+ # ``deleteRowCount`` is intentionally camelCase to keep the on-wire
+ # column name stable.
+ DataField(16, "deleteRowCount", AtomicType("BIGINT", nullable=True)),
+ DataField(17, "file_source", AtomicType("STRING", nullable=True)),
+ DataField(18, "first_row_id", AtomicType("BIGINT", nullable=True)),
+ DataField(
+ 19,
+ "write_cols",
+ ArrayType(nullable=True,
+ element_type=AtomicType("STRING", nullable=True))),
+])
+
+
+_TIMESTAMP_TYPE = pyarrow.timestamp("ms")
+_WRITE_COLS_TYPE = pyarrow.list_(pyarrow.string())
+
+
+def _to_json(obj: Any) -> str:
+ return json.dumps(obj, separators=(',', ':'), ensure_ascii=False,
+ default=str)
+
+
+def _stringify_path(value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, bytes):
+ try:
+ return value.decode("utf-8")
+ except UnicodeDecodeError:
+ return value.hex()
+ return str(value)
+
+
+def _stats_columns(file_meta, table_field_names: List[str]) -> List[str]:
+ cols = getattr(file_meta, "value_stats_cols", None)
+ if cols:
+ return list(cols)
+ return list(table_field_names)
+
+
+def _to_python(value: Any) -> Any:
+ """Render an internal-row cell value into a JSON-safe primitive."""
+ if value is None:
+ return None
+ if isinstance(value, bytes):
+ try:
+ return value.decode("utf-8")
+ except UnicodeDecodeError:
+ return value.hex()
+ if hasattr(value, "isoformat"):
+ try:
+ return value.isoformat()
+ except Exception:
+ return str(value)
+ if isinstance(value, (int, float, bool, str, list, dict)):
+ return value
+ return str(value)
+
+
+def _render_key(row) -> Optional[str]:
+ if row is None:
+ return None
+ values = getattr(row, "values", None)
+ if not values:
+ return None
+ return _to_json([_to_python(v) for v in values])
+
+
+def _render_partition(partition_row) -> Optional[str]:
+ if partition_row is None:
+ return None
+ fields = getattr(partition_row, "fields", None) or []
+ values = getattr(partition_row, "values", None) or []
+ if not fields:
+ return None
+ return "/".join("{}={}".format(field.name, value)
+ for field, value in zip(fields, values))
+
+
+def _render_stats_map(values: List[Any], columns: List[str]) -> str:
+ pairs = {}
+ n = min(len(columns), len(values) if values is not None else 0)
+ for i in range(n):
+ pairs[columns[i]] = _to_python(values[i])
+ return _to_json(pairs)
+
+
+def _render_null_counts(null_counts: Optional[List[int]],
+ columns: List[str]) -> str:
+ pairs = {}
+ if null_counts:
+ n = min(len(columns), len(null_counts))
+ for i in range(n):
+ pairs[columns[i]] = (None if null_counts[i] is None
+ else int(null_counts[i]))
+ return _to_json(pairs)
+
+
+class FilesTable(SystemTable):
+ """The ``$files`` system table."""
+
+ def system_table_name(self) -> str:
+ return "files"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["file_path"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ snapshot = self.base_table.snapshot_manager().get_latest_snapshot()
+ if snapshot is None:
+ return self._empty_table()
+
+ manifest_list_manager = ManifestListManager(self.base_table)
+ manifest_files = manifest_list_manager.read_all(snapshot)
+ manifest_file_manager = ManifestFileManager(self.base_table)
+ entries = manifest_file_manager.read_entries_parallel(
+ manifest_files, drop_stats=False)
+
+ file_format = self.base_table.options.file_format()
+ table_field_names = list(self.base_table.field_names)
+
+ rows = {
+ "partition": [],
+ "bucket": [],
+ "file_path": [],
+ "file_format": [],
+ "schema_id": [],
+ "level": [],
+ "record_count": [],
+ "file_size_in_bytes": [],
+ "min_key": [],
+ "max_key": [],
+ "null_value_counts": [],
+ "min_value_stats": [],
+ "max_value_stats": [],
+ "min_sequence_number": [],
+ "max_sequence_number": [],
+ "creation_time": [],
+ "deleteRowCount": [],
+ "file_source": [],
+ "first_row_id": [],
+ "write_cols": [],
+ }
+
+ for entry in entries:
+ meta = entry.file
+ rows["partition"].append(_render_partition(entry.partition))
+ rows["bucket"].append(int(entry.bucket))
+ rows["file_path"].append(_stringify_path(
+ meta.file_path or meta.file_name))
+ rows["file_format"].append(file_format)
+ rows["schema_id"].append(int(meta.schema_id))
+ rows["level"].append(int(meta.level))
+ rows["record_count"].append(int(meta.row_count))
+ rows["file_size_in_bytes"].append(int(meta.file_size))
+ rows["min_key"].append(_render_key(meta.min_key))
+ rows["max_key"].append(_render_key(meta.max_key))
+
+ stats_cols = _stats_columns(meta, table_field_names)
+ value_stats = meta.value_stats
+ rows["null_value_counts"].append(
+ _render_null_counts(value_stats.null_counts, stats_cols))
+ rows["min_value_stats"].append(_render_stats_map(
+ getattr(value_stats.min_values, "values", []) or [],
+ stats_cols))
+ rows["max_value_stats"].append(_render_stats_map(
+ getattr(value_stats.max_values, "values", []) or [],
+ stats_cols))
+
+ rows["min_sequence_number"].append(int(meta.min_sequence_number))
+ rows["max_sequence_number"].append(int(meta.max_sequence_number))
+ rows["creation_time"].append(meta.creation_time_epoch_millis())
+ rows["deleteRowCount"].append(
+ None if meta.delete_row_count is None
+ else int(meta.delete_row_count))
+ rows["file_source"].append(
+ None if meta.file_source is None else str(meta.file_source))
+ rows["first_row_id"].append(
+ None if meta.first_row_id is None
+ else int(meta.first_row_id))
+ rows["write_cols"].append(
+ list(meta.write_cols) if meta.write_cols else None)
+
+ return pyarrow.table({
+ "partition": pyarrow.array(
+ rows["partition"], type=pyarrow.string()),
+ "bucket": pyarrow.array(rows["bucket"], type=pyarrow.int32()),
+ "file_path": pyarrow.array(
+ rows["file_path"], type=pyarrow.string()),
+ "file_format": pyarrow.array(
+ rows["file_format"], type=pyarrow.string()),
+ "schema_id": pyarrow.array(
+ rows["schema_id"], type=pyarrow.int64()),
+ "level": pyarrow.array(rows["level"], type=pyarrow.int32()),
+ "record_count": pyarrow.array(
+ rows["record_count"], type=pyarrow.int64()),
+ "file_size_in_bytes": pyarrow.array(
+ rows["file_size_in_bytes"], type=pyarrow.int64()),
+ "min_key": pyarrow.array(rows["min_key"], type=pyarrow.string()),
+ "max_key": pyarrow.array(rows["max_key"], type=pyarrow.string()),
+ "null_value_counts": pyarrow.array(
+ rows["null_value_counts"], type=pyarrow.string()),
+ "min_value_stats": pyarrow.array(
+ rows["min_value_stats"], type=pyarrow.string()),
+ "max_value_stats": pyarrow.array(
+ rows["max_value_stats"], type=pyarrow.string()),
+ "min_sequence_number": pyarrow.array(
+ rows["min_sequence_number"], type=pyarrow.int64()),
+ "max_sequence_number": pyarrow.array(
+ rows["max_sequence_number"], type=pyarrow.int64()),
+ "creation_time": pyarrow.array(
+ rows["creation_time"], type=_TIMESTAMP_TYPE),
+ "deleteRowCount": pyarrow.array(
+ rows["deleteRowCount"], type=pyarrow.int64()),
+ "file_source": pyarrow.array(
+ rows["file_source"], type=pyarrow.string()),
+ "first_row_id": pyarrow.array(
+ rows["first_row_id"], type=pyarrow.int64()),
+ "write_cols": pyarrow.array(
+ rows["write_cols"], type=_WRITE_COLS_TYPE),
+ })
+
+ @staticmethod
+ def _empty_table() -> pyarrow.Table:
+ return pyarrow.table({
+ "partition": pyarrow.array([], type=pyarrow.string()),
+ "bucket": pyarrow.array([], type=pyarrow.int32()),
+ "file_path": pyarrow.array([], type=pyarrow.string()),
+ "file_format": pyarrow.array([], type=pyarrow.string()),
+ "schema_id": pyarrow.array([], type=pyarrow.int64()),
+ "level": pyarrow.array([], type=pyarrow.int32()),
+ "record_count": pyarrow.array([], type=pyarrow.int64()),
+ "file_size_in_bytes": pyarrow.array([], type=pyarrow.int64()),
+ "min_key": pyarrow.array([], type=pyarrow.string()),
+ "max_key": pyarrow.array([], type=pyarrow.string()),
+ "null_value_counts": pyarrow.array([], type=pyarrow.string()),
+ "min_value_stats": pyarrow.array([], type=pyarrow.string()),
+ "max_value_stats": pyarrow.array([], type=pyarrow.string()),
+ "min_sequence_number": pyarrow.array([], type=pyarrow.int64()),
+ "max_sequence_number": pyarrow.array([], type=pyarrow.int64()),
+ "creation_time": pyarrow.array([], type=_TIMESTAMP_TYPE),
+ "deleteRowCount": pyarrow.array([], type=pyarrow.int64()),
+ "file_source": pyarrow.array([], type=pyarrow.string()),
+ "first_row_id": pyarrow.array([], type=pyarrow.int64()),
+ "write_cols": pyarrow.array([], type=_WRITE_COLS_TYPE),
+ })
diff --git a/paimon-python/pypaimon/table/system/manifests_table.py b/paimon-python/pypaimon/table/system/manifests_table.py
new file mode 100644
index 0000000000..1975a4208a
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/manifests_table.py
@@ -0,0 +1,115 @@
+# 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.
+
+"""The ``$manifests`` system table — manifest list for the latest snapshot."""
+
+from typing import List, Optional
+
+import pyarrow
+
+from pypaimon.manifest.manifest_list_manager import ManifestListManager
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "file_name", AtomicType("STRING", nullable=False)),
+ DataField(1, "file_size", AtomicType("BIGINT", nullable=False)),
+ DataField(2, "num_added_files", AtomicType("BIGINT", nullable=False)),
+ DataField(3, "num_deleted_files", AtomicType("BIGINT", nullable=False)),
+ DataField(4, "schema_id", AtomicType("BIGINT", nullable=False)),
+ DataField(5, "min_partition_stats", AtomicType("STRING", nullable=True)),
+ DataField(6, "max_partition_stats", AtomicType("STRING", nullable=True)),
+ DataField(7, "min_row_id", AtomicType("BIGINT", nullable=True)),
+ DataField(8, "max_row_id", AtomicType("BIGINT", nullable=True)),
+])
+
+
+class ManifestsTable(SystemTable):
+ """The ``$manifests`` system table for the latest snapshot."""
+
+ def system_table_name(self) -> str:
+ return "manifests"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["file_name"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ snapshot = self.base_table.snapshot_manager().get_latest_snapshot()
+ if snapshot is None:
+ return self._empty_table()
+
+ manifest_list_manager = ManifestListManager(self.base_table)
+ manifests = manifest_list_manager.read_all(snapshot)
+
+ file_names: List[str] = []
+ file_sizes: List[int] = []
+ num_added: List[int] = []
+ num_deleted: List[int] = []
+ schema_ids: List[int] = []
+ min_partition_stats: List[Optional[str]] = []
+ max_partition_stats: List[Optional[str]] = []
+ min_row_ids: List[Optional[int]] = []
+ max_row_ids: List[Optional[int]] = []
+
+ for meta in manifests:
+ file_names.append(meta.file_name)
+ file_sizes.append(int(meta.file_size))
+ num_added.append(int(meta.num_added_files))
+ num_deleted.append(int(meta.num_deleted_files))
+ schema_ids.append(int(meta.schema_id))
+ # TODO: render min/max_partition_stats by casting partition
+ # rows to their string form. pypaimon
+ # has SimpleStats but no shared partition-row-to-string
+ # helper yet; emit NULL to preserve the column shape.
+ min_partition_stats.append(None)
+ max_partition_stats.append(None)
+ min_row_ids.append(
+ None if meta.min_row_id is None else int(meta.min_row_id))
+ max_row_ids.append(
+ None if meta.max_row_id is None else int(meta.max_row_id))
+
+ return pyarrow.table({
+ "file_name": pyarrow.array(file_names, type=pyarrow.string()),
+ "file_size": pyarrow.array(file_sizes, type=pyarrow.int64()),
+ "num_added_files": pyarrow.array(num_added, type=pyarrow.int64()),
+ "num_deleted_files": pyarrow.array(num_deleted, type=pyarrow.int64()),
+ "schema_id": pyarrow.array(schema_ids, type=pyarrow.int64()),
+ "min_partition_stats": pyarrow.array(
+ min_partition_stats, type=pyarrow.string()),
+ "max_partition_stats": pyarrow.array(
+ max_partition_stats, type=pyarrow.string()),
+ "min_row_id": pyarrow.array(min_row_ids, type=pyarrow.int64()),
+ "max_row_id": pyarrow.array(max_row_ids, type=pyarrow.int64()),
+ })
+
+ @staticmethod
+ def _empty_table() -> pyarrow.Table:
+ return pyarrow.table({
+ "file_name": pyarrow.array([], type=pyarrow.string()),
+ "file_size": pyarrow.array([], type=pyarrow.int64()),
+ "num_added_files": pyarrow.array([], type=pyarrow.int64()),
+ "num_deleted_files": pyarrow.array([], type=pyarrow.int64()),
+ "schema_id": pyarrow.array([], type=pyarrow.int64()),
+ "min_partition_stats": pyarrow.array([], type=pyarrow.string()),
+ "max_partition_stats": pyarrow.array([], type=pyarrow.string()),
+ "min_row_id": pyarrow.array([], type=pyarrow.int64()),
+ "max_row_id": pyarrow.array([], type=pyarrow.int64()),
+ })
diff --git a/paimon-python/pypaimon/table/system/options_table.py b/paimon-python/pypaimon/table/system/options_table.py
new file mode 100644
index 0000000000..3f876ea3d8
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/options_table.py
@@ -0,0 +1,54 @@
+# 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.
+
+"""The ``$options`` system table — every option from the latest schema."""
+
+from typing import List
+
+import pyarrow
+
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "key", AtomicType("STRING", nullable=False)),
+ DataField(1, "value", AtomicType("STRING", nullable=False)),
+])
+
+
+class OptionsTable(SystemTable):
+ """The ``$options`` system table: one (key, value) row per option."""
+
+ def system_table_name(self) -> str:
+ return "options"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["key"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ schema = self.base_table.schema_manager.latest()
+ options = schema.options if schema is not None else {}
+ keys: List[str] = []
+ values: List[str] = []
+ for key, value in options.items():
+ keys.append(str(key))
+ values.append("" if value is None else str(value))
+ return pyarrow.table({"key": keys, "value": values})
diff --git a/paimon-python/pypaimon/table/system/partitions_table.py b/paimon-python/pypaimon/table/system/partitions_table.py
new file mode 100644
index 0000000000..583e4fd94f
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/partitions_table.py
@@ -0,0 +1,162 @@
+# 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.
+
+"""The ``$partitions`` system table — aggregated partition stats."""
+
+from typing import List, Optional
+
+import pyarrow
+
+from pypaimon.manifest.manifest_file_manager import ManifestFileManager
+from pypaimon.manifest.manifest_list_manager import ManifestListManager
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "partition", AtomicType("STRING", nullable=True)),
+ DataField(1, "record_count", AtomicType("BIGINT", nullable=False)),
+ DataField(2, "file_size_in_bytes", AtomicType("BIGINT", nullable=False)),
+ DataField(3, "file_count", AtomicType("BIGINT", nullable=False)),
+ DataField(4, "last_update_time", AtomicType("TIMESTAMP(3)", nullable=True)),
+ DataField(5, "created_at", AtomicType("TIMESTAMP(3)", nullable=True)),
+ DataField(6, "created_by", AtomicType("STRING", nullable=True)),
+ DataField(7, "updated_by", AtomicType("STRING", nullable=True)),
+ DataField(8, "options", AtomicType("STRING", nullable=True)),
+ DataField(9, "total_buckets", AtomicType("INT", nullable=False)),
+ DataField(10, "done", AtomicType("BOOLEAN", nullable=False)),
+])
+
+
+_TIMESTAMP_TYPE = pyarrow.timestamp("ms")
+
+
+class PartitionsTable(SystemTable):
+ """The ``$partitions`` system table.
+
+ The filesystem flow aggregates from manifest entries; catalog-owned
+ columns (``created_at``, ``created_by``, ``updated_by``, ``options``,
+ ``done``) are filled with placeholders because the filesystem
+ catalog does not track them.
+ """
+
+ def system_table_name(self) -> str:
+ return "partitions"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["partition"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ snapshot = self.base_table.snapshot_manager().get_latest_snapshot()
+ if snapshot is None:
+ return self._empty_table()
+
+ manifest_list_manager = ManifestListManager(self.base_table)
+ manifest_files = manifest_list_manager.read_all(snapshot)
+ manifest_file_manager = ManifestFileManager(self.base_table)
+ entries = manifest_file_manager.read_entries_parallel(
+ manifest_files, drop_stats=True)
+
+ partition_map: dict = {}
+ for entry in entries:
+ spec_items = tuple(
+ (field.name, str(value))
+ for field, value in zip(
+ entry.partition.fields, entry.partition.values))
+ spec_key = spec_items
+
+ stats = partition_map.get(spec_key)
+ if stats is None:
+ stats = {
+ "spec_items": spec_items,
+ "record_count": 0,
+ "file_size_in_bytes": 0,
+ "file_count": 0,
+ "last_update_time": None,
+ "buckets": set(),
+ }
+ partition_map[spec_key] = stats
+
+ stats["record_count"] += int(entry.file.row_count)
+ stats["file_size_in_bytes"] += int(entry.file.file_size)
+ stats["file_count"] += 1
+ if entry.file.creation_time is not None:
+ ct_ms = entry.file.creation_time.get_millisecond()
+ if (stats["last_update_time"] is None
+ or ct_ms > stats["last_update_time"]):
+ stats["last_update_time"] = ct_ms
+ stats["buckets"].add(int(entry.bucket))
+
+ partition_strings: List[Optional[str]] = []
+ record_counts: List[int] = []
+ file_sizes: List[int] = []
+ file_counts: List[int] = []
+ last_update_times: List[Optional[int]] = []
+ total_buckets: List[int] = []
+
+ for stats in partition_map.values():
+ partition_strings.append(_render_partition(stats["spec_items"]))
+ record_counts.append(stats["record_count"])
+ file_sizes.append(stats["file_size_in_bytes"])
+ file_counts.append(stats["file_count"])
+ last_update_times.append(stats["last_update_time"])
+ total_buckets.append(len(stats["buckets"]))
+
+ n = len(partition_map)
+ return pyarrow.table({
+ "partition": pyarrow.array(
+ partition_strings, type=pyarrow.string()),
+ "record_count": pyarrow.array(
+ record_counts, type=pyarrow.int64()),
+ "file_size_in_bytes": pyarrow.array(
+ file_sizes, type=pyarrow.int64()),
+ "file_count": pyarrow.array(file_counts, type=pyarrow.int64()),
+ "last_update_time": pyarrow.array(
+ last_update_times, type=_TIMESTAMP_TYPE),
+ "created_at": pyarrow.array([None] * n, type=_TIMESTAMP_TYPE),
+ "created_by": pyarrow.array([None] * n, type=pyarrow.string()),
+ "updated_by": pyarrow.array([None] * n, type=pyarrow.string()),
+ "options": pyarrow.array([None] * n, type=pyarrow.string()),
+ "total_buckets": pyarrow.array(total_buckets, type=pyarrow.int32()),
+ "done": pyarrow.array([False] * n, type=pyarrow.bool_()),
+ })
+
+ @staticmethod
+ def _empty_table() -> pyarrow.Table:
+ return pyarrow.table({
+ "partition": pyarrow.array([], type=pyarrow.string()),
+ "record_count": pyarrow.array([], type=pyarrow.int64()),
+ "file_size_in_bytes": pyarrow.array([], type=pyarrow.int64()),
+ "file_count": pyarrow.array([], type=pyarrow.int64()),
+ "last_update_time": pyarrow.array([], type=_TIMESTAMP_TYPE),
+ "created_at": pyarrow.array([], type=_TIMESTAMP_TYPE),
+ "created_by": pyarrow.array([], type=pyarrow.string()),
+ "updated_by": pyarrow.array([], type=pyarrow.string()),
+ "options": pyarrow.array([], type=pyarrow.string()),
+ "total_buckets": pyarrow.array([], type=pyarrow.int32()),
+ "done": pyarrow.array([], type=pyarrow.bool_()),
+ })
+
+
+def _render_partition(spec_items) -> Optional[str]:
+ """Render a partition spec as ``pt=v/pt2=v2`` or None when empty."""
+ if not spec_items:
+ return None
+ return "/".join("{}={}".format(name, value) for name, value in spec_items)
diff --git a/paimon-python/pypaimon/table/system/schemas_table.py b/paimon-python/pypaimon/table/system/schemas_table.py
new file mode 100644
index 0000000000..7b917be4e3
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/schemas_table.py
@@ -0,0 +1,97 @@
+# 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.
+
+"""The ``$schemas`` system table — every committed table schema."""
+
+import json
+from typing import Any, List, Optional
+
+import pyarrow
+
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "schema_id", AtomicType("BIGINT", nullable=False)),
+ DataField(1, "fields", AtomicType("STRING", nullable=False)),
+ DataField(2, "partition_keys", AtomicType("STRING", nullable=False)),
+ DataField(3, "primary_keys", AtomicType("STRING", nullable=False)),
+ DataField(4, "options", AtomicType("STRING", nullable=False)),
+ DataField(5, "comment", AtomicType("STRING", nullable=True)),
+ DataField(6, "update_time", AtomicType("TIMESTAMP(3)", nullable=False)),
+])
+
+
+_TIMESTAMP_TYPE = pyarrow.timestamp("ms")
+
+
+def _to_json(value: Any) -> str:
+ """Compact JSON encoding for the four serialised columns.
+
+ Field ordering follows the source object (insertion order for dicts
+ and lists is preserved by ``json.dumps``); bit-exact equality with
+ any external encoder is not promised — callers compare decoded
+ structures, not raw strings.
+ """
+ return json.dumps(value, separators=(',', ':'), ensure_ascii=False)
+
+
+class SchemasTable(SystemTable):
+ """The ``$schemas`` system table."""
+
+ def system_table_name(self) -> str:
+ return "schemas"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["schema_id"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ schemas = self.base_table.schema_manager.list_all()
+
+ schema_ids: List[int] = []
+ fields_jsons: List[str] = []
+ partition_keys_jsons: List[str] = []
+ primary_keys_jsons: List[str] = []
+ options_jsons: List[str] = []
+ comments: List[Optional[str]] = []
+ update_times: List[int] = []
+
+ for schema in schemas:
+ schema_ids.append(int(schema.id))
+ fields_jsons.append(
+ _to_json([field.to_dict() for field in schema.fields]))
+ partition_keys_jsons.append(_to_json(list(schema.partition_keys)))
+ primary_keys_jsons.append(_to_json(list(schema.primary_keys)))
+ options_jsons.append(_to_json(dict(schema.options)))
+ comments.append(schema.comment)
+ update_times.append(int(schema.time_millis))
+
+ return pyarrow.table({
+ "schema_id": pyarrow.array(schema_ids, type=pyarrow.int64()),
+ "fields": pyarrow.array(fields_jsons, type=pyarrow.string()),
+ "partition_keys": pyarrow.array(
+ partition_keys_jsons, type=pyarrow.string()),
+ "primary_keys": pyarrow.array(
+ primary_keys_jsons, type=pyarrow.string()),
+ "options": pyarrow.array(options_jsons, type=pyarrow.string()),
+ "comment": pyarrow.array(comments, type=pyarrow.string()),
+ "update_time": pyarrow.array(update_times, type=_TIMESTAMP_TYPE),
+ })
diff --git a/paimon-python/pypaimon/table/system/snapshots_table.py b/paimon-python/pypaimon/table/system/snapshots_table.py
new file mode 100644
index 0000000000..be7331d21f
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/snapshots_table.py
@@ -0,0 +1,125 @@
+# 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.
+
+"""The ``$snapshots`` system table — every committed snapshot's metadata."""
+
+from typing import List, Optional
+
+import pyarrow
+
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "snapshot_id", AtomicType("BIGINT", nullable=False)),
+ DataField(1, "schema_id", AtomicType("BIGINT", nullable=False)),
+ DataField(2, "commit_user", AtomicType("STRING", nullable=False)),
+ DataField(3, "commit_identifier", AtomicType("BIGINT", nullable=False)),
+ DataField(4, "commit_kind", AtomicType("STRING", nullable=False)),
+ DataField(5, "commit_time", AtomicType("TIMESTAMP(3)", nullable=False)),
+ DataField(6, "base_manifest_list", AtomicType("STRING", nullable=False)),
+ DataField(7, "delta_manifest_list", AtomicType("STRING", nullable=False)),
+ DataField(8, "changelog_manifest_list", AtomicType("STRING", nullable=True)),
+ DataField(9, "total_record_count", AtomicType("BIGINT", nullable=True)),
+ DataField(10, "delta_record_count", AtomicType("BIGINT", nullable=True)),
+ DataField(11, "changelog_record_count", AtomicType("BIGINT", nullable=True)),
+ DataField(12, "watermark", AtomicType("BIGINT", nullable=True)),
+ DataField(13, "next_row_id", AtomicType("BIGINT", nullable=True)),
+])
+
+
+_TIMESTAMP_TYPE = pyarrow.timestamp("ms")
+
+
+class SnapshotsTable(SystemTable):
+ """The ``$snapshots`` system table."""
+
+ def system_table_name(self) -> str:
+ return "snapshots"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["snapshot_id"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ snapshots = self.base_table.snapshot_manager().list_snapshots()
+
+ snapshot_ids: List[int] = []
+ schema_ids: List[int] = []
+ commit_users: List[str] = []
+ commit_identifiers: List[int] = []
+ commit_kinds: List[str] = []
+ commit_times: List[int] = []
+ base_manifest_lists: List[str] = []
+ delta_manifest_lists: List[str] = []
+ changelog_manifest_lists: List[Optional[str]] = []
+ total_record_counts: List[Optional[int]] = []
+ delta_record_counts: List[Optional[int]] = []
+ changelog_record_counts: List[Optional[int]] = []
+ watermarks: List[Optional[int]] = []
+ next_row_ids: List[Optional[int]] = []
+
+ for snap in snapshots:
+ snapshot_ids.append(int(snap.id))
+ schema_ids.append(int(snap.schema_id))
+ commit_users.append(snap.commit_user)
+ commit_identifiers.append(int(snap.commit_identifier))
+ commit_kinds.append(snap.commit_kind)
+ commit_times.append(int(snap.time_millis))
+ base_manifest_lists.append(snap.base_manifest_list)
+ delta_manifest_lists.append(snap.delta_manifest_list)
+ changelog_manifest_lists.append(snap.changelog_manifest_list)
+ total_record_counts.append(
+ None if snap.total_record_count is None
+ else int(snap.total_record_count))
+ delta_record_counts.append(
+ None if snap.delta_record_count is None
+ else int(snap.delta_record_count))
+ changelog_record_counts.append(
+ None if snap.changelog_record_count is None
+ else int(snap.changelog_record_count))
+ watermarks.append(
+ None if snap.watermark is None else int(snap.watermark))
+ next_row_ids.append(
+ None if snap.next_row_id is None else int(snap.next_row_id))
+
+ return pyarrow.table({
+ "snapshot_id": pyarrow.array(snapshot_ids, type=pyarrow.int64()),
+ "schema_id": pyarrow.array(schema_ids, type=pyarrow.int64()),
+ "commit_user": pyarrow.array(commit_users, type=pyarrow.string()),
+ "commit_identifier": pyarrow.array(
+ commit_identifiers, type=pyarrow.int64()),
+ "commit_kind": pyarrow.array(commit_kinds, type=pyarrow.string()),
+ "commit_time": pyarrow.array(commit_times, type=_TIMESTAMP_TYPE),
+ "base_manifest_list": pyarrow.array(
+ base_manifest_lists, type=pyarrow.string()),
+ "delta_manifest_list": pyarrow.array(
+ delta_manifest_lists, type=pyarrow.string()),
+ "changelog_manifest_list": pyarrow.array(
+ changelog_manifest_lists, type=pyarrow.string()),
+ "total_record_count": pyarrow.array(
+ total_record_counts, type=pyarrow.int64()),
+ "delta_record_count": pyarrow.array(
+ delta_record_counts, type=pyarrow.int64()),
+ "changelog_record_count": pyarrow.array(
+ changelog_record_counts, type=pyarrow.int64()),
+ "watermark": pyarrow.array(watermarks, type=pyarrow.int64()),
+ "next_row_id": pyarrow.array(next_row_ids, type=pyarrow.int64()),
+ })
diff --git a/paimon-python/pypaimon/table/system/system_table.py b/paimon-python/pypaimon/table/system/system_table.py
new file mode 100644
index 0000000000..69bc14d7dd
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/system_table.py
@@ -0,0 +1,157 @@
+# 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.
+
+"""Abstract base class for read-only system tables.
+
+System tables expose snapshot, schema, manifest and other catalog
+metadata as queryable tables. They share the :class:`Table` contract
+so callers use the same ``new_read_builder().new_read().to_arrow()``
+flow as a regular data table, but every write or search builder
+raises :class:`NotImplementedError` to signal the read-only contract.
+"""
+
+from abc import abstractmethod
+from typing import TYPE_CHECKING, List, Optional
+
+from pypaimon.common.identifier import Identifier
+from pypaimon.common.predicate import Predicate
+from pypaimon.common.predicate_builder import PredicateBuilder
+from pypaimon.schema.data_types import DataField, RowType
+from pypaimon.table.table import Table
+
+if TYPE_CHECKING: # pragma: no cover - import for type hints only
+ import pyarrow
+
+ from pypaimon.table.file_store_table import FileStoreTable
+ from pypaimon.table.system.system_table_read import SystemTableRead
+ from pypaimon.table.system.system_table_scan import SystemTableScan
+
+
+_READ_ONLY_MESSAGE = "System table is read-only"
+
+
+class SystemTable(Table):
+ """Read-only view backed by metadata of a base data table.
+
+ Subclasses implement three hooks:
+
+ * :meth:`system_table_name` returns the short identifier used after
+ the ``$`` separator (e.g. ``"snapshots"``).
+ * :meth:`row_type` declares the table schema as a :class:`RowType`.
+ * :meth:`_build_arrow_table` materialises the entire table as a
+ single PyArrow ``Table`` — system tables are typically small
+ enough that one in-memory pass is the simplest correct shape.
+ """
+
+ def __init__(self, base_table: "FileStoreTable"):
+ self.base_table = base_table
+ self.file_io = base_table.file_io
+ self.table_path = base_table.table_path
+ self.identifier = Identifier.create(
+ base_table.identifier.get_database_name(),
+ base_table.identifier.get_table_name(),
+ branch=base_table.identifier.get_branch_name(),
+ system_table=self.system_table_name(),
+ )
+
+ @abstractmethod
+ def system_table_name(self) -> str:
+ """Return the short name appearing after the ``$`` separator."""
+
+ @abstractmethod
+ def row_type(self) -> RowType:
+ """Return the schema of this system table."""
+
+ def primary_keys(self) -> List[str]:
+ """Return primary key column names; default is no primary key."""
+ return []
+
+ @abstractmethod
+ def _build_arrow_table(self) -> "pyarrow.Table":
+ """Return the entire table contents as a PyArrow Table."""
+
+ def new_read_builder(self) -> "SystemReadBuilder":
+ return SystemReadBuilder(self)
+
+ def new_stream_read_builder(self):
+ raise NotImplementedError(_READ_ONLY_MESSAGE)
+
+ def new_batch_write_builder(self):
+ raise NotImplementedError(_READ_ONLY_MESSAGE)
+
+ def new_stream_write_builder(self):
+ raise NotImplementedError(_READ_ONLY_MESSAGE)
+
+ def new_full_text_search_builder(self):
+ raise NotImplementedError(_READ_ONLY_MESSAGE)
+
+ def new_vector_search_builder(self):
+ raise NotImplementedError(_READ_ONLY_MESSAGE)
+
+
+class SystemReadBuilder:
+ """ReadBuilder-shaped facade exposing the system table's data.
+
+ Mirrors :class:`pypaimon.read.read_builder.ReadBuilder` enough that
+ callers can reach for ``with_filter``, ``with_projection``,
+ ``with_limit``, ``new_predicate_builder``, ``read_type``,
+ ``new_scan`` and ``new_read`` without knowing they are talking to a
+ system table.
+ """
+
+ def __init__(self, system_table: SystemTable):
+ self.system_table = system_table
+ self._predicate: Optional[Predicate] = None
+ self._projection: Optional[List[str]] = None
+ self._limit: Optional[int] = None
+
+ def with_filter(self, predicate: Predicate) -> "SystemReadBuilder":
+ self._predicate = predicate
+ return self
+
+ def with_projection(self, projection: List[str]) -> "SystemReadBuilder":
+ self._projection = list(projection)
+ return self
+
+ def with_limit(self, limit: int) -> "SystemReadBuilder":
+ self._limit = limit
+ return self
+
+ def new_predicate_builder(self) -> PredicateBuilder:
+ return PredicateBuilder(self.read_type())
+
+ def read_type(self) -> List[DataField]:
+ all_fields = self.system_table.row_type().fields
+ if not self._projection:
+ return list(all_fields)
+ field_map = {f.name: f for f in all_fields}
+ # Silently skip unknown names to match ReadBuilder.with_projection.
+ return [field_map[name] for name in self._projection
+ if name in field_map]
+
+ def new_scan(self) -> "SystemTableScan":
+ from pypaimon.table.system.system_table_scan import SystemTableScan
+ return SystemTableScan(self.system_table)
+
+ def new_read(self) -> "SystemTableRead":
+ from pypaimon.table.system.system_table_read import SystemTableRead
+ return SystemTableRead(
+ system_table=self.system_table,
+ read_type=self.read_type(),
+ predicate=self._predicate,
+ limit=self._limit,
+ )
diff --git a/paimon-python/pypaimon/table/system/system_table_loader.py b/paimon-python/pypaimon/table/system/system_table_loader.py
new file mode 100644
index 0000000000..9d0576aec1
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/system_table_loader.py
@@ -0,0 +1,83 @@
+# 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.
+
+"""Registry that maps a system-table short name to its implementation.
+
+Implementation classes are referenced by dotted path and imported
+lazily, so adding a new table is a single registry entry plus the
+new module.
+
+The following short names are intentionally not registered here yet:
+
+ audit_log, binlog, read_optimized, consumers, statistics,
+ aggregation_fields, buckets, file_key_ranges, table_indexes,
+ row_tracking, all_tables, all_partitions, all_table_options,
+ catalog_options
+"""
+
+import importlib
+from typing import Callable, Dict, Optional, TYPE_CHECKING, Tuple
+
+if TYPE_CHECKING: # pragma: no cover - import for type hints only
+ from pypaimon.table.file_store_table import FileStoreTable
+ from pypaimon.table.system.system_table import SystemTable
+
+
+SYSTEM_TABLES: Tuple[str, ...] = (
+ "snapshots",
+ "schemas",
+ "options",
+ "manifests",
+ "files",
+ "partitions",
+ "tags",
+ "branches",
+)
+
+
+def _lazy(module_name: str, class_name: str) -> Callable[..., "SystemTable"]:
+ """Build a factory that imports the implementation on first call."""
+ def factory(base_table: "FileStoreTable") -> "SystemTable":
+ module = importlib.import_module(module_name)
+ cls = getattr(module, class_name)
+ return cls(base_table)
+ factory.__name__ = "load_" + class_name
+ return factory
+
+
+SYSTEM_TABLE_LOADERS: Dict[str, Callable[..., "SystemTable"]] = {
+ "snapshots": _lazy("pypaimon.table.system.snapshots_table", "SnapshotsTable"),
+ "schemas": _lazy("pypaimon.table.system.schemas_table", "SchemasTable"),
+ "options": _lazy("pypaimon.table.system.options_table", "OptionsTable"),
+ "manifests": _lazy("pypaimon.table.system.manifests_table", "ManifestsTable"),
+ "files": _lazy("pypaimon.table.system.files_table", "FilesTable"),
+ "partitions": _lazy("pypaimon.table.system.partitions_table", "PartitionsTable"),
+ "tags": _lazy("pypaimon.table.system.tags_table", "TagsTable"),
+ "branches": _lazy("pypaimon.table.system.branches_table", "BranchesTable"),
+}
+
+
+def load(name: str, base_table: "FileStoreTable") -> Optional["SystemTable"]:
+ """Return the SystemTable implementation for ``name`` or ``None``.
+
+ Callers (typically a Catalog) treat ``None`` as "no such system
+ table" and surface a ``TableNotExistException`` to the user.
+ """
+ factory = SYSTEM_TABLE_LOADERS.get(name)
+ if factory is None:
+ return None
+ return factory(base_table)
diff --git a/paimon-python/pypaimon/table/system/system_table_read.py b/paimon-python/pypaimon/table/system/system_table_read.py
new file mode 100644
index 0000000000..c02258ac3f
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/system_table_read.py
@@ -0,0 +1,127 @@
+# 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 pipeline for system tables.
+
+Mirrors the user-facing surface of :class:`TableRead` (``to_arrow``,
+``to_pandas``, ``to_iterator``, ``to_record_batch_iterator``,
+``to_duckdb``) so callers reach for the same API as a regular data
+table. The implementation operates purely on the in-memory PyArrow
+tables produced by :class:`SystemSplit` — no manifest reads, no data
+files.
+"""
+
+from typing import Any, Iterator, List, Optional, TYPE_CHECKING
+
+import pandas
+import pyarrow
+
+from pypaimon.common.predicate import Predicate
+from pypaimon.read.split import Split
+from pypaimon.schema.data_types import DataField, PyarrowFieldParser
+from pypaimon.table.system.system_table_scan import SystemSplit
+
+if TYPE_CHECKING: # pragma: no cover - type-only import
+ from pypaimon.table.system.system_table import SystemTable
+
+
+_PREDICATE_NOT_SUPPORTED = (
+ "predicate pushdown on system tables is not supported yet; "
+ "filter the resulting PyArrow / pandas table on the client side"
+)
+
+
+class SystemTableRead:
+ """In-memory read pipeline backed by a single SystemSplit."""
+
+ def __init__(
+ self,
+ system_table: "SystemTable",
+ read_type: List[DataField],
+ predicate: Optional[Predicate],
+ limit: Optional[int],
+ ):
+ self.system_table = system_table
+ self.read_type = read_type
+ self.predicate = predicate
+ self.limit = limit
+
+ def to_arrow(self, splits: List[Split]) -> pyarrow.Table:
+ return self._materialise(splits)
+
+ def to_pandas(self, splits: List[Split]) -> pandas.DataFrame:
+ return self.to_arrow(splits).to_pandas()
+
+ def to_iterator(self, splits: List[Split]) -> Iterator[dict]:
+ arrow_table = self.to_arrow(splits)
+ column_names = arrow_table.schema.names
+ for batch in arrow_table.to_batches():
+ py_columns = [batch.column(i).to_pylist()
+ for i in range(batch.num_columns)]
+ for row_idx in range(batch.num_rows):
+ yield {column_names[c]: py_columns[c][row_idx]
+ for c in range(batch.num_columns)}
+
+ def to_record_batch_iterator(
+ self, splits: List[Split]
+ ) -> Iterator[pyarrow.RecordBatch]:
+ for batch in self.to_arrow(splits).to_batches():
+ yield batch
+
+ def to_duckdb(
+ self,
+ splits: List[Split],
+ table_name: str,
+ connection: Optional[Any] = None,
+ ):
+ import duckdb
+
+ con = connection or duckdb.connect(database=":memory:")
+ con.register(table_name, self.to_arrow(splits))
+ return con
+
+ def _materialise(self, splits: List[Split]) -> pyarrow.Table:
+ if self.predicate is not None:
+ raise NotImplementedError(_PREDICATE_NOT_SUPPORTED)
+
+ if not splits:
+ return self._empty_table()
+
+ projected_names = [f.name for f in self.read_type]
+ slices: List[pyarrow.Table] = []
+ for split in splits:
+ if not isinstance(split, SystemSplit):
+ raise TypeError(
+ "SystemTableRead expects SystemSplit but received "
+ + type(split).__name__
+ )
+ arrow_table = split.arrow_table()
+ if projected_names:
+ arrow_table = arrow_table.select(projected_names)
+ slices.append(arrow_table)
+
+ combined = pyarrow.concat_tables(slices)
+ if self.limit is not None and combined.num_rows > self.limit:
+ combined = combined.slice(0, self.limit)
+ return combined
+
+ def _empty_table(self) -> pyarrow.Table:
+ target_schema = PyarrowFieldParser.from_paimon_schema(self.read_type)
+ return pyarrow.Table.from_arrays(
+ [pyarrow.array([], type=f.type) for f in target_schema],
+ schema=target_schema,
+ )
diff --git a/paimon-python/pypaimon/table/system/system_table_scan.py b/paimon-python/pypaimon/table/system/system_table_scan.py
new file mode 100644
index 0000000000..5bc43302a9
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/system_table_scan.py
@@ -0,0 +1,74 @@
+# 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.
+
+"""Scan / split implementation for system tables.
+
+System tables materialise their entire contents into a single PyArrow
+table that is shipped through a single :class:`SystemSplit`. This keeps
+the read pipeline trivially correct: there's no manifest pruning, no
+predicate pushdown and no parallelism to coordinate, only metadata
+that fits comfortably in memory.
+"""
+
+from typing import List, Optional, TYPE_CHECKING
+
+import pyarrow
+
+from pypaimon.manifest.schema.data_file_meta import DataFileMeta
+from pypaimon.read.plan import Plan
+from pypaimon.read.split import Split
+from pypaimon.table.row.generic_row import GenericRow
+
+if TYPE_CHECKING: # pragma: no cover - type-only import
+ from pypaimon.table.system.system_table import SystemTable
+
+
+class SystemSplit(Split):
+ """A single in-memory split carrying the whole system table."""
+
+ def __init__(self, arrow_table: pyarrow.Table):
+ self._arrow_table = arrow_table
+
+ @property
+ def row_count(self) -> int:
+ return self._arrow_table.num_rows
+
+ @property
+ def files(self) -> List[DataFileMeta]:
+ return []
+
+ @property
+ def partition(self) -> Optional[GenericRow]:
+ return None
+
+ @property
+ def bucket(self) -> int:
+ return -1
+
+ def arrow_table(self) -> pyarrow.Table:
+ return self._arrow_table
+
+
+class SystemTableScan:
+ """Returns a one-element plan containing the entire system table."""
+
+ def __init__(self, system_table: "SystemTable"):
+ self.system_table = system_table
+
+ def plan(self) -> Plan:
+ arrow_table = self.system_table._build_arrow_table()
+ return Plan(_splits=[SystemSplit(arrow_table)])
diff --git a/paimon-python/pypaimon/table/system/tags_table.py b/paimon-python/pypaimon/table/system/tags_table.py
new file mode 100644
index 0000000000..7cc50ec7a9
--- /dev/null
+++ b/paimon-python/pypaimon/table/system/tags_table.py
@@ -0,0 +1,89 @@
+# 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.
+
+"""The ``$tags`` system table — every tag plus its snapshot metadata."""
+
+from typing import List, Optional
+
+import pyarrow
+
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+TABLE_TYPE = RowType(False, [
+ DataField(0, "tag_name", AtomicType("STRING", nullable=False)),
+ DataField(1, "snapshot_id", AtomicType("BIGINT", nullable=False)),
+ DataField(2, "schema_id", AtomicType("BIGINT", nullable=False)),
+ DataField(3, "commit_time", AtomicType("TIMESTAMP(3)", nullable=False)),
+ DataField(4, "record_count", AtomicType("BIGINT", nullable=True)),
+ DataField(5, "create_time", AtomicType("TIMESTAMP(3)", nullable=True)),
+ DataField(6, "time_retained", AtomicType("STRING", nullable=True)),
+])
+
+
+_TIMESTAMP_TYPE = pyarrow.timestamp("ms")
+
+
+class TagsTable(SystemTable):
+ """The ``$tags`` system table."""
+
+ def system_table_name(self) -> str:
+ return "tags"
+
+ def row_type(self) -> RowType:
+ return TABLE_TYPE
+
+ def primary_keys(self) -> List[str]:
+ return ["tag_name"]
+
+ def _build_arrow_table(self) -> pyarrow.Table:
+ tag_manager = self.base_table.tag_manager()
+
+ names: List[str] = []
+ snapshot_ids: List[int] = []
+ schema_ids: List[int] = []
+ commit_times: List[int] = []
+ record_counts: List[Optional[int]] = []
+ create_times: List[Optional[int]] = []
+ time_retained: List[Optional[str]] = []
+
+ for name in tag_manager.list_tags():
+ tag = tag_manager.get(name)
+ if tag is None:
+ continue
+ names.append(name)
+ snapshot_ids.append(int(tag.id))
+ schema_ids.append(int(tag.schema_id))
+ commit_times.append(int(tag.time_millis))
+ record_counts.append(
+ None if tag.total_record_count is None
+ else int(tag.total_record_count))
+ # TODO: surface create_time and time_retained once the Tag
+ # dataclass carries them.
+ create_times.append(None)
+ time_retained.append(None)
+
+ return pyarrow.table({
+ "tag_name": pyarrow.array(names, type=pyarrow.string()),
+ "snapshot_id": pyarrow.array(snapshot_ids, type=pyarrow.int64()),
+ "schema_id": pyarrow.array(schema_ids, type=pyarrow.int64()),
+ "commit_time": pyarrow.array(commit_times, type=_TIMESTAMP_TYPE),
+ "record_count": pyarrow.array(record_counts, type=pyarrow.int64()),
+ "create_time": pyarrow.array(create_times, type=_TIMESTAMP_TYPE),
+ "time_retained": pyarrow.array(time_retained, type=pyarrow.string()),
+ })
diff --git a/paimon-python/pypaimon/tests/system/__init__.py b/paimon-python/pypaimon/tests/system/__init__.py
new file mode 100644
index 0000000000..13a83393a9
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git a/paimon-python/pypaimon/tests/system/branches_table_test.py b/paimon-python/pypaimon/tests/system/branches_table_test.py
new file mode 100644
index 0000000000..bfd8f9ef9d
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/branches_table_test.py
@@ -0,0 +1,121 @@
+# 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.
+
+"""End-to-end tests for the ``$branches`` system table."""
+
+import datetime
+import os
+import shutil
+import tempfile
+import time
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.common.json_util import JSON
+from pypaimon.schema.data_types import DataField
+from pypaimon.snapshot.snapshot import Snapshot
+from pypaimon.table.system.branches_table import BranchesTable
+
+
+def _seed_snapshot(table):
+ snapshot_dir = "{}/snapshot".format(table.table_path)
+ table.file_io.mkdirs(snapshot_dir)
+ snapshot = Snapshot(
+ version=3,
+ id=1,
+ schema_id=0,
+ base_manifest_list="base.avro",
+ delta_manifest_list="delta.avro",
+ total_record_count=0,
+ delta_record_count=0,
+ commit_user="seed",
+ commit_identifier=1,
+ commit_kind="APPEND",
+ time_millis=int(time.time() * 1000),
+ )
+ table.file_io.try_to_write_atomic(
+ "{}/snapshot-1".format(snapshot_dir), JSON.to_json(snapshot))
+ table.file_io.try_to_write_atomic(
+ "{}/LATEST".format(snapshot_dir), "1")
+ table.file_io.try_to_write_atomic(
+ "{}/EARLIEST".format(snapshot_dir), "1")
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class BranchesTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="branches_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [DataField.from_dict({"id": 0, "name": "v", "type": "INT"})]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+ self.table = self.catalog.get_table("db.t")
+ _seed_snapshot(self.table)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_branches_table_loaded_via_catalog(self):
+ table = self.catalog.get_table("db.t$branches")
+ self.assertIsInstance(table, BranchesTable)
+
+ def test_schema_column_layout(self):
+ table = self.catalog.get_table("db.t$branches")
+ row_type = table.row_type()
+ self.assertEqual(["branch_name", "create_time"],
+ [f.name for f in row_type.fields])
+ for field in row_type.fields:
+ self.assertFalse(field.type.nullable,
+ "{} should be NOT NULL".format(field.name))
+ self.assertEqual(["branch_name"], table.primary_keys())
+
+ def test_empty_when_no_branches_exist(self):
+ arrow_table = _read(self.catalog.get_table("db.t$branches"))
+ self.assertEqual(0, arrow_table.num_rows)
+ self.assertEqual(["branch_name", "create_time"],
+ arrow_table.schema.names)
+
+ def test_lists_every_branch_with_create_time(self):
+ before = int(time.time() * 1000)
+ self.table.branch_manager().create_branch("dev")
+ self.table.branch_manager().create_branch("staging")
+ after = int(time.time() * 1000)
+
+ arrow_table = _read(self.catalog.get_table("db.t$branches"))
+ names = arrow_table.column("branch_name").to_pylist()
+ self.assertEqual({"dev", "staging"}, set(names))
+
+ for ts in arrow_table.column("create_time").to_pylist():
+ # PyArrow timestamp values surface as naive datetimes that
+ # encode milliseconds since the UTC epoch; reattach the
+ # timezone before converting back to compare with the
+ # int(time.time() * 1000) bracket.
+ self.assertIsInstance(ts, datetime.datetime)
+ ms = int(ts.replace(
+ tzinfo=datetime.timezone.utc).timestamp() * 1000)
+ self.assertGreaterEqual(ms, before - 5000)
+ self.assertLessEqual(ms, after + 5000)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/files_table_test.py b/paimon-python/pypaimon/tests/system/files_table_test.py
new file mode 100644
index 0000000000..5d6b794472
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/files_table_test.py
@@ -0,0 +1,153 @@
+# 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.
+
+"""End-to-end tests for the ``$files`` system table."""
+
+import json
+import os
+import shutil
+import tempfile
+import unittest
+
+import pyarrow as pa
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.schema.data_types import DataField
+from pypaimon.table.system.files_table import FilesTable
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class FilesTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="files_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def _create_partitioned_table(self):
+ fields = [
+ DataField.from_dict({"id": 0, "name": "id", "type": "INT"}),
+ DataField.from_dict({"id": 1, "name": "v", "type": "STRING"}),
+ DataField.from_dict({"id": 2, "name": "dt", "type": "STRING"}),
+ ]
+ self.catalog.create_table(
+ "db.t",
+ Schema(fields=fields, partition_keys=["dt"]),
+ False,
+ )
+
+ def _write_two_partitions(self):
+ table = self.catalog.get_table("db.t")
+ write_builder = table.new_batch_write_builder()
+ writer = write_builder.new_write()
+ commit = write_builder.new_commit()
+ writer.write_arrow(pa.table({
+ "id": pa.array([1, 2, 3], type=pa.int32()),
+ "v": ["a", "b", "c"],
+ "dt": ["2024-01-01", "2024-01-01", "2024-01-02"],
+ }))
+ commit.commit(writer.prepare_commit())
+ writer.close()
+ commit.close()
+
+ def test_files_table_loaded_via_catalog(self):
+ self._create_partitioned_table()
+ table = self.catalog.get_table("db.t$files")
+ self.assertIsInstance(table, FilesTable)
+
+ def test_schema_column_layout(self):
+ self._create_partitioned_table()
+ table = self.catalog.get_table("db.t$files")
+ row_type = table.row_type()
+ expected = [
+ ("partition", True), ("bucket", False),
+ ("file_path", False), ("file_format", False),
+ ("schema_id", False), ("level", False),
+ ("record_count", False), ("file_size_in_bytes", False),
+ ("min_key", True), ("max_key", True),
+ ("null_value_counts", False),
+ ("min_value_stats", False), ("max_value_stats", False),
+ ("min_sequence_number", True), ("max_sequence_number", True),
+ ("creation_time", True), ("deleteRowCount", True),
+ ("file_source", True), ("first_row_id", True),
+ ("write_cols", True),
+ ]
+ self.assertEqual([n for n, _ in expected],
+ [f.name for f in row_type.fields])
+ for field, (_, expected_nullable) in zip(row_type.fields, expected):
+ self.assertEqual(expected_nullable, field.type.nullable,
+ "field {} nullability".format(field.name))
+ self.assertEqual(["file_path"], table.primary_keys())
+
+ def test_empty_when_no_snapshot_exists(self):
+ self._create_partitioned_table()
+ arrow_table = _read(self.catalog.get_table("db.t$files"))
+ self.assertEqual(0, arrow_table.num_rows)
+
+ def test_lists_files_with_partition_aggregation(self):
+ self._create_partitioned_table()
+ self._write_two_partitions()
+
+ arrow_table = _read(self.catalog.get_table("db.t$files"))
+ self.assertGreater(arrow_table.num_rows, 0)
+
+ # One row per file; partitions captured as `pt=value` strings.
+ partitions = set(arrow_table.column("partition").to_pylist())
+ self.assertIn("dt=2024-01-01", partitions)
+ self.assertIn("dt=2024-01-02", partitions)
+
+ for path in arrow_table.column("file_path").to_pylist():
+ self.assertTrue(path)
+ for record_count in arrow_table.column("record_count").to_pylist():
+ self.assertGreater(record_count, 0)
+ for size in arrow_table.column("file_size_in_bytes").to_pylist():
+ self.assertGreater(size, 0)
+
+ # Stats columns are JSON dicts keyed by column name.
+ for value in arrow_table.column("null_value_counts").to_pylist():
+ self.assertIsInstance(value, str)
+ decoded = json.loads(value)
+ self.assertIsInstance(decoded, dict)
+ for value in arrow_table.column("min_value_stats").to_pylist():
+ self.assertIsInstance(value, str)
+ self.assertIsInstance(json.loads(value), dict)
+ for value in arrow_table.column("max_value_stats").to_pylist():
+ self.assertIsInstance(value, str)
+ self.assertIsInstance(json.loads(value), dict)
+
+ # Append-only tables expose empty min_key / max_key.
+ for value in arrow_table.column("min_key").to_pylist():
+ self.assertIsNone(value)
+ for value in arrow_table.column("max_key").to_pylist():
+ self.assertIsNone(value)
+
+ for fmt in arrow_table.column("file_format").to_pylist():
+ self.assertTrue(fmt)
+ for level in arrow_table.column("level").to_pylist():
+ self.assertGreaterEqual(level, 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/list_tables_no_system_test.py b/paimon-python/pypaimon/tests/system/list_tables_no_system_test.py
new file mode 100644
index 0000000000..7df6a3ba3d
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/list_tables_no_system_test.py
@@ -0,0 +1,69 @@
+# 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.
+
+"""Regression: list_tables must not surface table-level system tables.
+
+System tables are accessible by name via ``get_table('db.t$<name>')``
+but they don't belong in directory listings. The test below pins both
+halves of that behaviour for FilesystemCatalog.
+"""
+
+import os
+import shutil
+import tempfile
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.schema.data_types import DataField
+from pypaimon.table.system import system_table_loader
+from pypaimon.table.system.system_table import SystemTable
+
+
+class ListTablesNoSystemTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="list_no_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [DataField.from_dict({"id": 0, "name": "v", "type": "INT"})]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_list_tables_does_not_include_system_table_suffixes(self):
+ names = self.catalog.list_tables("db")
+ self.assertIn("t", names)
+ for name in names:
+ self.assertNotIn(
+ "$", name,
+ "list_tables surfaced a system-table suffix: " + name)
+
+ def test_get_table_still_works_for_every_registered_system_table(self):
+ # Each registered system table should be retrievable by full
+ # identifier even though list_tables hid them; this proves the
+ # contract is consistent end-to-end.
+ for name in system_table_loader.SYSTEM_TABLES:
+ sys_table = self.catalog.get_table("db.t${}".format(name))
+ self.assertIsInstance(
+ sys_table, SystemTable,
+ "system table {} did not return a SystemTable".format(name))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/manager_extensions_test.py b/paimon-python/pypaimon/tests/system/manager_extensions_test.py
new file mode 100644
index 0000000000..69c1bdfc3f
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/manager_extensions_test.py
@@ -0,0 +1,140 @@
+# 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.
+
+"""Tests for the manager-level helpers that back system tables.
+
+The snapshots / schemas system tables need bulk-listing helpers that
+the corresponding managers had not surfaced. This file pins down
+their contracts:
+
+* :meth:`SnapshotManager.list_snapshots` — enumerate persisted
+ snapshots in ID order, skipping IDs whose files have been expired.
+* :meth:`SchemaManager.list_all` — return every committed table
+ schema in ID order.
+"""
+
+import os
+import shutil
+import tempfile
+import time
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.common.file_io import FileIO
+from pypaimon.common.json_util import JSON
+from pypaimon.schema.data_types import DataField
+from pypaimon.schema.schema_change import SchemaChange
+from pypaimon.snapshot.snapshot import Snapshot
+from pypaimon.snapshot.snapshot_manager import SnapshotManager
+
+
+def _write_snapshot(file_io: FileIO, snapshot_dir: str, snapshot_id: int,
+ schema_id: int = 0):
+ """Write a minimal snapshot JSON to ``snapshot_dir``."""
+ snapshot = Snapshot(
+ version=3,
+ id=snapshot_id,
+ schema_id=schema_id,
+ base_manifest_list="base-{}.avro".format(snapshot_id),
+ delta_manifest_list="delta-{}.avro".format(snapshot_id),
+ total_record_count=0,
+ delta_record_count=0,
+ commit_user="test-user",
+ commit_identifier=snapshot_id,
+ commit_kind="APPEND",
+ time_millis=int(time.time() * 1000),
+ )
+ file_io.try_to_write_atomic(
+ "{}/snapshot-{}".format(snapshot_dir, snapshot_id),
+ JSON.to_json(snapshot),
+ )
+
+
+def _new_warehouse():
+ tmp = tempfile.mkdtemp(prefix="mgrext_")
+ return tmp, os.path.join(tmp, "warehouse")
+
+
+class SnapshotManagerListSnapshotsTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp, self.warehouse = _new_warehouse()
+ self.catalog = CatalogFactory.create({"warehouse": self.warehouse})
+ self.catalog.create_database("db", False)
+ fields = [DataField.from_dict({"id": 0, "name": "v", "type": "INT"})]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+ self.table = self.catalog.get_table("db.t")
+ self.file_io = self.table.file_io
+ self.snapshot_dir = "{}/snapshot".format(self.table.table_path)
+ self.file_io.mkdirs(self.snapshot_dir)
+ self.manager = SnapshotManager(
+ self.file_io, self.table.table_path, branch="main"
+ )
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_empty_table_returns_empty_list(self):
+ self.assertEqual([], self.manager.list_snapshots())
+
+ def test_lists_persisted_snapshots_in_id_order(self):
+ for sid in (3, 1, 2): # write out of order to prove sort
+ _write_snapshot(self.file_io, self.snapshot_dir, sid)
+ result = self.manager.list_snapshots()
+ self.assertEqual([1, 2, 3], [s.id for s in result])
+
+ def test_skips_gaps_from_expired_snapshots(self):
+ # snapshot-2 missing — simulates an expired ID still bracketed by
+ # earlier and later live snapshots.
+ for sid in (1, 3):
+ _write_snapshot(self.file_io, self.snapshot_dir, sid)
+ result = self.manager.list_snapshots()
+ self.assertEqual([1, 3], [s.id for s in result])
+
+
+class SchemaManagerListAllTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp, self.warehouse = _new_warehouse()
+ self.catalog = CatalogFactory.create({"warehouse": self.warehouse})
+ self.catalog.create_database("db", False)
+ fields = [
+ DataField.from_dict({"id": 0, "name": "v", "type": "INT"}),
+ ]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+ self.manager = self.catalog.get_table("db.t").schema_manager
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_returns_single_schema_initially(self):
+ result = self.manager.list_all()
+ self.assertEqual([0], [s.id for s in result])
+
+ def test_lists_every_committed_schema_in_id_order(self):
+ for new_value in ("a", "b", "c"):
+ self.manager.commit_changes([SchemaChange.set_option(
+ "user-tag", new_value)])
+ result = self.manager.list_all()
+ self.assertEqual([0, 1, 2, 3], [s.id for s in result])
+ # Cache shouldn't return stale objects across calls.
+ again = self.manager.list_all()
+ self.assertEqual([0, 1, 2, 3], [s.id for s in again])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/manifests_table_test.py b/paimon-python/pypaimon/tests/system/manifests_table_test.py
new file mode 100644
index 0000000000..825ae23934
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/manifests_table_test.py
@@ -0,0 +1,112 @@
+# 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.
+
+"""End-to-end tests for the ``$manifests`` system table."""
+
+import os
+import shutil
+import tempfile
+import unittest
+
+import pyarrow as pa
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.schema.data_types import DataField
+from pypaimon.table.system.manifests_table import ManifestsTable
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class ManifestsTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="manifests_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [
+ DataField.from_dict({"id": 0, "name": "id", "type": "INT"}),
+ DataField.from_dict({"id": 1, "name": "v", "type": "STRING"}),
+ ]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+ self.table = self.catalog.get_table("db.t")
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def _write_one_commit(self):
+ write_builder = self.table.new_batch_write_builder()
+ writer = write_builder.new_write()
+ commit = write_builder.new_commit()
+ writer.write_arrow(pa.table({
+ "id": pa.array([1, 2], type=pa.int32()),
+ "v": ["a", "b"],
+ }))
+ commit.commit(writer.prepare_commit())
+ writer.close()
+ commit.close()
+
+ def test_manifests_table_loaded_via_catalog(self):
+ table = self.catalog.get_table("db.t$manifests")
+ self.assertIsInstance(table, ManifestsTable)
+
+ def test_schema_column_layout(self):
+ table = self.catalog.get_table("db.t$manifests")
+ row_type = table.row_type()
+ expected = [
+ ("file_name", False), ("file_size", False),
+ ("num_added_files", False), ("num_deleted_files", False),
+ ("schema_id", False), ("min_partition_stats", True),
+ ("max_partition_stats", True), ("min_row_id", True),
+ ("max_row_id", True),
+ ]
+ self.assertEqual([n for n, _ in expected],
+ [f.name for f in row_type.fields])
+ for field, (_, expected_nullable) in zip(row_type.fields, expected):
+ self.assertEqual(expected_nullable, field.type.nullable,
+ "field {} nullability".format(field.name))
+ self.assertEqual(["file_name"], table.primary_keys())
+
+ def test_empty_when_no_snapshot_exists(self):
+ arrow_table = _read(self.catalog.get_table("db.t$manifests"))
+ self.assertEqual(0, arrow_table.num_rows)
+
+ def test_lists_manifests_of_latest_snapshot(self):
+ self._write_one_commit()
+ arrow_table = _read(self.catalog.get_table("db.t$manifests"))
+ self.assertGreater(arrow_table.num_rows, 0)
+
+ for name in arrow_table.column("file_name").to_pylist():
+ self.assertTrue(name)
+ for size in arrow_table.column("file_size").to_pylist():
+ self.assertGreater(size, 0)
+ for n_added in arrow_table.column("num_added_files").to_pylist():
+ self.assertGreaterEqual(n_added, 0)
+
+ # min/max_partition_stats are placeholders until the partition
+ # cast-to-string helper lands; pin the placeholder contract.
+ for value in arrow_table.column("min_partition_stats").to_pylist():
+ self.assertIsNone(value)
+ for value in arrow_table.column("max_partition_stats").to_pylist():
+ self.assertIsNone(value)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/options_table_test.py b/paimon-python/pypaimon/tests/system/options_table_test.py
new file mode 100644
index 0000000000..c78b79e701
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/options_table_test.py
@@ -0,0 +1,88 @@
+# 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.
+
+"""End-to-end tests for the ``$options`` system table."""
+
+import os
+import shutil
+import tempfile
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.schema.data_types import DataField
+from pypaimon.table.system.options_table import OptionsTable
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class OptionsTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="opts_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [DataField.from_dict({"id": 0, "name": "v", "type": "INT"})]
+ self.catalog.create_table(
+ "db.t",
+ Schema(fields=fields, options={
+ "bucket": "2",
+ "user-flag": "alpha",
+ }),
+ False,
+ )
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_options_table_is_loaded_via_catalog(self):
+ table = self.catalog.get_table("db.t$options")
+ self.assertIsInstance(table, OptionsTable)
+
+ def test_schema_column_layout(self):
+ table = self.catalog.get_table("db.t$options")
+ row_type = table.row_type()
+ self.assertEqual(["key", "value"], [f.name for f in row_type.fields])
+ for field in row_type.fields:
+ self.assertFalse(field.type.nullable,
+ "{} should be NOT NULL".format(field.name))
+ self.assertEqual(["key"], table.primary_keys())
+
+ def test_read_returns_every_committed_option(self):
+ table = self.catalog.get_table("db.t$options")
+ arrow_table = _read(table)
+ self.assertEqual(["key", "value"], arrow_table.schema.names)
+ rendered = dict(zip(
+ arrow_table.column("key").to_pylist(),
+ arrow_table.column("value").to_pylist(),
+ ))
+ self.assertEqual("2", rendered["bucket"])
+ self.assertEqual("alpha", rendered["user-flag"])
+
+ def test_read_with_projection_keeps_requested_column_only(self):
+ table = self.catalog.get_table("db.t$options")
+ rb = table.new_read_builder().with_projection(["key"])
+ arrow_table = rb.new_read().to_arrow(rb.new_scan().plan().splits())
+ self.assertEqual(["key"], arrow_table.schema.names)
+ self.assertIn("bucket", arrow_table.column("key").to_pylist())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/partitions_table_test.py b/paimon-python/pypaimon/tests/system/partitions_table_test.py
new file mode 100644
index 0000000000..8f07fd5f2a
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/partitions_table_test.py
@@ -0,0 +1,132 @@
+# 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.
+
+"""End-to-end tests for the ``$partitions`` system table."""
+
+import os
+import shutil
+import tempfile
+import unittest
+
+import pyarrow as pa
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.schema.data_types import DataField
+from pypaimon.table.system.partitions_table import PartitionsTable
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class PartitionsTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="partitions_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def _create_partitioned_table(self):
+ fields = [
+ DataField.from_dict({"id": 0, "name": "id", "type": "INT"}),
+ DataField.from_dict({"id": 1, "name": "v", "type": "STRING"}),
+ DataField.from_dict({"id": 2, "name": "dt", "type": "STRING"}),
+ ]
+ self.catalog.create_table(
+ "db.t",
+ Schema(fields=fields, partition_keys=["dt"]),
+ False,
+ )
+
+ def _write_two_partitions(self):
+ table = self.catalog.get_table("db.t")
+ write_builder = table.new_batch_write_builder()
+ writer = write_builder.new_write()
+ commit = write_builder.new_commit()
+ writer.write_arrow(pa.table({
+ "id": pa.array([1, 2, 3], type=pa.int32()),
+ "v": ["a", "b", "c"],
+ "dt": ["2024-01-01", "2024-01-01", "2024-01-02"],
+ }))
+ commit.commit(writer.prepare_commit())
+ writer.close()
+ commit.close()
+
+ def test_partitions_table_loaded_via_catalog(self):
+ self._create_partitioned_table()
+ table = self.catalog.get_table("db.t$partitions")
+ self.assertIsInstance(table, PartitionsTable)
+
+ def test_schema_column_layout(self):
+ self._create_partitioned_table()
+ table = self.catalog.get_table("db.t$partitions")
+ row_type = table.row_type()
+ expected = [
+ ("partition", True), ("record_count", False),
+ ("file_size_in_bytes", False), ("file_count", False),
+ ("last_update_time", True), ("created_at", True),
+ ("created_by", True), ("updated_by", True),
+ ("options", True), ("total_buckets", False),
+ ("done", False),
+ ]
+ self.assertEqual([n for n, _ in expected],
+ [f.name for f in row_type.fields])
+ for field, (_, expected_nullable) in zip(row_type.fields, expected):
+ self.assertEqual(expected_nullable, field.type.nullable,
+ "field {} nullability".format(field.name))
+ self.assertEqual(["partition"], table.primary_keys())
+
+ def test_empty_when_no_snapshot_exists(self):
+ self._create_partitioned_table()
+ arrow_table = _read(self.catalog.get_table("db.t$partitions"))
+ self.assertEqual(0, arrow_table.num_rows)
+
+ def test_aggregates_partitions_after_commit(self):
+ self._create_partitioned_table()
+ self._write_two_partitions()
+
+ arrow_table = _read(self.catalog.get_table("db.t$partitions"))
+ partitions = arrow_table.column("partition").to_pylist()
+ self.assertEqual({"dt=2024-01-01", "dt=2024-01-02"}, set(partitions))
+
+ record_counts = dict(zip(
+ partitions, arrow_table.column("record_count").to_pylist()))
+ self.assertEqual(2, record_counts["dt=2024-01-01"])
+ self.assertEqual(1, record_counts["dt=2024-01-02"])
+
+ for size in arrow_table.column("file_size_in_bytes").to_pylist():
+ self.assertGreater(size, 0)
+ for count in arrow_table.column("file_count").to_pylist():
+ self.assertGreaterEqual(count, 1)
+ for total_buckets in arrow_table.column("total_buckets").to_pylist():
+ self.assertGreaterEqual(total_buckets, 1)
+ # FileSystem catalog does not maintain a "done" flag.
+ for done in arrow_table.column("done").to_pylist():
+ self.assertFalse(done)
+ # Catalog-managed fields are not surfaced by the filesystem path.
+ for field in ("created_by", "updated_by", "options", "created_at"):
+ for value in arrow_table.column(field).to_pylist():
+ self.assertIsNone(value)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/schemas_table_test.py b/paimon-python/pypaimon/tests/system/schemas_table_test.py
new file mode 100644
index 0000000000..2b0bdee18f
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/schemas_table_test.py
@@ -0,0 +1,115 @@
+# 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.
+
+"""End-to-end tests for the ``$schemas`` system table."""
+
+import datetime
+import json
+import os
+import shutil
+import tempfile
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.schema.data_types import DataField
+from pypaimon.schema.schema_change import SchemaChange
+from pypaimon.table.system.schemas_table import SchemasTable
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class SchemasTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="schemas_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [
+ DataField.from_dict({"id": 0, "name": "id", "type": "INT"}),
+ DataField.from_dict({"id": 1, "name": "name", "type": "STRING"}),
+ ]
+ self.catalog.create_table(
+ "db.t",
+ Schema(fields=fields,
+ options={"user-flag": "alpha"},
+ comment="initial table"),
+ False,
+ )
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_schemas_table_loaded_via_catalog(self):
+ table = self.catalog.get_table("db.t$schemas")
+ self.assertIsInstance(table, SchemasTable)
+
+ def test_schema_column_layout(self):
+ table = self.catalog.get_table("db.t$schemas")
+ row_type = table.row_type()
+ self.assertEqual(
+ ["schema_id", "fields", "partition_keys", "primary_keys",
+ "options", "comment", "update_time"],
+ [f.name for f in row_type.fields],
+ )
+ expected_nullability = [False, False, False, False, False, True, False]
+ for field, expected in zip(row_type.fields, expected_nullability):
+ self.assertEqual(expected, field.type.nullable,
+ "field {} nullability".format(field.name))
+ self.assertEqual(["schema_id"], table.primary_keys())
+
+ def test_lists_every_committed_schema_in_id_order(self):
+ # Mutate the schema a couple of times so list_all() returns more
+ # than one row.
+ table = self.catalog.get_table("db.t")
+ table.schema_manager.commit_changes(
+ [SchemaChange.set_option("user-flag", "beta")])
+ table.schema_manager.commit_changes(
+ [SchemaChange.set_option("user-flag", "gamma")])
+
+ arrow_table = _read(self.catalog.get_table("db.t$schemas"))
+ self.assertEqual([0, 1, 2],
+ arrow_table.column("schema_id").to_pylist())
+
+ fields_json = arrow_table.column("fields").to_pylist()[0]
+ decoded = json.loads(fields_json)
+ self.assertEqual(["id", "name"], [f["name"] for f in decoded])
+
+ options_jsons = arrow_table.column("options").to_pylist()
+ self.assertEqual("alpha", json.loads(options_jsons[0])["user-flag"])
+ self.assertEqual("beta", json.loads(options_jsons[1])["user-flag"])
+ self.assertEqual("gamma", json.loads(options_jsons[2])["user-flag"])
+
+ comments = arrow_table.column("comment").to_pylist()
+ self.assertEqual("initial table", comments[0])
+
+ for ts in arrow_table.column("update_time").to_pylist():
+ self.assertIsInstance(ts, datetime.datetime)
+
+ def test_empty_arrays_serialize_to_json_lists(self):
+ arrow_table = _read(self.catalog.get_table("db.t$schemas"))
+ self.assertEqual("[]",
+ arrow_table.column("partition_keys").to_pylist()[0])
+ self.assertEqual("[]",
+ arrow_table.column("primary_keys").to_pylist()[0])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/snapshots_table_test.py b/paimon-python/pypaimon/tests/system/snapshots_table_test.py
new file mode 100644
index 0000000000..4e3e637c07
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/snapshots_table_test.py
@@ -0,0 +1,165 @@
+# 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.
+
+"""End-to-end tests for the ``$snapshots`` system table."""
+
+import datetime
+import os
+import shutil
+import tempfile
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.common.json_util import JSON
+from pypaimon.schema.data_types import DataField
+from pypaimon.snapshot.snapshot import Snapshot
+from pypaimon.table.system.snapshots_table import SnapshotsTable
+
+
+_T0 = 1779100000000
+_T1 = 1779100050000
+
+
+def _write(table, snapshot):
+ snapshot_dir = "{}/snapshot".format(table.table_path)
+ table.file_io.mkdirs(snapshot_dir)
+ table.file_io.try_to_write_atomic(
+ "{}/snapshot-{}".format(snapshot_dir, snapshot.id),
+ JSON.to_json(snapshot),
+ )
+
+
+def _seed_two_snapshots(table):
+ snapshot_one = Snapshot(
+ version=3,
+ id=1,
+ schema_id=0,
+ base_manifest_list="base-1.avro",
+ delta_manifest_list="delta-1.avro",
+ total_record_count=10,
+ delta_record_count=10,
+ commit_user="alice",
+ commit_identifier=100,
+ commit_kind="APPEND",
+ time_millis=_T0,
+ watermark=7,
+ )
+ snapshot_two = Snapshot(
+ version=3,
+ id=2,
+ schema_id=1,
+ base_manifest_list="base-2.avro",
+ delta_manifest_list="delta-2.avro",
+ total_record_count=25,
+ delta_record_count=15,
+ commit_user="bob",
+ commit_identifier=200,
+ commit_kind="OVERWRITE",
+ time_millis=_T1,
+ changelog_manifest_list="cl-2.avro",
+ changelog_record_count=3,
+ )
+ _write(table, snapshot_one)
+ _write(table, snapshot_two)
+ table.file_io.try_to_write_atomic(
+ "{}/snapshot/EARLIEST".format(table.table_path), "1")
+ table.file_io.try_to_write_atomic(
+ "{}/snapshot/LATEST".format(table.table_path), "2")
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class SnapshotsTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="snapshots_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [DataField.from_dict({"id": 0, "name": "v", "type": "INT"})]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+ self.table = self.catalog.get_table("db.t")
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_snapshots_table_loaded_via_catalog(self):
+ table = self.catalog.get_table("db.t$snapshots")
+ self.assertIsInstance(table, SnapshotsTable)
+
+ def test_schema_column_layout(self):
+ table = self.catalog.get_table("db.t$snapshots")
+ row_type = table.row_type()
+ expected = [
+ ("snapshot_id", False), ("schema_id", False),
+ ("commit_user", False), ("commit_identifier", False),
+ ("commit_kind", False), ("commit_time", False),
+ ("base_manifest_list", False), ("delta_manifest_list", False),
+ ("changelog_manifest_list", True),
+ ("total_record_count", True), ("delta_record_count", True),
+ ("changelog_record_count", True), ("watermark", True),
+ ("next_row_id", True),
+ ]
+ self.assertEqual([n for n, _ in expected],
+ [f.name for f in row_type.fields])
+ for field, (_, expected_nullable) in zip(row_type.fields, expected):
+ self.assertEqual(expected_nullable, field.type.nullable,
+ "field {} nullability".format(field.name))
+ self.assertEqual(["snapshot_id"], table.primary_keys())
+
+ def test_empty_table_returns_no_rows(self):
+ arrow_table = _read(self.catalog.get_table("db.t$snapshots"))
+ self.assertEqual(0, arrow_table.num_rows)
+
+ def test_lists_committed_snapshots_in_id_order(self):
+ _seed_two_snapshots(self.table)
+
+ arrow_table = _read(self.catalog.get_table("db.t$snapshots"))
+ self.assertEqual([1, 2], arrow_table.column("snapshot_id").to_pylist())
+ self.assertEqual([0, 1], arrow_table.column("schema_id").to_pylist())
+ self.assertEqual(["alice", "bob"],
+ arrow_table.column("commit_user").to_pylist())
+ self.assertEqual(["APPEND", "OVERWRITE"],
+ arrow_table.column("commit_kind").to_pylist())
+ self.assertEqual([100, 200],
+ arrow_table.column("commit_identifier").to_pylist())
+ self.assertEqual([10, 25],
+ arrow_table.column("total_record_count").to_pylist())
+ self.assertEqual([10, 15],
+ arrow_table.column("delta_record_count").to_pylist())
+ # Nullable columns: row 1 has watermark, row 2 has changelog.
+ self.assertEqual([7, None],
+ arrow_table.column("watermark").to_pylist())
+ self.assertEqual([None, "cl-2.avro"],
+ arrow_table.column("changelog_manifest_list").to_pylist())
+ self.assertEqual([None, 3],
+ arrow_table.column("changelog_record_count").to_pylist())
+ self.assertEqual([None, None],
+ arrow_table.column("next_row_id").to_pylist())
+
+ times = arrow_table.column("commit_time").to_pylist()
+ self.assertIsInstance(times[0], datetime.datetime)
+ as_ms = [int(t.replace(tzinfo=datetime.timezone.utc).timestamp() * 1000)
+ for t in times]
+ self.assertEqual([_T0, _T1], as_ms)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/system_read_pipeline_test.py b/paimon-python/pypaimon/tests/system/system_read_pipeline_test.py
new file mode 100644
index 0000000000..6700325b61
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/system_read_pipeline_test.py
@@ -0,0 +1,159 @@
+# 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.
+
+"""Tests for the in-memory SystemReadBuilder / Scan / Read pipeline.
+
+These exercise the duck-typed surface so callers can reach for
+``rb.with_filter / with_projection / with_limit / new_scan / new_read``
+exactly as they would on a regular data table.
+"""
+
+import types
+import unittest
+
+import pyarrow as pa
+
+from pypaimon.common.identifier import Identifier
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemReadBuilder, SystemTable
+from pypaimon.table.system.system_table_scan import SystemSplit, SystemTableScan
+from pypaimon.table.system.system_table_read import SystemTableRead
+
+
+_DUMMY_ROW_TYPE = RowType(False, [
+ DataField(0, "c1", AtomicType("STRING", nullable=False)),
+ DataField(1, "c2", AtomicType("BIGINT", nullable=False)),
+])
+
+
+class _DummySystemTable(SystemTable):
+ """Returns a 3-row table for pipeline tests."""
+
+ def system_table_name(self) -> str:
+ return "dummy"
+
+ def row_type(self) -> RowType:
+ return _DUMMY_ROW_TYPE
+
+ def _build_arrow_table(self):
+ return pa.table({"c1": ["a", "b", "c"], "c2": [1, 2, 3]})
+
+
+def _fake_base():
+ return types.SimpleNamespace(
+ identifier=Identifier.create("db", "t"),
+ file_io=object(),
+ table_path="/tmp/db/t",
+ )
+
+
+class SystemReadPipelineTest(unittest.TestCase):
+
+ def setUp(self):
+ self.table = _DummySystemTable(_fake_base())
+
+ def _splits_and_read(self, rb):
+ return rb.new_read(), rb.new_scan().plan().splits()
+
+ def test_new_read_builder_returns_system_read_builder(self):
+ self.assertIsInstance(self.table.new_read_builder(), SystemReadBuilder)
+
+ def test_scan_produces_single_in_memory_split(self):
+ rb = self.table.new_read_builder()
+ splits = rb.new_scan().plan().splits()
+ self.assertEqual(1, len(splits))
+ self.assertIsInstance(splits[0], SystemSplit)
+ self.assertEqual(3, splits[0].row_count)
+ self.assertEqual([], splits[0].files)
+ self.assertIsNone(splits[0].partition)
+ self.assertEqual(-1, splits[0].bucket)
+
+ def test_default_read_returns_full_arrow_table(self):
+ rb = self.table.new_read_builder()
+ read, splits = self._splits_and_read(rb)
+ result = read.to_arrow(splits)
+ self.assertEqual(["c1", "c2"], result.schema.names)
+ self.assertEqual(3, result.num_rows)
+ self.assertEqual(["a", "b", "c"], result.column("c1").to_pylist())
+ self.assertEqual([1, 2, 3], result.column("c2").to_pylist())
+
+ def test_with_projection_drops_columns(self):
+ rb = self.table.new_read_builder().with_projection(["c1"])
+ read, splits = self._splits_and_read(rb)
+ result = read.to_arrow(splits)
+ self.assertEqual(["c1"], result.schema.names)
+ self.assertEqual(3, result.num_rows)
+
+ def test_projection_silently_skips_unknown_columns(self):
+ # Mirrors ReadBuilder.with_projection contract: unknown names
+ # are dropped rather than failing eagerly.
+ rb = self.table.new_read_builder().with_projection(["c2", "no_such"])
+ read, splits = self._splits_and_read(rb)
+ result = read.to_arrow(splits)
+ self.assertEqual(["c2"], result.schema.names)
+
+ def test_with_limit_truncates_rows(self):
+ rb = self.table.new_read_builder().with_limit(1)
+ read, splits = self._splits_and_read(rb)
+ result = read.to_arrow(splits)
+ self.assertEqual(1, result.num_rows)
+ self.assertEqual("a", result.column("c1")[0].as_py())
+
+ def test_filter_is_not_supported_yet(self):
+ rb = self.table.new_read_builder().with_filter(object())
+ read, splits = self._splits_and_read(rb)
+ with self.assertRaises(NotImplementedError):
+ read.to_arrow(splits)
+
+ def test_to_pandas_returns_dataframe(self):
+ rb = self.table.new_read_builder()
+ read, splits = self._splits_and_read(rb)
+ df = read.to_pandas(splits)
+ self.assertEqual(3, len(df))
+ self.assertEqual(["c1", "c2"], list(df.columns))
+
+ def test_to_record_batch_iterator_yields_batches(self):
+ rb = self.table.new_read_builder()
+ read, splits = self._splits_and_read(rb)
+ batches = list(read.to_record_batch_iterator(splits))
+ self.assertEqual(3, sum(b.num_rows for b in batches))
+
+ def test_to_iterator_yields_one_dict_per_row(self):
+ rb = self.table.new_read_builder()
+ read, splits = self._splits_and_read(rb)
+ rows = list(read.to_iterator(splits))
+ self.assertEqual(3, len(rows))
+ self.assertEqual({"c1", "c2"}, set(rows[0].keys()))
+ self.assertEqual("a", rows[0]["c1"])
+
+ def test_read_type_reflects_current_projection(self):
+ rb = self.table.new_read_builder()
+ self.assertEqual(["c1", "c2"], [f.name for f in rb.read_type()])
+ rb.with_projection(["c2"])
+ self.assertEqual(["c2"], [f.name for f in rb.read_type()])
+
+ def test_new_scan_returns_system_table_scan(self):
+ rb = self.table.new_read_builder()
+ self.assertIsInstance(rb.new_scan(), SystemTableScan)
+
+ def test_new_read_returns_system_table_read(self):
+ rb = self.table.new_read_builder()
+ self.assertIsInstance(rb.new_read(), SystemTableRead)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/system_table_catalog_dispatch_test.py b/paimon-python/pypaimon/tests/system/system_table_catalog_dispatch_test.py
new file mode 100644
index 0000000000..ef47e97924
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/system_table_catalog_dispatch_test.py
@@ -0,0 +1,194 @@
+# 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.
+
+"""End-to-end tests that ``Catalog.get_table`` dispatches ``$xxx`` requests
+to the SystemTableLoader and surfaces the right errors when the name is
+unknown.
+
+The dispatch must work identically for FileSystemCatalog and RESTCatalog;
+RESTCatalog coverage is added alongside the dispatch change for that
+implementation.
+"""
+
+import os
+import shutil
+import tempfile
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.catalog.catalog_exception import TableNotExistException
+from pypaimon.schema.data_types import DataField
+from pypaimon.table.file_store_table import FileStoreTable
+from pypaimon.table.system import system_table_loader
+
+
+class _FakeSystemTable:
+ """Stand-in returned by an injected SystemTableLoader factory."""
+
+ def __init__(self, base_table, marker: str):
+ self.base_table = base_table
+ self.marker = marker
+
+
+def _install_fake_factory(name: str, marker: str):
+ """Register a fake factory under ``name`` for the lifetime of a test."""
+
+ def factory(base):
+ return _FakeSystemTable(base, marker)
+
+ previous = system_table_loader.SYSTEM_TABLE_LOADERS.get(name)
+ system_table_loader.SYSTEM_TABLE_LOADERS[name] = factory
+ return previous
+
+
+def _restore_factory(name: str, previous):
+ if previous is None:
+ system_table_loader.SYSTEM_TABLE_LOADERS.pop(name, None)
+ else:
+ system_table_loader.SYSTEM_TABLE_LOADERS[name] = previous
+
+
+class FilesystemCatalogSystemTableDispatchTest(unittest.TestCase):
+
+ def setUp(self):
+ self.temp_dir = tempfile.mkdtemp(prefix="sys_dispatch_")
+ self.warehouse = os.path.join(self.temp_dir, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": self.warehouse})
+ self.catalog.create_database("db", False)
+ fields = [
+ DataField.from_dict({"id": 1, "name": "id", "type": "INT"}),
+ DataField.from_dict({"id": 2, "name": "name", "type": "STRING"}),
+ ]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+
+ def tearDown(self):
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
+
+ def test_regular_get_table_still_returns_file_store_table(self):
+ table = self.catalog.get_table("db.t")
+ self.assertIsInstance(table, FileStoreTable)
+ self.assertFalse(table.identifier.is_system_table())
+
+ def test_get_system_table_routes_through_loader(self):
+ marker = "fs-dispatch-marker"
+ previous = _install_fake_factory("snapshots", marker)
+ try:
+ sys_table = self.catalog.get_table("db.t$snapshots")
+ finally:
+ _restore_factory("snapshots", previous)
+
+ self.assertIsInstance(sys_table, _FakeSystemTable)
+ self.assertEqual(marker, sys_table.marker)
+ # The loader is passed the BASE table, not a system-table identifier.
+ self.assertIsInstance(sys_table.base_table, FileStoreTable)
+ self.assertFalse(sys_table.base_table.identifier.is_system_table())
+ self.assertEqual("t", sys_table.base_table.identifier.get_table_name())
+
+ def test_unknown_system_table_raises_table_not_exist(self):
+ # Pick a name that the registry deliberately does NOT carry.
+ with self.assertRaises(TableNotExistException):
+ self.catalog.get_table("db.t$definitely_not_a_system_table")
+
+ def test_system_table_request_for_missing_base_propagates_table_not_exist(self):
+ with self.assertRaises(TableNotExistException):
+ self.catalog.get_table("db.does_not_exist$snapshots")
+
+
+class RestCatalogSystemTableDispatchTest(unittest.TestCase):
+ """Tests that RESTCatalog.get_table dispatches identically to FileSystem.
+
+ Uses a hand-rolled lightweight stand-in instead of a live REST server:
+ the dispatch logic is pure Python and the network-bound code path
+ (``_load_data_table``) is already covered by RESTCatalog's own tests.
+ Stubbing it lets these tests stay fast and focused on the new branch.
+ """
+
+ def _build_catalog(self):
+ from pypaimon.catalog.rest.rest_catalog import RESTCatalog
+ catalog = RESTCatalog.__new__(RESTCatalog)
+
+ loaded_identifiers = []
+
+ def fake_load_data_table(identifier):
+ loaded_identifiers.append(identifier)
+ # The system-table loader only needs an object that quacks like
+ # a base table; the production factories will exercise the real
+ # FileStoreTable surface.
+ from pypaimon.common.identifier import Identifier as _Ident
+ assert isinstance(identifier, _Ident)
+ assert not identifier.is_system_table(), (
+ "dispatch must strip the $-suffix before reaching "
+ "_load_data_table; got: " + identifier.get_object_name())
+
+ class _FakeBaseTable:
+ pass
+
+ base = _FakeBaseTable()
+ base.identifier = identifier
+ return base
+
+ catalog._load_data_table = fake_load_data_table
+ return catalog, loaded_identifiers
+
+ def test_regular_get_table_calls_load_data_table_unchanged(self):
+ catalog, loaded = self._build_catalog()
+ result = catalog.get_table("db.t")
+ self.assertIsNotNone(result)
+ self.assertEqual(1, len(loaded))
+ self.assertFalse(loaded[0].is_system_table())
+ self.assertEqual("t", loaded[0].get_table_name())
+
+ def test_get_system_table_routes_through_loader(self):
+ catalog, loaded = self._build_catalog()
+ marker = "rest-dispatch-marker"
+ previous = _install_fake_factory("snapshots", marker)
+ try:
+ sys_table = catalog.get_table("db.t$snapshots")
+ finally:
+ _restore_factory("snapshots", previous)
+
+ self.assertIsInstance(sys_table, _FakeSystemTable)
+ self.assertEqual(marker, sys_table.marker)
+ # _load_data_table received the BASE identifier (no system suffix).
+ self.assertEqual(1, len(loaded))
+ self.assertFalse(loaded[0].is_system_table())
+ self.assertEqual("t", loaded[0].get_table_name())
+
+ def test_get_system_table_preserves_branch_segment(self):
+ catalog, loaded = self._build_catalog()
+ marker = "rest-dispatch-branched-marker"
+ previous = _install_fake_factory("snapshots", marker)
+ try:
+ sys_table = catalog.get_table("db.t$branch_dev$snapshots")
+ finally:
+ _restore_factory("snapshots", previous)
+
+ self.assertIsInstance(sys_table, _FakeSystemTable)
+ # The base identifier carries the branch but not the system suffix.
+ self.assertEqual(1, len(loaded))
+ self.assertFalse(loaded[0].is_system_table())
+ self.assertEqual("t", loaded[0].get_table_name())
+ self.assertEqual("dev", loaded[0].get_branch_name())
+
+ def test_unknown_system_table_raises_table_not_exist(self):
+ catalog, _ = self._build_catalog()
+ with self.assertRaises(TableNotExistException):
+ catalog.get_table("db.t$definitely_not_a_system_table")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/system_table_loader_test.py b/paimon-python/pypaimon/tests/system/system_table_loader_test.py
new file mode 100644
index 0000000000..1c8690a2bc
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/system_table_loader_test.py
@@ -0,0 +1,84 @@
+# 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.
+
+"""Tests for the SystemTableLoader registry."""
+
+import unittest
+
+from pypaimon.table.system import system_table_loader as loader
+
+_EXPECTED_SYSTEM_TABLES = (
+ "snapshots",
+ "schemas",
+ "options",
+ "manifests",
+ "files",
+ "partitions",
+ "tags",
+ "branches",
+)
+
+# Short names recognised by the Paimon catalog that this loader does
+# not register yet. The loader must not silently surface any of these.
+_UNREGISTERED_NAMES = {
+ "audit_log",
+ "binlog",
+ "read_optimized",
+ "consumers",
+ "statistics",
+ "aggregation_fields",
+ "buckets",
+ "file_key_ranges",
+ "table_indexes",
+ "row_tracking",
+ "all_tables",
+ "all_partitions",
+ "all_table_options",
+ "catalog_options",
+}
+
+
+class SystemTableLoaderTest(unittest.TestCase):
+
+ def test_system_tables_tuple_lists_expected_names_in_order(self):
+ self.assertEqual(_EXPECTED_SYSTEM_TABLES, loader.SYSTEM_TABLES)
+
+ def test_registry_keys_match_system_tables_tuple(self):
+ self.assertEqual(set(_EXPECTED_SYSTEM_TABLES),
+ set(loader.SYSTEM_TABLE_LOADERS.keys()))
+
+ def test_unregistered_names_stay_out_of_registry(self):
+ registered = set(loader.SYSTEM_TABLE_LOADERS.keys())
+ intersection = registered & _UNREGISTERED_NAMES
+ self.assertEqual(set(), intersection,
+ "unregistered names must stay out of the registry: "
+ + str(sorted(intersection)))
+
+ def test_load_returns_none_for_unknown_name(self):
+ self.assertIsNone(loader.load("not_a_real_system_table", base_table=None))
+
+ def test_load_dispatches_to_registered_factory(self):
+ sentinel = object()
+ loader.SYSTEM_TABLE_LOADERS["__test_only__"] = lambda base: sentinel
+ try:
+ self.assertIs(sentinel, loader.load("__test_only__", base_table=None))
+ finally:
+ loader.SYSTEM_TABLE_LOADERS.pop("__test_only__", None)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/system_table_test.py b/paimon-python/pypaimon/tests/system/system_table_test.py
new file mode 100644
index 0000000000..fbb05cb22a
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/system_table_test.py
@@ -0,0 +1,112 @@
+# 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.
+
+"""Tests for the read-only SystemTable base class."""
+
+import types
+import unittest
+
+from pypaimon.common.identifier import Identifier
+from pypaimon.schema.data_types import AtomicType, DataField, RowType
+from pypaimon.table.system.system_table import SystemTable
+
+
+_DUMMY_ROW_TYPE = RowType(False, [
+ DataField(0, "key", AtomicType("STRING", nullable=False)),
+ DataField(1, "value", AtomicType("STRING", nullable=True)),
+])
+
+
+class _DummySystemTable(SystemTable):
+ """Concrete SystemTable used only by these unit tests.
+
+ Subclasses are normally per-system-table (snapshots, schemas, ...).
+ This stub exercises the abstract base contract independently of any
+ real metadata source.
+ """
+
+ def system_table_name(self) -> str:
+ return "dummy"
+
+ def row_type(self) -> RowType:
+ return _DUMMY_ROW_TYPE
+
+ def _build_arrow_table(self): # pragma: no cover - not exercised in this test
+ import pyarrow as pa
+ return pa.table({"key": [], "value": []})
+
+
+def _fake_base(database: str = "db", table: str = "t", branch=None):
+ """Construct a minimal stand-in for FileStoreTable.
+
+ SystemTable only touches ``identifier``, ``file_io`` and ``table_path``
+ on its base, so a SimpleNamespace covers the surface without dragging
+ in catalog/schema bootstrap.
+ """
+ identifier = Identifier.create(database, table, branch=branch)
+ return types.SimpleNamespace(
+ identifier=identifier,
+ file_io=object(),
+ table_path="/tmp/" + database + "/" + table,
+ )
+
+
+class SystemTableTest(unittest.TestCase):
+
+ def test_identifier_encodes_system_table_suffix(self):
+ sys_table = _DummySystemTable(_fake_base())
+ self.assertTrue(sys_table.identifier.is_system_table())
+ self.assertEqual("dummy", sys_table.identifier.get_system_table_name())
+ self.assertEqual("t", sys_table.identifier.get_table_name())
+ self.assertEqual("db", sys_table.identifier.get_database_name())
+ self.assertEqual("t$dummy", sys_table.identifier.get_object_name())
+
+ def test_identifier_preserves_branch_segment(self):
+ sys_table = _DummySystemTable(_fake_base(branch="dev"))
+ self.assertEqual("dev", sys_table.identifier.get_branch_name())
+ self.assertEqual("dummy", sys_table.identifier.get_system_table_name())
+ self.assertEqual("t$branch_dev$dummy", sys_table.identifier.get_object_name())
+
+ def test_base_table_handles_are_exposed(self):
+ base = _fake_base()
+ sys_table = _DummySystemTable(base)
+ self.assertIs(base, sys_table.base_table)
+ self.assertIs(base.file_io, sys_table.file_io)
+ self.assertEqual(base.table_path, sys_table.table_path)
+
+ def test_row_type_and_primary_keys_defaults(self):
+ sys_table = _DummySystemTable(_fake_base())
+ self.assertIs(_DUMMY_ROW_TYPE, sys_table.row_type())
+ self.assertEqual([], sys_table.primary_keys())
+
+ def test_write_and_search_builders_are_read_only(self):
+ sys_table = _DummySystemTable(_fake_base())
+ for method_name in (
+ "new_stream_read_builder",
+ "new_batch_write_builder",
+ "new_stream_write_builder",
+ "new_full_text_search_builder",
+ "new_vector_search_builder",
+ ):
+ with self.assertRaises(NotImplementedError) as ctx:
+ getattr(sys_table, method_name)()
+ self.assertIn("read-only", str(ctx.exception).lower(),
+ "method {}: {}".format(method_name, ctx.exception))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/paimon-python/pypaimon/tests/system/tags_table_test.py b/paimon-python/pypaimon/tests/system/tags_table_test.py
new file mode 100644
index 0000000000..bfc5af9109
--- /dev/null
+++ b/paimon-python/pypaimon/tests/system/tags_table_test.py
@@ -0,0 +1,132 @@
+# 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.
+
+"""End-to-end tests for the ``$tags`` system table."""
+
+import datetime
+import os
+import shutil
+import tempfile
+import unittest
+
+from pypaimon import CatalogFactory, Schema
+from pypaimon.common.json_util import JSON
+from pypaimon.schema.data_types import DataField
+from pypaimon.snapshot.snapshot import Snapshot
+from pypaimon.table.system.tags_table import TagsTable
+
+
+_TAG_COMMIT_MS = 1779100000000
+
+
+def _seed_snapshot(table):
+ snapshot_dir = "{}/snapshot".format(table.table_path)
+ table.file_io.mkdirs(snapshot_dir)
+ snapshot = Snapshot(
+ version=3,
+ id=7,
+ schema_id=0,
+ base_manifest_list="base-7.avro",
+ delta_manifest_list="delta-7.avro",
+ total_record_count=42,
+ delta_record_count=42,
+ commit_user="seed",
+ commit_identifier=7,
+ commit_kind="APPEND",
+ time_millis=_TAG_COMMIT_MS,
+ )
+ table.file_io.try_to_write_atomic(
+ "{}/snapshot-7".format(snapshot_dir), JSON.to_json(snapshot))
+ table.file_io.try_to_write_atomic(
+ "{}/LATEST".format(snapshot_dir), "7")
+ table.file_io.try_to_write_atomic(
+ "{}/EARLIEST".format(snapshot_dir), "7")
+
+
+def _read(table):
+ rb = table.new_read_builder()
+ return rb.new_read().to_arrow(rb.new_scan().plan().splits())
+
+
+class TagsTableTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.mkdtemp(prefix="tags_sys_")
+ warehouse = os.path.join(self.tmp, "warehouse")
+ self.catalog = CatalogFactory.create({"warehouse": warehouse})
+ self.catalog.create_database("db", False)
+ fields = [DataField.from_dict({"id": 0, "name": "v", "type": "INT"})]
+ self.catalog.create_table("db.t", Schema(fields=fields), False)
+ self.table = self.catalog.get_table("db.t")
+ _seed_snapshot(self.table)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_tags_table_loaded_via_catalog(self):
+ table = self.catalog.get_table("db.t$tags")
+ self.assertIsInstance(table, TagsTable)
+
+ def test_schema_column_layout(self):
+ table = self.catalog.get_table("db.t$tags")
+ row_type = table.row_type()
+ self.assertEqual(
+ ["tag_name", "snapshot_id", "schema_id", "commit_time",
+ "record_count", "create_time", "time_retained"],
+ [f.name for f in row_type.fields],
+ )
+ expected_nullability = [False, False, False, False, True, True, True]
+ for field, expected in zip(row_type.fields, expected_nullability):
+ self.assertEqual(expected, field.type.nullable,
+ "field {} nullability".format(field.name))
+ self.assertEqual(["tag_name"], table.primary_keys())
+
+ def test_empty_when_no_tags_created(self):
+ arrow_table = _read(self.catalog.get_table("db.t$tags"))
+ self.assertEqual(0, arrow_table.num_rows)
+
+ def test_lists_created_tags_with_snapshot_metadata(self):
+ self.table.create_tag("v1", snapshot_id=7)
+ self.table.create_tag("v2", snapshot_id=7)
+
+ arrow_table = _read(self.catalog.get_table("db.t$tags"))
+ names = arrow_table.column("tag_name").to_pylist()
+ self.assertEqual({"v1", "v2"}, set(names))
+
+ snapshot_ids = arrow_table.column("snapshot_id").to_pylist()
+ schema_ids = arrow_table.column("schema_id").to_pylist()
+ record_counts = arrow_table.column("record_count").to_pylist()
+ self.assertEqual([7, 7], snapshot_ids)
+ self.assertEqual([0, 0], schema_ids)
+ self.assertEqual([42, 42], record_counts)
+
+ for ts in arrow_table.column("commit_time").to_pylist():
+ self.assertIsInstance(ts, datetime.datetime)
+ ms = int(ts.replace(
+ tzinfo=datetime.timezone.utc).timestamp() * 1000)
+ self.assertEqual(_TAG_COMMIT_MS, ms)
+
+ # Until pypaimon Tag carries these fields they are surfaced as
+ # None — same trade-off as FileSystemCatalog.get_tag.
+ for value in arrow_table.column("create_time").to_pylist():
+ self.assertIsNone(value)
+ for value in arrow_table.column("time_retained").to_pylist():
+ self.assertIsNone(value)
+
+
+if __name__ == "__main__":
+ unittest.main()