iceframex 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
iceframex/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """
2
+ iceframex - Unified DataFrame-like API for Apache Iceberg, Delta Lake, and Apache Hudi.
3
+
4
+ iceframex provides a simple, intuitive API for working with lakehouse tables
5
+ using REST or SQL catalogs with local and distributed execution.
6
+
7
+ Improvements over IceFrame:
8
+ * Multi-format table support (Iceberg, Delta Lake, Apache Hudi) through one
9
+ :class:`UnifiedTable` API.
10
+ * Distributed execution backends (Ray, Dask) for larger-than-memory scans.
11
+ * A read-write MCP server so AI agents can both query and mutate tables.
12
+ * Python 3.9+ support (IceFrame requires 3.10+).
13
+ """
14
+
15
+ #: Single source of truth for the package version. ``pyproject.toml`` reads it
16
+ #: from here via ``[tool.setuptools.dynamic]``.
17
+ __version__ = "0.1.0"
18
+
19
+ from iceframex.core import UnifiedTable
20
+ from iceframex.exceptions import (
21
+ CatalogError,
22
+ IceFrameXError,
23
+ SchemaError,
24
+ TableNotFoundError,
25
+ UnsupportedFormatError,
26
+ ValidationError,
27
+ )
28
+ from iceframex.formats import TableFormat, detect_format
29
+ from iceframex.utils import load_catalog_config_from_env
30
+
31
+ __all__ = [
32
+ "UnifiedTable",
33
+ "TableFormat",
34
+ "detect_format",
35
+ "load_catalog_config_from_env",
36
+ "IceFrameXError",
37
+ "CatalogError",
38
+ "TableNotFoundError",
39
+ "SchemaError",
40
+ "ValidationError",
41
+ "UnsupportedFormatError",
42
+ "__version__",
43
+ ]
iceframex/core.py ADDED
@@ -0,0 +1,247 @@
1
+ """
2
+ Core UnifiedTable class - main entry point for iceframex.
3
+
4
+ Provides a single API that works across Apache Iceberg, Delta Lake, and Apache
5
+ Hudi tables, dispatching to the appropriate format backend automatically.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import html
11
+ import logging
12
+ import os
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ import polars as pl
16
+ import pyarrow as pa
17
+
18
+ from iceframex.exceptions import (
19
+ UnsupportedFormatError,
20
+ )
21
+ from iceframex.formats import TableFormat, detect_format
22
+ from iceframex.formats.base import BaseTableBackend
23
+ from iceframex.formats.delta import DeltaBackend
24
+ from iceframex.formats.hudi import HudiBackend
25
+ from iceframex.formats.iceberg import IcebergBackend
26
+ from iceframex.utils import (
27
+ validate_catalog_config,
28
+ )
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ def _safe_cwd() -> str:
34
+ try:
35
+ return os.getcwd()
36
+ except OSError:
37
+ return "/"
38
+
39
+
40
+ if TYPE_CHECKING: # pragma: no cover
41
+ from iceframex.query import QueryBuilder
42
+
43
+
44
+ _BACKEND_MAP: dict[TableFormat, type[BaseTableBackend]] = {
45
+ TableFormat.ICEBERG: IcebergBackend,
46
+ TableFormat.DELTA: DeltaBackend,
47
+ TableFormat.HUDI: HudiBackend,
48
+ }
49
+
50
+
51
+ class UnifiedTable:
52
+ """
53
+ Unified table handle for lakehouse formats.
54
+
55
+ ``UnifiedTable`` is the main entry point. It detects or accepts a table
56
+ format and routes all CRUD operations to the matching backend::
57
+
58
+ >>> ice = UnifiedTable({"uri": "http://localhost:8181", "type": "rest", "warehouse": "s3://bucket/wh"})
59
+ >>> ice.create_table("db.users", schema=arrow_schema)
60
+ >>> df = ice.read_table("db.users")
61
+ >>> ice.append_to_table("db.users", new_rows)
62
+
63
+ Format can be specified explicitly or detected from a path::
64
+
65
+ >>> ice = UnifiedTable(config, format="delta")
66
+ >>> ice.create_table("sales", df, path="/lakehouse/sales")
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ catalog_config: dict[str, Any],
72
+ *,
73
+ format: str | TableFormat | None = None,
74
+ path: str | None = None,
75
+ pool_size: int | None = None,
76
+ ):
77
+ """
78
+ Initialize UnifiedTable with catalog configuration.
79
+
80
+ Args:
81
+ catalog_config: Dictionary containing catalog configuration.
82
+ Must include 'uri' and 'type' keys.
83
+ format: Optional table format ('iceberg', 'delta', 'hudi').
84
+ path: Optional filesystem path used for format detection.
85
+ pool_size: Deprecated and ignored (kept for IceFrame compatibility).
86
+ """
87
+ validate_catalog_config(catalog_config)
88
+ self.catalog_config = catalog_config
89
+ self.format = detect_format(path=path, format=format)
90
+
91
+ backend_cls = _BACKEND_MAP.get(self.format)
92
+ if backend_cls is None:
93
+ raise UnsupportedFormatError(f"No backend registered for format {self.format}")
94
+
95
+ if pool_size is not None:
96
+ import warnings
97
+
98
+ warnings.warn(
99
+ "UnifiedTable(pool_size=...) is deprecated and ignored.",
100
+ DeprecationWarning,
101
+ stacklevel=2,
102
+ )
103
+
104
+ self._backend = backend_cls(catalog_config)
105
+ self._warehouse = catalog_config.get("warehouse", _safe_cwd())
106
+
107
+ # ------------------------------------------------------------------
108
+ # CRUD
109
+ # ------------------------------------------------------------------
110
+
111
+ def create_table(
112
+ self,
113
+ table_name: str,
114
+ schema: Any,
115
+ partition_spec: list[tuple] | None = None,
116
+ sort_order: list[str] | None = None,
117
+ properties: dict[str, str] | None = None,
118
+ ) -> Any:
119
+ """Create a new table in the selected format."""
120
+ return self._backend.create_table(
121
+ table_name=table_name,
122
+ schema=schema,
123
+ partition_spec=partition_spec,
124
+ sort_order=sort_order,
125
+ properties=properties,
126
+ )
127
+
128
+ def read_table(
129
+ self,
130
+ table_name: str,
131
+ columns: list[str] | None = None,
132
+ filter_expr: str | Any | None = None,
133
+ limit: int | None = None,
134
+ ) -> pl.DataFrame:
135
+ """Read table data into a Polars DataFrame."""
136
+ return self._backend.read_table(
137
+ table_name=table_name,
138
+ columns=columns,
139
+ filter_expr=filter_expr,
140
+ limit=limit,
141
+ )
142
+
143
+ def append_to_table(
144
+ self,
145
+ table_name: str,
146
+ data: pl.DataFrame | dict[str, list],
147
+ branch: str | None = None,
148
+ ) -> None:
149
+ """Append rows to an existing table."""
150
+ self._backend.append_to_table(table_name=table_name, data=data, branch=branch)
151
+
152
+ def overwrite_table(
153
+ self,
154
+ table_name: str,
155
+ data: pl.DataFrame | dict[str, list],
156
+ ) -> None:
157
+ """Replace all data in a table."""
158
+ self._backend.overwrite_table(table_name=table_name, data=data)
159
+
160
+ def delete_from_table(self, table_name: str, filter_expr: str) -> None:
161
+ """Delete rows matching a filter expression."""
162
+ self._backend.delete_from_table(table_name=table_name, filter_expr=filter_expr)
163
+
164
+ def drop_table(self, table_name: str) -> None:
165
+ """Drop a table from the catalog / filesystem."""
166
+ self._backend.drop_table(table_name=table_name)
167
+
168
+ def table_exists(self, table_name: str) -> bool:
169
+ """Return True if the table exists."""
170
+ return self._backend.table_exists(table_name)
171
+
172
+ def list_tables(self, namespace: str = "default") -> list[str]:
173
+ """List table names in a namespace."""
174
+ return self._backend.list_tables(namespace)
175
+
176
+ def count_rows(self, table_name: str) -> int:
177
+ """Return the total row count."""
178
+ return self._backend.count_rows(table_name)
179
+
180
+ # ------------------------------------------------------------------
181
+ # Utility / ergonomics
182
+ # ------------------------------------------------------------------
183
+
184
+ def to_arrow(
185
+ self,
186
+ table_name: str,
187
+ columns: list[str] | None = None,
188
+ filter_expr: Any | None = None,
189
+ limit: int | None = None,
190
+ ) -> pa.Table:
191
+ """Read a table as a PyArrow Table."""
192
+ return self.read_table(
193
+ table_name, columns=columns, filter_expr=filter_expr, limit=limit
194
+ ).to_arrow()
195
+
196
+ def to_pandas(
197
+ self,
198
+ table_name: str,
199
+ columns: list[str] | None = None,
200
+ filter_expr: Any | None = None,
201
+ limit: int | None = None,
202
+ ):
203
+ """Read a table as a pandas DataFrame (requires pandas)."""
204
+ return self.read_table(
205
+ table_name, columns=columns, filter_expr=filter_expr, limit=limit
206
+ ).to_pandas()
207
+
208
+ def lazy(
209
+ self,
210
+ table_name: str,
211
+ columns: list[str] | None = None,
212
+ filter_expr: Any | None = None,
213
+ ) -> pl.LazyFrame:
214
+ """Return a Polars LazyFrame over a table."""
215
+ return self.read_table(table_name, columns=columns, filter_expr=filter_expr).lazy()
216
+
217
+ def head(self, table_name: str, n: int = 5) -> pl.DataFrame:
218
+ """Read the first ``n`` rows of a table."""
219
+ return self.read_table(table_name, limit=n)
220
+
221
+ def describe(self, table_name: str) -> pl.DataFrame:
222
+ """Summary statistics for every column."""
223
+ return self.read_table(table_name).describe()
224
+
225
+ def query(self, table_name: str) -> QueryBuilder:
226
+ """Start a fluent query builder for a table."""
227
+ from iceframex.query import QueryBuilder
228
+
229
+ return QueryBuilder(self, table_name)
230
+
231
+ # ------------------------------------------------------------------
232
+ # HTML repr for notebooks
233
+ # ------------------------------------------------------------------
234
+
235
+ def _repr_html_(self) -> str:
236
+ uri = html.escape(str(self.catalog_config.get("uri", "unknown")))
237
+ catalog_type = html.escape(str(self.catalog_config.get("type", "unknown")))
238
+ warehouse = html.escape(str(self._warehouse))
239
+ return f"""
240
+ <div style="border: 1px solid #e0e0e0; border-radius: 4px; padding: 10px;">
241
+ <h3>UnifiedTable Connection</h3>
242
+ <p><strong>Format:</strong> {self.format.value}</p>
243
+ <p><strong>URI:</strong> {uri}</p>
244
+ <p><strong>Type:</strong> {catalog_type}</p>
245
+ <p><strong>Warehouse:</strong> {warehouse}</p>
246
+ </div>
247
+ """
@@ -0,0 +1,5 @@
1
+ """Distributed execution package for iceframex."""
2
+
3
+ from iceframex.distributed.engine import DistributedEngine
4
+
5
+ __all__ = ["DistributedEngine"]
@@ -0,0 +1,213 @@
1
+ """Distributed execution backends for iceframex.
2
+
3
+ Provides :class:`DistributedEngine` which can run table scans and writes
4
+ across a Ray or Dask cluster, bridging the "no distributed compute" gap in
5
+ IceFrame.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from typing import Any, Callable
12
+
13
+ import polars as pl
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class DistributedEngine:
19
+ """
20
+ Distributed execution engine for lakehouse tables.
21
+
22
+ Wraps Ray or Dask to parallelize reads and writes across a cluster.
23
+ Usage::
24
+
25
+ >>> engine = DistributedEngine(backend="ray")
26
+ >>> df = engine.read_table(ice, "db.events", columns=["id", "ts"])
27
+ >>> engine.write_table(ice, "db.events_out", df)
28
+
29
+ If neither Ray nor Dask is installed, falls back to single-process
30
+ execution through the underlying :class:`~iceframex.core.UnifiedTable`.
31
+ """
32
+
33
+ def __init__(self, backend: str = "ray", **backend_kwargs):
34
+ self.backend = backend
35
+ self.backend_kwargs = backend_kwargs
36
+ self._ray = None
37
+ self._dask = None
38
+ self._initialized = False
39
+
40
+ def _ensure_ray(self):
41
+ if self._ray is None:
42
+ import ray # type: ignore
43
+
44
+ if not ray.is_initialized():
45
+ ray.init(**self.backend_kwargs)
46
+ self._ray = ray
47
+ return self._ray
48
+
49
+ def _ensure_dask(self):
50
+ if self._dask is None:
51
+ from dask.distributed import Client # type: ignore
52
+
53
+ self._dask = Client(**self.backend_kwargs)
54
+ return self._dask
55
+
56
+ def _init_backend(self):
57
+ if self._initialized:
58
+ return
59
+ if self.backend == "ray":
60
+ try:
61
+ self._ensure_ray()
62
+ except ImportError as exc:
63
+ logger.warning("Ray not installed; falling back to local execution: %s", exc)
64
+ self.backend = "local"
65
+ elif self.backend == "dask":
66
+ try:
67
+ self._ensure_dask()
68
+ except ImportError as exc:
69
+ logger.warning("Dask not installed; falling back to local execution: %s", exc)
70
+ self.backend = "local"
71
+ else:
72
+ self.backend = "local"
73
+ self._initialized = True
74
+
75
+ def read_table(
76
+ self,
77
+ ice: Any,
78
+ table_name: str,
79
+ columns: list[str] | None = None,
80
+ filter_expr: Any | None = None,
81
+ limit: int | None = None,
82
+ num_partitions: int = 4,
83
+ ) -> pl.DataFrame:
84
+ """
85
+ Read a table in parallel across the distributed backend.
86
+
87
+ Falls back to :meth:`UnifiedTable.read_table` if no distributed
88
+ backend is available.
89
+ """
90
+ self._init_backend()
91
+ if self.backend == "local":
92
+ return ice.read_table(table_name, columns=columns, filter_expr=filter_expr, limit=limit)
93
+
94
+ # Read the table locally first (single node), then repartition across
95
+ # the cluster. True distributed scan pushdown is format-dependent and
96
+ # left to backend-specific implementations.
97
+ df = ice.read_table(table_name, columns=columns, filter_expr=filter_expr, limit=limit)
98
+ if self.backend == "ray":
99
+ return self._ray_parallelize(df, num_partitions)
100
+ if self.backend == "dask":
101
+ return self._dask_parallelize(df, num_partitions)
102
+ return df
103
+
104
+ def write_table(
105
+ self,
106
+ ice: Any,
107
+ table_name: str,
108
+ df: pl.DataFrame,
109
+ mode: str = "append",
110
+ ) -> None:
111
+ """
112
+ Write a DataFrame to a table across the distributed backend.
113
+
114
+ Falls back to :meth:`UnifiedTable.append_to_table` / overwrite.
115
+ """
116
+ self._init_backend()
117
+ if self.backend == "local":
118
+ if mode == "overwrite":
119
+ ice.overwrite_table(table_name, df)
120
+ else:
121
+ ice.append_to_table(table_name, df)
122
+ return
123
+
124
+ # Gather to a single DataFrame then write (coordinated write).
125
+ if self.backend == "ray":
126
+ df = self._ray_gather(df)
127
+ elif self.backend == "dask":
128
+ df = self._dask_gather(df)
129
+
130
+ if mode == "overwrite":
131
+ ice.overwrite_table(table_name, df)
132
+ else:
133
+ ice.append_to_table(table_name, df)
134
+
135
+ def map_partitions(
136
+ self,
137
+ func: Callable[[pl.DataFrame], pl.DataFrame],
138
+ df: pl.DataFrame,
139
+ num_partitions: int = 4,
140
+ ) -> pl.DataFrame:
141
+ """Apply a function across partitions of a DataFrame."""
142
+ self._init_backend()
143
+ if self.backend == "local":
144
+ return func(df)
145
+ if self.backend == "ray":
146
+ return self._ray_map_partitions(func, df, num_partitions)
147
+ if self.backend == "dask":
148
+ return self._dask_map_partitions(func, df, num_partitions)
149
+ return func(df)
150
+
151
+ # -- Ray helpers -----------------------------------------------------
152
+
153
+ def _ray_parallelize(self, df: pl.DataFrame, num_partitions: int) -> pl.DataFrame:
154
+ ray = self._ensure_ray()
155
+
156
+ @ray.remote
157
+ def _process(chunk: pl.DataFrame) -> pl.DataFrame:
158
+ return chunk
159
+
160
+ chunks = [
161
+ df.slice(i, max(1, df.height // num_partitions))
162
+ for i in range(0, df.height, max(1, df.height // num_partitions))
163
+ ]
164
+ refs = [_process.remote(chunk) for chunk in chunks]
165
+ results = ray.get(refs)
166
+ return pl.concat(results) if results else df
167
+
168
+ def _ray_gather(self, df: pl.DataFrame) -> pl.DataFrame:
169
+ return df
170
+
171
+ def _ray_map_partitions(self, func, df, num_partitions):
172
+ ray = self._ensure_ray()
173
+
174
+ @ray.remote
175
+ def _map(chunk):
176
+ return func(chunk)
177
+
178
+ chunks = [
179
+ df.slice(i, max(1, df.height // num_partitions))
180
+ for i in range(0, df.height, max(1, df.height // num_partitions))
181
+ ]
182
+ refs = [_map.remote(chunk) for chunk in chunks]
183
+ return pl.concat(ray.get(refs)) if refs else df
184
+
185
+ # -- Dask helpers ----------------------------------------------------
186
+
187
+ def _dask_parallelize(self, df: pl.DataFrame, num_partitions: int) -> pl.DataFrame:
188
+ import dask.dataframe as dd # type: ignore
189
+
190
+ ddf = dd.from_pandas(df.to_pandas(), npartitions=num_partitions)
191
+ return pl.from_pandas(ddf.compute())
192
+
193
+ def _dask_gather(self, df: pl.DataFrame) -> pl.DataFrame:
194
+ return df
195
+
196
+ def _dask_map_partitions(self, func, df, num_partitions):
197
+ import dask.dataframe as dd # type: ignore
198
+
199
+ ddf = dd.from_pandas(df.to_pandas(), npartitions=num_partitions)
200
+ result = ddf.map_partitions(lambda pdf: func(pl.from_pandas(pdf)).to_pandas())
201
+ return pl.from_pandas(result.compute())
202
+
203
+ def shutdown(self):
204
+ """Shut down the distributed client."""
205
+ if self._dask is not None:
206
+ self._dask.close()
207
+ self._dask = None
208
+ if self._ray is not None:
209
+ try:
210
+ self._ray.shutdown()
211
+ except Exception: # noqa: BLE001
212
+ pass
213
+ self._ray = None
@@ -0,0 +1,93 @@
1
+ """Console script entry points for iceframex."""
2
+
3
+ import sys
4
+
5
+ from iceframex.core import UnifiedTable
6
+ from iceframex.mcp.server import start as mcp_start
7
+
8
+
9
+ def cli(argv: list[str] | None = None) -> int:
10
+ """Minimal CLI for iceframex.
11
+
12
+ Usage:
13
+ iceframex list-tables --config-uri http://localhost:8181 --config-type rest
14
+ iceframex mcp
15
+ """
16
+ argv = argv if argv is not None else sys.argv[1:]
17
+
18
+ if not argv:
19
+ print("iceframex - Unified lakehouse table API")
20
+ print("Commands:")
21
+ print(" list-tables List tables in a catalog namespace")
22
+ print(" read-table Read rows from a table")
23
+ print(" mcp Start the read-write MCP server")
24
+ return 0
25
+
26
+ command = argv[0]
27
+ rest = argv[1:]
28
+
29
+ if command == "mcp":
30
+ mcp_start()
31
+ return 0
32
+
33
+ if command in ("list-tables", "read-table"):
34
+ # Very small argparse-free parser for common flags.
35
+ config = {}
36
+ table_name = None
37
+ namespace = "default"
38
+ i = 0
39
+ while i < len(rest):
40
+ arg = rest[i]
41
+ if arg in ("--config-uri", "--uri"):
42
+ config["uri"] = rest[i + 1]
43
+ i += 2
44
+ elif arg in ("--config-type", "--type"):
45
+ config["type"] = rest[i + 1]
46
+ i += 2
47
+ elif arg in ("--config-warehouse", "--warehouse"):
48
+ config["warehouse"] = rest[i + 1]
49
+ i += 2
50
+ elif arg == "--namespace":
51
+ namespace = rest[i + 1]
52
+ i += 2
53
+ elif arg == "--table":
54
+ table_name = rest[i + 1]
55
+ i += 2
56
+ elif arg.startswith("--"):
57
+ i += 2
58
+ else:
59
+ table_name = arg
60
+ i += 1
61
+
62
+ if not config:
63
+ print("Error: --config-uri and --config-type are required.")
64
+ return 1
65
+
66
+ ice = UnifiedTable(config)
67
+
68
+ if command == "list-tables":
69
+ tables = ice.list_tables(namespace)
70
+ for t in tables:
71
+ print(t)
72
+ return 0
73
+
74
+ if command == "read-table":
75
+ if not table_name:
76
+ print("Error: --table is required for read-table.")
77
+ return 1
78
+ df = ice.read_table(table_name, limit=20)
79
+ print(df)
80
+ return 0
81
+
82
+ print(f"Unknown command: {command}")
83
+ return 1
84
+
85
+
86
+ def chat(argv: list[str] | None = None) -> int:
87
+ """Placeholder for the LLM chat entry point (agent extra)."""
88
+ print("iceframex-chat requires the 'agent' extra: pip install iceframex[agent]")
89
+ return 0
90
+
91
+
92
+ if __name__ == "__main__":
93
+ raise SystemExit(cli())
@@ -0,0 +1,33 @@
1
+ """Exception hierarchy for iceframex."""
2
+
3
+
4
+ class IceFrameXError(Exception):
5
+ """Base exception for all iceframex errors."""
6
+
7
+
8
+ class CatalogError(IceFrameXError):
9
+ """Raised when a catalog operation fails (connect, list, create, drop)."""
10
+
11
+
12
+ class TableNotFoundError(IceFrameXError):
13
+ """Raised when a requested table does not exist."""
14
+
15
+
16
+ class SchemaError(IceFrameXError):
17
+ """Raised when a table schema is invalid or incompatible."""
18
+
19
+
20
+ class ValidationError(IceFrameXError):
21
+ """Raised when user input fails validation."""
22
+
23
+
24
+ class UnsupportedFormatError(IceFrameXError):
25
+ """Raised when a table format is not supported by a backend."""
26
+
27
+
28
+ class UnsupportedOperationError(IceFrameXError):
29
+ """Raised when an operation is not supported for a given table format."""
30
+
31
+
32
+ class ConfigurationError(IceFrameXError):
33
+ """Raised when catalog or backend configuration is missing or invalid."""
@@ -0,0 +1,62 @@
1
+ """Multi-format table abstraction.
2
+
3
+ Defines the :class:`TableFormat` enum and :func:`detect_format` helper so that
4
+ :class:`~iceframex.core.UnifiedTable` can dispatch to the correct backend
5
+ (Iceberg, Delta Lake, or Apache Hudi) based on user input or table metadata.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from enum import Enum
11
+
12
+
13
+ class TableFormat(str, Enum):
14
+ """Supported lakehouse table formats."""
15
+
16
+ ICEBERG = "iceberg"
17
+ DELTA = "delta"
18
+ HUDI = "hudi"
19
+
20
+ @classmethod
21
+ def from_string(cls, value: str) -> TableFormat:
22
+ """Parse a user-facing format string into a :class:`TableFormat`."""
23
+ try:
24
+ return cls(value.lower())
25
+ except ValueError as exc:
26
+ from iceframex.exceptions import UnsupportedFormatError
27
+
28
+ raise UnsupportedFormatError(
29
+ f"Unsupported table format '{value}'. "
30
+ f"Supported formats: {[f.value for f in TableFormat]}"
31
+ ) from exc
32
+
33
+
34
+ def detect_format(path: str | None = None, format: str | None = None) -> TableFormat:
35
+ """Detect the table format.
36
+
37
+ Resolution order:
38
+ 1. Explicit ``format`` argument wins.
39
+ 2. If a path is given, inspect its extension/directory markers.
40
+ 3. Default to Iceberg.
41
+
42
+ Args:
43
+ path: Optional filesystem path to a table directory or file.
44
+ format: Optional explicit format name ('iceberg', 'delta', 'hudi').
45
+
46
+ Returns:
47
+ A :class:`TableFormat` member.
48
+ """
49
+ if format is not None:
50
+ return TableFormat.from_string(format)
51
+
52
+ if path is not None:
53
+ lower = path.lower()
54
+ # Delta tables carry a `_delta_log/` directory; Hudi carries
55
+ # `.hoodie/`. Iceberg relies on catalog metadata, so we can't
56
+ # reliably detect it from path alone — default to iceberg.
57
+ if "_delta_log" in lower or lower.endswith(".delta"):
58
+ return TableFormat.DELTA
59
+ if ".hoodie" in lower or lower.endswith(".hudi"):
60
+ return TableFormat.HUDI
61
+
62
+ return TableFormat.ICEBERG