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 57233dbc18 [python] Add list-manifests & manifest by file support for
Python CLI. (#11148)
57233dbc18 is described below
commit 57233dbc18db4cefa45ab1447a44843368b1191e
Author: Master.TJ <[email protected]>
AuthorDate: Sat Nov 14 10:27:37 2026 +0800
[python] Add list-manifests & manifest by file support for Python CLI.
(#11148)
---
docs/docs/pypaimon/cli-query.md | 86 +++++++++-
docs/docs/pypaimon/cli.md | 4 +
paimon-python/pypaimon/cli/cli_table.py | 224 +++++++++++++++++++++++++
paimon-python/pypaimon/tests/cli_table_test.py | 214 +++++++++++++++++++++++
4 files changed, 526 insertions(+), 2 deletions(-)
diff --git a/docs/docs/pypaimon/cli-query.md b/docs/docs/pypaimon/cli-query.md
index 3038c09df5..da12abcd21 100644
--- a/docs/docs/pypaimon/cli-query.md
+++ b/docs/docs/pypaimon/cli-query.md
@@ -1,7 +1,7 @@
---
title: "CLI: Query and Inspect"
sidebar_label: "Query and Inspect"
-description: "Inspect schemas, snapshots, partitions, scan plans, and table
rows from the terminal."
+description: "Inspect schemas, snapshots, manifests, partitions, scan plans,
and table rows from the terminal."
---
<!--
@@ -25,7 +25,7 @@ under the License.
# CLI: Query and Inspect
-Inspect schemas, snapshots, partitions, scan plans, and table rows from the
terminal. Configure a catalog with the [CLI quick start](./cli#basic-usage)
first. The examples use existing tables and illustrative output; replace table
and column names with your own.
+Inspect schemas, snapshots, manifests, partitions, scan plans, and table rows
from the terminal. Configure a catalog with the [CLI quick
start](./cli#basic-usage) first. The examples use existing tables and
illustrative output; replace table and column names with your own.
## Table Read
@@ -344,6 +344,88 @@ exit status. Expired snapshots are not reconstructed. If a
snapshot disappears d
it is skipped; other metadata read errors fail the command. These commands
read snapshot metadata
without opening manifest or data files or modifying the table.
+## Table List Manifests
+
+List the manifests referenced by the latest or a specific retained snapshot.
By default, the
+command includes base, delta, and changelog manifest lists, in that order.
+
+```shell
+paimon table list-manifests mydb.orders
+
+# Inspect one manifest-list type in a historical snapshot
+paimon table list-manifests mydb.orders --snapshot-id 42 --type delta
+
+# Limit the total number of manifests and export structured JSON
+paimon table list-manifests mydb.orders --limit 20 --format json
+```
+
+**Options:**
+
+- `--snapshot-id`: Positive snapshot ID. Omit it to use the latest snapshot.
+- `--type`: `all` (default), `base`, `delta`, or `changelog`.
+- `--limit, -l`: Positive maximum number of manifests across all selected
lists. Omit it to show all.
+- `--format, -f`: Output format: `table` (default) or `json`.
+
+Table output groups manifests by type and manifest-list file, showing file
names, sizes in bytes,
+added/deleted file counts, schema IDs, partition statistics, and row-ID
bounds. Missing values are
+displayed as `-`. JSON output contains `table`, `snapshot_id`, and a
`manifests` array.
+
+Output:
+```text
+Table: mydb.orders
+Snapshot: 6
+
+base (manifest-list-example):
+ file_name file_size num_added_files num_deleted_files schema_id
min_partition_stats max_partition_stats min_row_id max_row_id
+manifest-example 2317 1 0 0
{} {} - -
+```
+
+## Table Manifest
+
+Read a manifest file and display its original `ADD` and `DELETE` entries,
including file metadata
+and statistics. JSON is the default output format. Use the `file_name`
returned by `list-manifests`:
+
+```shell
+paimon table manifest mydb.orders --file manifest-example
+
+# Display complete metadata as a readable table
+paimon table manifest mydb.orders --file manifest-example --format table
+```
+
+**Options:**
+
+- `--file`: Manifest file name within the table's `manifest/` directory, not a
path. **Required**.
+- `--format, -f`: Output format: `json` (default) or `table`.
+
+Output contains `table`, `manifest_file`, `manifest_path`, and `entries`.
Table output displays
+the complete `entries` array as JSON in a single field. Historical manifests
can be inspected
+while their files remain available.
+
+Output:
+```json
+{
+ "table": "mydb.orders",
+ "manifest_file": "manifest-example",
+ "manifest_path": "/warehouse/mydb.db/orders/manifest/manifest-example",
+ "entries": [
+ {
+ "kind": "ADD",
+ "partition": {},
+ "bucket": 0,
+ "total_buckets": -1,
+ "file": {
+ "file_name": "data-example.parquet",
+ "file_size": 803,
+ "row_count": 2,
+ "schema_id": 0,
+ "value_stats": {"min_values": {}, "max_values": {}, "null_counts": {}},
+ "first_row_id": null
+ }
+ }
+ ]
+}
+```
+
## Table List Partitions
List partitions of a Paimon table. Supports optional pattern filtering to
match specific partitions.
diff --git a/docs/docs/pypaimon/cli.md b/docs/docs/pypaimon/cli.md
index 0a045680c2..0795b91868 100644
--- a/docs/docs/pypaimon/cli.md
+++ b/docs/docs/pypaimon/cli.md
@@ -105,6 +105,8 @@ paimon table get demo.people
paimon table list-schemas demo.people --limit 20
paimon table list-snapshots demo.people --limit 20
paimon table snapshot demo.people
+paimon table list-manifests demo.people --limit 20
+paimon table manifest demo.people --file manifest-example
paimon table explain demo.people --where "id = 2"
```
@@ -116,6 +118,8 @@ paimon table explain demo.people --where "id = 2"
<span id="table-list-schemas"></span>
<span id="table-snapshot"></span>
<span id="table-list-snapshots"></span>
+<span id="table-list-manifests"></span>
+<span id="table-manifest"></span>
<span id="table-create"></span>
<span id="table-import"></span>
<span id="import-from-csv"></span>
diff --git a/paimon-python/pypaimon/cli/cli_table.py
b/paimon-python/pypaimon/cli/cli_table.py
index f43d0edace..f3ff9c459f 100644
--- a/paimon-python/pypaimon/cli/cli_table.py
+++ b/paimon-python/pypaimon/cli/cli_table.py
@@ -485,6 +485,116 @@ def cmd_table_list_snapshots(args):
sys.exit(1)
+def cmd_table_list_manifests(args):
+ """
+ Execute the 'table list-manifests' command.
+
+ Lists the base, delta and changelog manifests referenced by a snapshot.
+
+ Args:
+ args: Parsed command line arguments.
+ """
+ from pypaimon.manifest.manifest_list_manager import ManifestListManager
+ from pypaimon.utils.row_to_string import cast_row_to_string
+
+ table = _open_manifest_table(args)
+ try:
+ manager = table.snapshot_manager()
+ snapshot = (manager.get_latest_snapshot() if args.snapshot_id is None
+ else manager.get_snapshot_by_id(args.snapshot_id))
+ if snapshot is None and args.snapshot_id is not None:
+ raise ValueError(f"Snapshot {args.snapshot_id} not found for table
'{args.table}'.")
+
+ manifests = []
+ kinds = ('base', 'delta', 'changelog') if args.type == 'all' else
(args.type,)
+ if snapshot is not None:
+ list_manager = ManifestListManager(table)
+ for kind in kinds:
+ list_name = getattr(snapshot, kind + '_manifest_list')
+ if not list_name:
+ continue
+ list_size = getattr(snapshot, kind + '_manifest_list_size')
+ for meta in list_manager.read(list_name, list_size):
+ manifests.append({
+ 'type': kind,
+ 'manifest_list': list_name,
+ 'file_name': meta.file_name,
+ 'file_size': meta.file_size,
+ 'num_added_files': meta.num_added_files,
+ 'num_deleted_files': meta.num_deleted_files,
+ 'schema_id': meta.schema_id,
+ 'min_partition_stats':
cast_row_to_string(meta.partition_stats.min_values),
+ 'max_partition_stats':
cast_row_to_string(meta.partition_stats.max_values),
+ 'min_row_id': meta.min_row_id,
+ 'max_row_id': meta.max_row_id,
+ })
+ if args.limit is not None and len(manifests) >= args.limit:
+ break
+ if args.limit is not None and len(manifests) >= args.limit:
+ break
+
+ snapshot_id = snapshot.id if snapshot is not None else None
+ if args.format == 'json':
+ print(json.dumps({'table': args.table, 'snapshot_id': snapshot_id,
'manifests': manifests},
+ ensure_ascii=False, indent=2, allow_nan=False))
+ else:
+ print(f"Table: {args.table}\nSnapshot:
{_snapshot_display_value(snapshot_id)}")
+ if not manifests:
+ print(f"No manifests found for table '{args.table}'.")
+ return
+ import pandas as pd
+ columns = ['file_name', 'file_size', 'num_added_files',
'num_deleted_files', 'schema_id',
+ 'min_partition_stats', 'max_partition_stats',
'min_row_id', 'max_row_id']
+ for kind in kinds:
+ group = [meta for meta in manifests if meta['type'] == kind]
+ if not group:
+ continue
+ print('\n{} ({}):'.format(kind, group[0]['manifest_list']))
+ # Convert before Pandas can coerce nullable row IDs to floats.
+ rows = [[_snapshot_display_value(meta[column]) for column in
columns] for meta in group]
+ print(pd.DataFrame(rows,
columns=columns).to_string(index=False))
+ except Exception as e:
+ print(f"Error: Failed to list manifests for table '{args.table}':
{e}", file=sys.stderr)
+ sys.exit(1)
+
+
+def cmd_table_manifest(args):
+ """
+ Execute the 'table manifest' command.
+
+ Displays a manifest's original ADD/DELETE entries and complete metadata.
+
+ Args:
+ args: Parsed command line arguments.
+ """
+ from pypaimon.manifest.manifest_file_manager import ManifestFileManager
+
+ table = _open_manifest_table(args)
+ try:
+ name = args.file
+ if not name or name in ('.', '..') or any(char in name for char in
('/', '\\', '\x00')):
+ raise ValueError('--file must be a file name within the table
manifest directory.')
+ manager = ManifestFileManager(table)
+ # Reading a single file preserves DELETE entries and their original
order.
+ entries = manager.read(name, drop_stats=False)
+ result = {
+ 'table': args.table,
+ 'manifest_file': name,
+ 'manifest_path': manager.manifest_path + '/' + name,
+ 'entries': [_manifest_entry_to_dict(table, entry) for entry in
entries],
+ }
+ result = _manifest_json_value(result)
+ if getattr(args, 'format', 'json') == 'json':
+ print(json.dumps(result, ensure_ascii=False, indent=2,
allow_nan=False))
+ else:
+ import pandas as pd
+ rows = [[key, _snapshot_display_value(value)] for key, value in
result.items()]
+ print(pd.DataFrame(rows, columns=['Field',
'Value']).to_string(index=False))
+ except Exception as e:
+ print(f"Error: Failed to read manifest '{args.file}' for table
'{args.table}': {e}", file=sys.stderr)
+ sys.exit(1)
+
+
def cmd_table_rollback(args):
"""
Execute the 'table rollback' command.
@@ -1063,6 +1173,85 @@ def _open_snapshot_manager(args):
sys.exit(1)
+def _open_manifest_table(args):
+ """Load a file-store table for the manifest inspection commands."""
+ from pypaimon.table.file_store_table import FileStoreTable
+
+ table = _open_schema_table(args)
+ if not isinstance(table, FileStoreTable):
+ print('Error: Manifest inspection is not supported for this table
type; expected a FileStoreTable.',
+ file=sys.stderr)
+ sys.exit(1)
+ return table
+
+
+def _manifest_entry_to_dict(table, entry):
+ """Keep all stored file metadata and add the resolved data-file path and
format."""
+ from dataclasses import fields
+ from pypaimon.table.system.files_table import _data_file_format,
_metadata_file_path
+
+ meta = entry.file
+ file = {field.name: getattr(meta, field.name) for field in fields(meta)}
+ if table.primary_keys and meta.schema_id != table.table_schema.id:
+ schema = table.schema_manager.get_schema(meta.schema_id)
+ key_names = [name for name in schema.primary_keys if name not in
schema.partition_keys]
+ # Key types cannot change, but the reader uses the latest key names.
+ # Restore the names recorded by this file's schema after a rename.
+ for name in ('min_key', 'max_key', 'key_stats'):
+ file[name] = _manifest_json_value(file[name], key_names)
+ file['file_path'] = _metadata_file_path(table, entry)
+ file['file_format'] = _data_file_format(meta.file_name)
+ file['file_source'] = {0: 'APPEND', 1: 'COMPACT'}.get(meta.file_source,
meta.file_source)
+ return {
+ 'kind': {0: 'ADD', 1: 'DELETE'}.get(entry.kind, entry.kind),
+ 'partition': entry.partition,
+ 'bucket': entry.bucket,
+ 'total_buckets': entry.total_buckets,
+ 'file': file,
+ }
+
+
+def _manifest_json_value(value, field_names=None):
+ """Render decoded metadata without losing integers, decimal precision or
binary values."""
+ import base64
+ import math
+ from datetime import date, time
+ from decimal import Decimal
+ from pypaimon.data.timestamp import Timestamp
+ from pypaimon.manifest.schema.simple_stats import SimpleStats
+ from pypaimon.table.row.internal_row import InternalRow
+
+ if isinstance(value, InternalRow):
+ names = [field.name for field in value.fields] if field_names is None
else field_names
+ # Empty stats can retain schema fields even when the stored row has no
values.
+ return {name: _manifest_json_value(value.get_field(i)) for i, name in
enumerate(names[:len(value)])}
+ if isinstance(value, SimpleStats):
+ counts = value.null_counts
+ names = [field.name for field in value.min_values.fields] if
field_names is None else field_names
+ return {
+ 'min_values': _manifest_json_value(value.min_values, names),
+ 'max_values': _manifest_json_value(value.max_values, names),
+ 'null_counts': None if counts is None else {
+ name: counts[i] if i < len(counts) else None for i, name in
enumerate(names)
+ },
+ }
+ if isinstance(value, dict):
+ return {key: _manifest_json_value(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_manifest_json_value(item) for item in value]
+ if isinstance(value, (bytes, bytearray, memoryview)):
+ return {'encoding': 'base64', 'data':
base64.b64encode(value).decode('ascii')}
+ if isinstance(value, Decimal):
+ return str(value)
+ if isinstance(value, Timestamp):
+ return value.to_local_date_time().isoformat()
+ if isinstance(value, (date, time)):
+ return value.isoformat()
+ if isinstance(value, float) and not math.isfinite(value):
+ return 'NaN' if math.isnan(value) else ('Infinity' if value > 0 else
'-Infinity')
+ return value
+
+
def add_table_subcommands(table_parser):
"""
Add table subcommands to the parser.
@@ -1212,6 +1401,41 @@ def add_table_subcommands(table_parser):
)
list_snapshots_parser.set_defaults(func=cmd_table_list_snapshots)
+ # table list-manifests command
+ list_manifests_parser = table_subparsers.add_parser(
+ 'list-manifests', help='List the manifests referenced by a snapshot'
+ )
+ list_manifests_parser.add_argument('table', help='Table identifier in
format: database.table')
+ list_manifests_parser.add_argument(
+ '--snapshot-id', type=_positive_int, default=None,
+ help='Snapshot ID to inspect (default: the latest snapshot)'
+ )
+ list_manifests_parser.add_argument(
+ '--type', choices=['all', 'base', 'delta', 'changelog'], default='all',
+ help='Manifest list type (default: all)'
+ )
+ list_manifests_parser.add_argument(
+ '--limit', '-l', type=_positive_int, default=None,
+ help='Maximum number of manifests across all selected lists (default:
all)'
+ )
+ list_manifests_parser.add_argument(
+ '--format', '-f', choices=['table', 'json'], default='table',
+ help='Output format: table (default) or json'
+ )
+ list_manifests_parser.set_defaults(func=cmd_table_list_manifests)
+
+ # table manifest command
+ manifest_parser = table_subparsers.add_parser(
+ 'manifest', help='Inspect a manifest and its original ADD/DELETE
entries'
+ )
+ manifest_parser.add_argument('table', help='Table identifier in format:
database.table')
+ manifest_parser.add_argument('--file', required=True, help='Manifest file
name within the table manifest directory')
+ manifest_parser.add_argument(
+ '--format', '-f', choices=['table', 'json'], default='json',
+ help='Output format: json (default) or table'
+ )
+ manifest_parser.set_defaults(func=cmd_table_manifest)
+
# table rollback command
rollback_parser = table_subparsers.add_parser(
'rollback',
diff --git a/paimon-python/pypaimon/tests/cli_table_test.py
b/paimon-python/pypaimon/tests/cli_table_test.py
index d35398be3b..8792699903 100644
--- a/paimon-python/pypaimon/tests/cli_table_test.py
+++ b/paimon-python/pypaimon/tests/cli_table_test.py
@@ -20,7 +20,11 @@ import os
import shutil
import tempfile
import unittest
+from dataclasses import replace
+from datetime import date, datetime
+from decimal import Decimal
from io import StringIO
+from pathlib import Path
from unittest.mock import patch
import pyarrow as pa
@@ -29,11 +33,19 @@ import pytest
from pypaimon import CatalogFactory, Schema
from pypaimon.cli.cli import main
from pypaimon.common.json_util import JSON
+from pypaimon.data.timestamp import Timestamp
+from pypaimon.manifest.manifest_file_manager import ManifestFileManager
+from pypaimon.manifest.manifest_list_manager import ManifestListManager
+from pypaimon.manifest.schema.data_file_meta import DataFileMeta
+from pypaimon.manifest.schema.manifest_entry import ManifestEntry
+from pypaimon.manifest.schema.manifest_file_meta import ManifestFileMeta
+from pypaimon.manifest.schema.simple_stats import SimpleStats
from pypaimon.schema.data_types import DataField
from pypaimon.schema.schema_manager import SchemaManager
from pypaimon.schema.table_schema import TableSchema
from pypaimon.snapshot.snapshot import Snapshot
from pypaimon.snapshot.snapshot_manager import SnapshotManager
+from pypaimon.table.row.generic_row import GenericRow
class CliTableTest(unittest.TestCase):
@@ -156,6 +168,34 @@ class CliTableTest(unittest.TestCase):
f.write(JSON.to_json(schema))
return identifier, table
+ def _create_manifest_table(self, primary_keys=None, options=None,
suffix='manifests'):
+ """Write real Avro metadata without creating the referenced data
files."""
+ identifier, table = self._create_snapshot_table(
+ snapshots=[self._snapshot(1), self._snapshot(2,
changelog_manifest_list='change-2')],
+ primary_keys=primary_keys, options=options, suffix=suffix)
+ empty = GenericRow([], [])
+ key = GenericRow([7] if primary_keys else [],
table.trimmed_primary_keys_fields)
+ stats = SimpleStats(GenericRow([7], table.fields), GenericRow([8],
table.fields), [0])
+ entry = ManifestEntry(0, empty, 0, table.total_buckets, DataFileMeta(
+ file_name='data-test.parquet', file_size=1024, row_count=2,
+ min_key=key, max_key=key, key_stats=SimpleStats(key, key, [0] if
primary_keys else []),
+ value_stats=stats, min_sequence_number=9007199254740993,
max_sequence_number=9007199254740994,
+ schema_id=0, level=0, extra_files=[],
creation_time=Timestamp.from_epoch_millis(1700000000123),
+ file_source=0))
+ file_manager = ManifestFileManager(table)
+ table.file_io.mkdirs(file_manager.manifest_path)
+ metas = []
+ for name in ('manifest-base', 'manifest-delta', 'manifest-change'):
+ file_manager.write(name, [entry])
+ metas.append(ManifestFileMeta(
+ name, os.path.getsize(os.path.join(file_manager.manifest_path,
name)), 1, 0,
+ SimpleStats(empty, empty, []), 0))
+ manager = ManifestListManager(table)
+ for name, files in (('base-1', [metas[0]]), ('delta-1', []),
+ ('base-2', [metas[0]]), ('delta-2', [metas[1]]),
('change-2', [metas[2]])):
+ manager.write(name, files)
+ return identifier, table, entry
+
def _run_table_command(self, *argv, config=None):
"""Run a table command and capture stdout, stderr and the exit code."""
out, err = StringIO(), StringIO()
@@ -677,6 +717,180 @@ class CliTableTest(unittest.TestCase):
listed =
json.loads(self._run_table_command_success('list-snapshots', identifier, '-f',
'json'))
self.assertEqual([1], [s['id'] for s in listed])
+ def test_cli_table_list_manifests(self):
+ identifier, table, _ = self._create_manifest_table()
+ manager = ManifestListManager(table)
+ meta = manager.read('base-2')[0]
+ manager.write('base-2', [replace(meta, min_row_id=9007199254740993,
max_row_id=9007199254740994),
+ replace(meta, file_name='manifest-null')])
+ latest = table.snapshot_manager().get_latest_snapshot()
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
+ side_effect=[latest, AssertionError('resolved
twice')]), \
+ patch.object(ManifestFileManager, 'read',
side_effect=AssertionError('manifest entries read')):
+ result =
json.loads(self._run_table_command_success('list-manifests', identifier, '-f',
'json'))
+ self.assertEqual((identifier, 2), (result['table'],
result['snapshot_id']))
+ self.assertEqual([('base', 'base-2'), ('base', 'base-2'), ('delta',
'delta-2'), ('changelog', 'change-2')],
+ [(m['type'], m['manifest_list']) for m in
result['manifests']])
+ self.assertEqual([9007199254740993, None, None, None],
[m['min_row_id'] for m in result['manifests']])
+ for options, snapshot_id, names in (
+ (('--type', 'delta'), 2, ['manifest-delta']),
+ (('--snapshot-id', '1'), 1, ['manifest-base']),
+ (('--snapshot-id', '1', '--type', 'changelog'), 1, []),
+ (('-l', '1'), 2, ['manifest-base'])):
+ with self.subTest(options=options):
+ result = json.loads(self._run_table_command_success(
+ 'list-manifests', identifier, *options, '-f', 'json'))
+ self.assertEqual(snapshot_id, result['snapshot_id'])
+ self.assertEqual(names, [m['file_name'] for m in
result['manifests']])
+ output = self._run_table_command_success('list-manifests', identifier,
'--limit', '3')
+ header = next(line.split() for line in output.splitlines() if
'num_added_files' in line)
+ self.assertEqual(['file_name', 'file_size', 'num_added_files',
'num_deleted_files', 'schema_id',
+ 'min_partition_stats', 'max_partition_stats',
'min_row_id', 'max_row_id'], header)
+ rows = [line.split() for line in output.splitlines() if
line.lstrip().startswith('manifest-')]
+ self.assertEqual(['manifest-base', 'manifest-null', 'manifest-delta'],
[row[0] for row in rows])
+ self.assertEqual(['{}', '{}', '9007199254740993', '9007199254740994'],
rows[0][-4:])
+ self.assertEqual(['-', '-'], rows[1][-2:])
+
+ def test_cli_table_list_manifests_empty_and_missing_snapshot(self):
+ identifier, _ = self._create_snapshot_table(snapshots=[])
+ result = json.loads(self._run_table_command_success('list-manifests',
identifier, '-f', 'json'))
+ self.assertEqual({'table': identifier, 'snapshot_id': None,
'manifests': []}, result)
+ self.assertIn('No manifests',
self._run_table_command_success('list-manifests', identifier))
+ out, err, code = self._run_table_command('list-manifests', identifier,
'--snapshot-id', '99')
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('Snapshot 99 not found', err)
+
+ def test_cli_table_manifest_preserves_raw_entries_and_formats(self):
+ identifier, table, entry = self._create_manifest_table()
+ extra = dict(first_row_id=9007199254740993, write_cols=['id'],
write_cols_sequences=[9007199254740994],
+ extra_files=['file.index'], embedded_index=b'\x00\xff',
delete_row_count=1, file_source=1,
+ external_path='s3://warehouse/external/data-test.parquet')
+ # This file is absent from all snapshot manifest lists; its data file
does not exist.
+ deleted = replace(entry, kind=1, file=replace(entry.file, **extra))
+ ManifestFileManager(table).write('manifest-retained', [entry, deleted])
+ root = Path(table.table_path)
+ before = {path: path.read_bytes() for path in root.rglob('*') if
path.is_file()}
+ args = ('manifest', identifier, '--file', 'manifest-retained')
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
side_effect=AssertionError('snapshot read')):
+ result = json.loads(self._run_table_command_success(*args))
+ self.assertEqual((identifier, 'manifest-retained', table.table_path +
'/manifest/manifest-retained'),
+ (result['table'], result['manifest_file'],
result['manifest_path']))
+ self.assertEqual([('ADD', {}, 0), ('DELETE', {}, 0)],
+ [(e['kind'], e['partition'], e['bucket']) for e in
result['entries']])
+ file = result['entries'][0]['file']
+ expected = dict(file_name='data-test.parquet', file_format='parquet',
file_size=1024, row_count=2,
+ schema_id=0, min_sequence_number=9007199254740993,
first_row_id=None, file_source='APPEND',
+ creation_time='2023-11-14T22:13:20.123000',
+ file_path=table.table_path +
'/bucket-0/data-test.parquet')
+ self.assertEqual(expected, {key: file[key] for key in expected})
+ file = result['entries'][1]['file']
+ expected = dict(extra, file_source='COMPACT',
embedded_index={'encoding': 'base64', 'data': 'AP8='},
+ file_path=extra['external_path'])
+ self.assertEqual(expected, {key: file[key] for key in expected})
+ output = self._run_table_command_success(*args, '-f', 'table')
+ rows = dict(line.split(None, 1) for line in output.splitlines()[1:])
+ self.assertEqual(['table', 'manifest_file', 'manifest_path',
'entries'], list(rows))
+ self.assertEqual(result, dict(rows,
entries=json.loads(rows['entries'])))
+ self.assertEqual(before, {path: path.read_bytes() for path in
root.rglob('*') if path.is_file()})
+
+ def test_cli_table_manifest_historical_schema(self):
+ identifier, table, entry =
self._create_manifest_table(primary_keys=['id'], options={'bucket': '1'})
+ renamed = [DataField.from_dict({'id': 0, 'name': 'renamed_id', 'type':
'INT NOT NULL'}),
+ DataField.from_dict({'id': 1, 'name': 'new_column', 'type':
'STRING'})]
+ schema = TableSchema.from_schema(1, Schema(
+ fields=renamed, primary_keys=['renamed_id'], options={'bucket':
'1'}))
+ with open(table.schema_manager._to_schema_path(1), 'w') as f:
+ f.write(JSON.to_json(schema))
+ meta = replace(entry.file, value_stats=replace(entry.file.value_stats,
null_counts=None),
+ value_stats_cols=['id'])
+ ManifestFileManager(table).write('manifest-old', [replace(entry,
file=meta)])
+ result = json.loads(self._run_table_command_success('manifest',
identifier, '--file', 'manifest-old'))
+ file = result['entries'][0]['file']
+ self.assertEqual((0, ['id'], {'id': 7}, {'id': 7}),
+ (file['schema_id'], file['value_stats_cols'],
file['min_key'], file['max_key']))
+ self.assertEqual({'min_values': {'id': 7}, 'max_values': {'id': 7},
'null_counts': {'id': 0}},
+ file['key_stats'])
+ self.assertEqual({'min_values': {'id': 7}, 'max_values': {'id': 8},
'null_counts': None}, file['value_stats'])
+
+ def test_cli_table_manifest_typed_stats_and_partition(self):
+ identifier = 'test_db.typed_manifest'
+ definitions = [('pt', 'DATE'), ('amount', 'DECIMAL(30, 9)'),
('payload', 'BYTES'), ('at', 'TIMESTAMP(6)'),
+ ('nan', 'DOUBLE'), ('positive', 'DOUBLE'), ('negative',
'DOUBLE')]
+ fields = [DataField.from_dict({'id': i, 'name': name, 'type':
type_name})
+ for i, (name, type_name) in enumerate(definitions)]
+ self.catalog.create_table(identifier, Schema(fields=fields,
partition_keys=['pt']), False)
+ table = self.catalog.get_table(identifier)
+ empty = GenericRow([], [])
+ values = [date(2026, 11, 13), Decimal('123456789012345678.123456789'),
b'\x00\xff',
+ datetime(2026, 11, 13, 1, 2, 3, 123456), float('nan'),
float('inf'), float('-inf')]
+ stats = SimpleStats(GenericRow(values, fields), GenericRow(values,
fields), [0, None, 0, 0])
+ entry = ManifestEntry(0, GenericRow(values[:1],
table.partition_keys_fields), 0, -1, DataFileMeta(
+ 'typed.parquet', 100, 1, empty, empty, SimpleStats(empty, empty,
[]), stats, 0, 0, 0, 0, []))
+ manager = ManifestFileManager(table)
+ table.file_io.mkdirs(manager.manifest_path)
+ manager.write('manifest-typed', [entry])
+ result = json.loads(self._run_table_command_success('manifest',
identifier, '--file', 'manifest-typed'))
+ self.assertEqual({'pt': '2026-11-13'},
result['entries'][0]['partition'])
+ stats = result['entries'][0]['file']['value_stats']
+ expected = {'pt': '2026-11-13', 'amount':
'123456789012345678.123456789',
+ 'payload': {'encoding': 'base64', 'data': 'AP8='}, 'at':
'2026-11-13T01:02:03.123456',
+ 'nan': 'NaN', 'positive': 'Infinity', 'negative':
'-Infinity'}
+ self.assertEqual(expected, stats['min_values'])
+ self.assertEqual(expected, stats['max_values'])
+ self.assertEqual(
+ {'pt': 0, 'amount': None, 'payload': 0, 'at': 0, 'nan': None,
'positive': None, 'negative': None},
+ stats['null_counts'])
+
+ def test_cli_table_manifest_empty_entries_and_stats(self):
+ identifier, table, entry = self._create_manifest_table()
+ manager = ManifestFileManager(table)
+ manager.write('manifest-empty', [])
+ # Dedicated vector files can store an empty row while retaining schema
field definitions.
+ meta = replace(entry.file, value_stats=SimpleStats.empty_stats(),
value_stats_cols=None)
+ manager.write('manifest-empty-stats', [replace(entry, file=meta)])
+ for name, count in (('manifest-empty', 0), ('manifest-empty-stats',
1)):
+ with self.subTest(file=name):
+ args = ('manifest', identifier, '--file', name)
+ result = json.loads(self._run_table_command_success(*args,
'--format', 'json'))
+ self.assertEqual(count, len(result['entries']))
+ if count:
+ self.assertEqual({'min_values': {}, 'max_values': {},
'null_counts': {'id': None}},
+
result['entries'][0]['file']['value_stats'])
+ output = self._run_table_command_success(*args, '--format',
'table')
+ rows = dict(line.split(None, 1) for line in
output.splitlines()[1:])
+ self.assertEqual(result['entries'],
json.loads(rows['entries']))
+
+ def test_cli_table_manifest_invalid_arguments(self):
+ cases = [('manifest', 'test_db.users'), ('manifest', 'test_db.users',
'--file', 'manifest-test', '-f', 'csv')]
+ cases.extend(('list-manifests', 'test_db.users', option, value)
+ for option, value in (('--snapshot-id', '0'), ('--limit',
'-1'), ('--type', 'invalid')))
+ for args in cases:
+ with self.subTest(args=args):
+ out, err, code = self._run_table_command(*args)
+ self.assertEqual(('', 2), (out, code))
+ self.assertIn('error:', err)
+ for name in ('../manifest-test', 'dir\\manifest-test', '..', '',
'\x00'):
+ with self.subTest(file=name):
+ out, err, code = self._run_table_command('manifest',
'test_db.users', '--file', name)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('file name', err.lower())
+
+ def test_cli_table_manifest_metadata_errors(self):
+ identifier, table, _ = self._create_manifest_table()
+ os.remove(os.path.join(table.table_path, 'manifest', 'base-2'))
+ with open(os.path.join(table.table_path, 'manifest',
'manifest-corrupt'), 'wb') as f:
+ f.write(b'not avro')
+ for args, message in (
+ (('list-manifests', identifier), 'Failed to list manifests'),
+ (('manifest', identifier, '--file', 'manifest-missing'),
'Failed to read manifest'),
+ (('manifest', identifier, '--file', 'manifest-corrupt'),
'Failed to read manifest'),
+ (('list-manifests', identifier + '$snapshots'), 'expected a
FileStoreTable'),
+ (('manifest', identifier + '$snapshots', '--file',
'manifest-base'), 'expected a FileStoreTable')):
+ with self.subTest(args=args):
+ out, err, code = self._run_table_command(*args)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn(message, err)
+
def test_cli_table_create_with_json_schema(self):
"""Test table create with JSON schema file."""
import json