icetrace 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.
icetrace/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """icetrace — Scan-planning & metadata forensics engine for Apache Iceberg."""
2
+
3
+ __version__ = "0.1.0"
4
+ __all__ = ["__version__"]
@@ -0,0 +1,5 @@
1
+ """Catalog adapter package."""
2
+
3
+ from icetrace.catalog.adapter import CatalogConnectionError, IcebergCatalogAdapter
4
+
5
+ __all__ = ["CatalogConnectionError", "IcebergCatalogAdapter"]
@@ -0,0 +1,212 @@
1
+ """Strictly read-only, metadata-only Catalog Adapter built on PyIceberg."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ from pyiceberg.catalog import Catalog, load_catalog
9
+ from pyiceberg.table import Table
10
+
11
+ from icetrace.catalog.bounds import resolve_metrics_mode
12
+ from icetrace.models import (
13
+ ColumnSchemaInfo,
14
+ PartitionFieldInfo,
15
+ PartitionSpecInfo,
16
+ SnapshotSummaryInfo,
17
+ SortFieldInfo,
18
+ TableLayoutReport,
19
+ )
20
+
21
+
22
+ class CatalogConnectionError(RuntimeError):
23
+ """Raised when an Iceberg catalog or table cannot be loaded."""
24
+
25
+
26
+ class IcebergCatalogAdapter:
27
+ """Modular, read-only adapter wrapping PyIceberg catalogs (Glue, REST, SQL, Hive).
28
+
29
+ Can be initialized either with an already-instantiated PyIceberg `Catalog`
30
+ (ideal for local demos & zero-credential tests) or resolved lazily via
31
+ `~/.pyiceberg.yaml` and environment variables (`ICETRACE_CATALOG_*` / `AWS_*`).
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ catalog_name: str = "default",
37
+ catalog: Catalog | None = None,
38
+ properties: dict[str, Any] | None = None,
39
+ ) -> None:
40
+ self.catalog_name = catalog_name
41
+ self._catalog = catalog
42
+ self._properties = properties or {}
43
+
44
+ @property
45
+ def catalog(self) -> Catalog:
46
+ if self._catalog is None:
47
+ self._catalog = self._load_catalog()
48
+ return self._catalog
49
+
50
+ def _load_catalog(self) -> Catalog:
51
+ props: dict[str, Any] = dict(self._properties)
52
+
53
+ # Allow zero-config environment-driven connection for Glue / REST / SQL
54
+ env_type = os.environ.get("ICETRACE_CATALOG_TYPE")
55
+ if env_type and "type" not in props:
56
+ props["type"] = env_type
57
+ env_uri = os.environ.get("ICETRACE_CATALOG_URI")
58
+ if env_uri and "uri" not in props:
59
+ props["uri"] = env_uri
60
+ env_warehouse = os.environ.get("ICETRACE_WAREHOUSE")
61
+ if env_warehouse and "warehouse" not in props:
62
+ props["warehouse"] = env_warehouse
63
+ env_token = os.environ.get("ICETRACE_TOKEN")
64
+ if env_token and "token" not in props:
65
+ props["token"] = env_token
66
+
67
+ # Auto-detect Glue if AWS_PROFILE or AWS_REGION is set and no explicit type/pyiceberg.yaml
68
+ if not props and (
69
+ os.environ.get("ICETRACE_GLUE") == "1" or os.environ.get("ICETRACE_CATALOG_TYPE") == "glue"
70
+ ):
71
+ props["type"] = "glue"
72
+
73
+ try:
74
+ if props:
75
+ return load_catalog(self.catalog_name, **props)
76
+ return load_catalog(self.catalog_name)
77
+ except Exception as exc:
78
+ raise CatalogConnectionError(
79
+ f"Failed to load Iceberg catalog '{self.catalog_name}': {exc}. "
80
+ "Configure ~/.pyiceberg.yaml or set ICETRACE_CATALOG_TYPE (e.g. glue, rest, sql)."
81
+ ) from exc
82
+
83
+ def list_namespaces(self) -> list[str]:
84
+ return [".".join(ns) for ns in self.catalog.list_namespaces()]
85
+
86
+ def list_tables(self, namespace: str | None = None, limit: int = 100) -> tuple[list[str], list[str]]:
87
+ namespaces = [namespace] if namespace else self.list_namespaces()
88
+ tables: list[str] = []
89
+ for ns in namespaces:
90
+ for ident in self.catalog.list_tables(ns):
91
+ tables.append(".".join(ident))
92
+ if len(tables) >= limit:
93
+ return namespaces, tables
94
+ return namespaces, tables
95
+
96
+ def load_table(self, table_identifier: str) -> Table:
97
+ try:
98
+ return self.catalog.load_table(table_identifier)
99
+ except Exception as exc:
100
+ raise CatalogConnectionError(
101
+ f"Failed to load table '{table_identifier}' from catalog '{self.catalog_name}': {exc}"
102
+ ) from exc
103
+
104
+ def inspect_table_layout(
105
+ self,
106
+ table_identifier: str,
107
+ snapshot_limit: int = 20,
108
+ ) -> TableLayoutReport:
109
+ """Read-only inspection of table metadata.json (zero manifest reads)."""
110
+ table = self.load_table(table_identifier)
111
+ meta = table.metadata
112
+ props = dict(meta.properties)
113
+
114
+ columns: list[ColumnSchemaInfo] = []
115
+ for idx, field in enumerate(table.schema().fields, start=1):
116
+ mode, _ = resolve_metrics_mode(field.name, idx, props)
117
+ columns.append(
118
+ ColumnSchemaInfo(
119
+ field_id=field.field_id,
120
+ name=field.name,
121
+ ordinal=idx,
122
+ type_str=str(field.field_type),
123
+ required=field.required,
124
+ metrics_mode=mode,
125
+ )
126
+ )
127
+
128
+ partition_specs: list[PartitionSpecInfo] = []
129
+ for spec in meta.partition_specs:
130
+ partition_specs.append(
131
+ PartitionSpecInfo(
132
+ spec_id=spec.spec_id,
133
+ is_default=(spec.spec_id == meta.default_spec_id),
134
+ fields=[
135
+ PartitionFieldInfo(
136
+ field_id=pf.field_id,
137
+ source_id=pf.source_id,
138
+ name=pf.name,
139
+ transform=str(pf.transform),
140
+ )
141
+ for pf in spec.fields
142
+ ],
143
+ )
144
+ )
145
+
146
+ default_sort_fields: list[SortFieldInfo] = []
147
+ sort_order = table.sort_order()
148
+ for sf in sort_order.fields:
149
+ default_sort_fields.append(
150
+ SortFieldInfo(
151
+ source_id=sf.source_id,
152
+ transform=str(sf.transform),
153
+ direction=str(sf.direction),
154
+ null_order=str(sf.null_order),
155
+ )
156
+ )
157
+
158
+ metrics_props = {
159
+ k: v for k, v in props.items() if k.startswith("write.metadata.metrics")
160
+ }
161
+ retention_props = {
162
+ k: v
163
+ for k, v in props.items()
164
+ if k.startswith("history.expire")
165
+ or k.startswith("write.metadata.delete-after-commit")
166
+ or k.startswith("write.metadata.previous-versions-max")
167
+ or k.startswith("gc.enabled")
168
+ }
169
+
170
+ all_snapshots = list(meta.snapshots)
171
+ recent = sorted(all_snapshots, key=lambda s: s.timestamp_ms, reverse=True)[:snapshot_limit]
172
+ snapshot_infos: list[SnapshotSummaryInfo] = []
173
+ for snap in recent:
174
+ summary = snap.summary
175
+ additional = summary.additional_properties if summary else {}
176
+
177
+ def _int(key: str, _add: dict[str, str] = additional) -> int | None:
178
+ val = _add.get(key)
179
+ return int(val) if val is not None and val.lstrip("-").isdigit() else None
180
+
181
+ snapshot_infos.append(
182
+ SnapshotSummaryInfo(
183
+ snapshot_id=snap.snapshot_id,
184
+ parent_snapshot_id=snap.parent_snapshot_id,
185
+ sequence_number=snap.sequence_number,
186
+ timestamp_ms=snap.timestamp_ms,
187
+ operation=str(summary.operation.value) if summary and summary.operation else None,
188
+ added_data_files=_int("added-data-files"),
189
+ deleted_data_files=_int("deleted-data-files"),
190
+ added_delete_files=_int("added-delete-files"),
191
+ total_data_files=_int("total-data-files"),
192
+ total_records=_int("total-records"),
193
+ total_files_size_bytes=_int("total-files-size"),
194
+ )
195
+ )
196
+
197
+ return TableLayoutReport(
198
+ table=table_identifier,
199
+ catalog=self.catalog_name,
200
+ location=meta.location,
201
+ format_version=meta.format_version,
202
+ table_uuid=str(meta.table_uuid),
203
+ current_snapshot_id=meta.current_snapshot_id,
204
+ total_snapshots=len(all_snapshots),
205
+ columns=columns,
206
+ partition_specs=partition_specs,
207
+ default_sort_order_id=meta.default_sort_order_id,
208
+ default_sort_fields=default_sort_fields,
209
+ metrics_properties=metrics_props,
210
+ retention_properties=retention_props,
211
+ recent_snapshots=snapshot_infos,
212
+ )
@@ -0,0 +1,114 @@
1
+ """Iceberg binary bound decoding and metrics-mode resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from decimal import Decimal
7
+ from typing import Any
8
+ from uuid import UUID
9
+
10
+ from pyiceberg.conversions import from_bytes
11
+ from pyiceberg.types import (
12
+ BinaryType,
13
+ BooleanType,
14
+ DateType,
15
+ DecimalType,
16
+ DoubleType,
17
+ FixedType,
18
+ FloatType,
19
+ IcebergType,
20
+ IntegerType,
21
+ LongType,
22
+ PrimitiveType,
23
+ StringType,
24
+ TimestampType,
25
+ TimestamptzType,
26
+ TimeType,
27
+ UUIDType,
28
+ )
29
+
30
+ DEFAULT_MAX_INFERRED_COLUMN_METRICS = 32
31
+ DEFAULT_METRICS_MODE = "truncate(16)"
32
+ _TRUNCATE_RE = re.compile(r"^truncate\((\d+)\)$")
33
+
34
+
35
+ def decode_bound(iceberg_type: IcebergType, raw: bytes | Any) -> Any:
36
+ """Decode an Iceberg binary-encoded column bound into a native Python value."""
37
+ if raw is None:
38
+ return None
39
+ if not isinstance(raw, (bytes, bytearray, memoryview)):
40
+ return raw
41
+ if not isinstance(iceberg_type, PrimitiveType):
42
+ return None
43
+ try:
44
+ return from_bytes(iceberg_type, bytes(raw))
45
+ except Exception:
46
+ return None
47
+
48
+
49
+ def is_orderable_type(iceberg_type: IcebergType) -> bool:
50
+ """Return True if column bounds support meaningful interval-overlap math."""
51
+ return isinstance(
52
+ iceberg_type,
53
+ (
54
+ IntegerType,
55
+ LongType,
56
+ FloatType,
57
+ DoubleType,
58
+ DecimalType,
59
+ DateType,
60
+ TimeType,
61
+ TimestampType,
62
+ TimestamptzType,
63
+ StringType,
64
+ UUIDType,
65
+ BooleanType,
66
+ BinaryType,
67
+ FixedType,
68
+ ),
69
+ )
70
+
71
+
72
+ def normalize_comparable(value: Any) -> Any:
73
+ """Normalize decoded bound values so homogeneous values sort deterministically."""
74
+ if isinstance(value, UUID):
75
+ return value.bytes
76
+ if isinstance(value, Decimal):
77
+ return value
78
+ return value
79
+
80
+
81
+ def resolve_metrics_mode(
82
+ column_name: str,
83
+ ordinal: int,
84
+ table_properties: dict[str, str],
85
+ ) -> tuple[str, int | None]:
86
+ """Resolve effective Iceberg metrics mode and optional truncation width for a column.
87
+
88
+ Follows Apache Iceberg's MetricsConfig semantics:
89
+ 1. Explicit `write.metadata.metrics.column.<name>` overrides everything.
90
+ 2. Otherwise, if ordinal > `write.metadata.metrics.max-inferred-column-defaults` (default 32),
91
+ Iceberg records NO metrics (`none`) unless overridden.
92
+ 3. Otherwise, falls back to `write.metadata.metrics.default` (default `truncate(16)`).
93
+ """
94
+ col_key = f"write.metadata.metrics.column.{column_name}"
95
+ if col_key in table_properties:
96
+ mode = table_properties[col_key].strip().lower()
97
+ else:
98
+ max_inferred = int(
99
+ table_properties.get(
100
+ "write.metadata.metrics.max-inferred-column-defaults",
101
+ str(DEFAULT_MAX_INFERRED_COLUMN_METRICS),
102
+ )
103
+ )
104
+ if ordinal > max_inferred:
105
+ mode = "none"
106
+ else:
107
+ mode = table_properties.get(
108
+ "write.metadata.metrics.default",
109
+ DEFAULT_METRICS_MODE,
110
+ ).strip().lower()
111
+
112
+ m = _TRUNCATE_RE.match(mode)
113
+ trunc_width = int(m.group(1)) if m else None
114
+ return mode, trunc_width
@@ -0,0 +1 @@
1
+ """Secondary CLI interface for icetrace."""
icetrace/cli/main.py ADDED
@@ -0,0 +1,355 @@
1
+ """Rich CLI for icetrace (secondary interface for local debugging, demos, and CI)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shutil
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+ from rich.table import Table as RichTable
12
+
13
+ from icetrace import __version__
14
+ from icetrace.catalog.adapter import IcebergCatalogAdapter
15
+ from icetrace.demo import create_demo_catalog
16
+ from icetrace.engine.audit import audit_pruning_health
17
+ from icetrace.engine.diff import diff_snapshots
18
+ from icetrace.engine.planner import explain_scan
19
+ from icetrace.mcp.server import main as run_mcp_server
20
+ from icetrace.models import PruningAuditReport, ScanPlanReport, SnapshotDiffReport
21
+
22
+ app = typer.Typer(
23
+ name="icetrace",
24
+ help="Scan-planning & metadata forensics engine for Apache Iceberg (EXPLAIN ANALYZE without Spark).",
25
+ no_args_is_help=True,
26
+ )
27
+ console = Console()
28
+
29
+
30
+ def _fmt_bytes(num: int | float) -> str:
31
+ val = float(num)
32
+ for unit in ("B", "KB", "MB", "GB", "TB"):
33
+ if abs(val) < 1024.0:
34
+ return f"{val:.1f} {unit}"
35
+ val /= 1024.0
36
+ return f"{val:.1f} PB"
37
+
38
+
39
+ def _render_scan_report(report: ScanPlanReport) -> None:
40
+ f = report.observed_facts
41
+ console.print(
42
+ Panel.fit(
43
+ f"[bold cyan]icetrace explain[/bold cyan] [bold]{report.table}[/bold]\n"
44
+ f"Catalog: [dim]{report.catalog}[/dim] | Snapshot: [dim]{report.snapshot_id}[/dim] | "
45
+ f"Sampled: [dim]{report.sampled}[/dim]\n"
46
+ f"Predicate: [yellow]{report.predicate or '(none)'}[/yellow]",
47
+ border_style="cyan",
48
+ )
49
+ )
50
+
51
+ funnel = RichTable(title="4-Stage Pruning Funnel (Metadata Only)", show_header=True, header_style="bold")
52
+ funnel.add_column("Stage")
53
+ funnel.add_column("Evaluated", justify="right")
54
+ funnel.add_column("Pruned", justify="right")
55
+ funnel.add_column("Surviving", justify="right")
56
+ funnel.add_column("Pruned %", justify="right")
57
+
58
+ s1 = f.stage1_manifest_list
59
+ s2 = f.stage2_partitions
60
+ s3 = f.stage3_column_bounds
61
+ s4 = f.stage4_deletes
62
+
63
+ funnel.add_row(
64
+ "1. Manifest List (Partition Summaries)",
65
+ str(s1.total_data_manifests),
66
+ str(s1.pruned_data_manifests),
67
+ str(s1.surviving_data_manifests),
68
+ f"{s1.pruned_pct:.1f}%",
69
+ )
70
+ funnel.add_row(
71
+ "2. Manifest Entries (Partition Tuples)",
72
+ str(s2.evaluated_data_files),
73
+ str(s2.pruned_by_partition),
74
+ str(s2.surviving_after_partition),
75
+ f"{s2.pruned_pct:.1f}%",
76
+ )
77
+ funnel.add_row(
78
+ "3. Column Bounds (Min/Max/Null Metrics)",
79
+ str(s3.evaluated_data_files),
80
+ str(s3.pruned_by_bounds),
81
+ f"[bold]{s3.surviving_data_files}[/bold]",
82
+ f"{s3.pruned_pct:.1f}%",
83
+ )
84
+ funnel.add_row(
85
+ "4. Surviving Bytes / Delete Files",
86
+ _fmt_bytes(s3.total_bytes_evaluated),
87
+ f"{s3.bytes_pruned_pct:.1f}% bytes pruned",
88
+ f"{_fmt_bytes(s3.surviving_bytes)} ({s4.total_delete_files} deletes)",
89
+ "-",
90
+ )
91
+ console.print(funnel)
92
+
93
+ if f.survival_reasons:
94
+ reasons_str = ", ".join(f"[bold]{k}[/bold]: {v}" for k, v in f.survival_reasons.items())
95
+ console.print(f"\n[bold]Survival Attribution:[/bold] {reasons_str}")
96
+
97
+ if report.diagnoses:
98
+ diag_tbl = RichTable(title="Inferred Diagnoses", show_header=True, header_style="bold")
99
+ diag_tbl.add_column("Severity", width=8)
100
+ diag_tbl.add_column("Code", width=26)
101
+ diag_tbl.add_column("Evidence & Recommendation")
102
+ for d in report.diagnoses:
103
+ sev_color = {"HIGH": "red", "MEDIUM": "yellow", "LOW": "blue", "INFO": "dim"}.get(d.severity, "white")
104
+ diag_tbl.add_row(
105
+ f"[{sev_color}]{d.severity}[/{sev_color}]",
106
+ d.code,
107
+ f"[bold]Evidence:[/bold] {d.evidence}\n[bold]Fix:[/bold] {d.recommendation}",
108
+ )
109
+ console.print(diag_tbl)
110
+ else:
111
+ console.print("\n[green]No pruning anomalies detected for this predicate.[/green]")
112
+
113
+
114
+ def _render_audit_report(report: PruningAuditReport) -> None:
115
+ s = report.observed_facts.table_summary
116
+ console.print(
117
+ Panel.fit(
118
+ f"[bold cyan]icetrace audit[/bold cyan] [bold]{report.table}[/bold] (Format v{s.format_version})\n"
119
+ f"Files: {s.live_data_files} data ({_fmt_bytes(s.total_data_bytes)}) | "
120
+ f"Deletes: {s.live_delete_files} (pos={s.position_delete_files}, eq={s.equality_delete_files}, dv={s.deletion_vectors}) | "
121
+ f"Manifests: {s.data_manifests_count} | Snapshots: {s.total_snapshots}",
122
+ border_style="cyan",
123
+ )
124
+ )
125
+
126
+ tbl = RichTable(title="Per-Column Pruning Readiness", show_header=True, header_style="bold")
127
+ tbl.add_column("#", justify="right", no_wrap=True)
128
+ tbl.add_column("Column", no_wrap=True)
129
+ tbl.add_column("Mode", no_wrap=True)
130
+ tbl.add_column("Bounds", justify="right", no_wrap=True)
131
+ tbl.add_column("Overlap", justify="right", no_wrap=True)
132
+ tbl.add_column("Trunc%", justify="right", no_wrap=True)
133
+ tbl.add_column("Grade", justify="center", no_wrap=True)
134
+ tbl.add_column("Issues", overflow="fold")
135
+
136
+ for c in report.observed_facts.column_pruning_scores:
137
+ grade_color = {"A": "green", "B": "green", "C": "yellow", "D": "dark_orange", "F": "red"}.get(
138
+ c.pruning_grade, "dim"
139
+ )
140
+ ov_str = f"{c.overlap_ratio:.2f}" if c.overlap_ratio is not None else "-"
141
+ tbl.add_row(
142
+ str(c.ordinal),
143
+ c.column,
144
+ c.metrics_mode,
145
+ f"{c.bounds_coverage_pct:.0f}%",
146
+ ov_str,
147
+ f"{c.truncation_collision_pct:.0f}%",
148
+ f"[{grade_color}][bold]{c.pruning_grade}[/bold][/{grade_color}]",
149
+ "; ".join(c.issues) if c.issues else "[dim]ok[/dim]",
150
+ )
151
+ console.print(tbl)
152
+
153
+ if report.diagnoses:
154
+ console.print("\n[bold]Top Diagnoses:[/bold]")
155
+ for d in report.diagnoses:
156
+ console.print(f" • [bold]{d.severity}[/bold] [{d.code}]: {d.evidence} -> [dim]{d.recommendation}[/dim]")
157
+
158
+
159
+ def _render_diff_report(report: SnapshotDiffReport) -> None:
160
+ d = report.delta_facts
161
+ console.print(
162
+ Panel.fit(
163
+ f"[bold cyan]icetrace diff[/bold cyan] [bold]{report.table}[/bold]\n"
164
+ f"Snapshots: {d.from_snapshot_id} -> {d.to_snapshot_id}\n"
165
+ f"Manifests: {d.data_manifests_delta:+d} | Data Files: {d.data_files_delta:+d} | "
166
+ f"Deletes: {d.delete_files_delta:+d} | Bytes: {_fmt_bytes(d.total_bytes_delta)}",
167
+ border_style="cyan",
168
+ )
169
+ )
170
+ if d.predicate and d.surviving_files_delta is not None:
171
+ console.print(
172
+ f"Predicate [yellow]{d.predicate}[/yellow]: "
173
+ f"{d.from_surviving_files} -> {d.to_surviving_files} surviving files ({d.surviving_files_delta:+d})"
174
+ )
175
+ for diag in report.diagnoses:
176
+ console.print(f" • [bold]{diag.severity}[/bold] [{diag.code}]: {diag.evidence}")
177
+
178
+
179
+ @app.command()
180
+ def version() -> None:
181
+ """Print icetrace version."""
182
+ console.print(f"icetrace {__version__}")
183
+
184
+
185
+ @app.command()
186
+ def demo(
187
+ json_output: bool = typer.Option(False, "--json", help="Emit machine-readable JSON output."),
188
+ ) -> None:
189
+ """Run an instant zero-credential demo showcasing 3 real Iceberg pruning traps."""
190
+ catalog, tmp_dir, table_id = create_demo_catalog()
191
+ try:
192
+ table = catalog.load_table(table_id)
193
+ # 1. Healthy sorted column vs broken truncate(16) vs 32-column cutoff
194
+ scan_trunc = explain_scan(
195
+ table=table,
196
+ table_identifier=table_id,
197
+ catalog_name="demo",
198
+ predicate_sql="tenant_id = 'org_prod_us_east_03_0042'",
199
+ )
200
+ scan_cutoff = explain_scan(
201
+ table=table,
202
+ table_identifier=table_id,
203
+ catalog_name="demo",
204
+ predicate_sql="trace_key = 'tr_03_0042'",
205
+ )
206
+ audit = audit_pruning_health(
207
+ table=table,
208
+ table_identifier=table_id,
209
+ catalog_name="demo",
210
+ columns=["event_id", "tenant_id", "amount", "trace_key"],
211
+ )
212
+
213
+ if json_output:
214
+ console.print_json(
215
+ json.dumps(
216
+ {
217
+ "explain_truncated_bounds": scan_trunc.model_dump(),
218
+ "explain_32_col_cutoff": scan_cutoff.model_dump(),
219
+ "audit": audit.model_dump(),
220
+ }
221
+ )
222
+ )
223
+ return
224
+
225
+ console.print(
226
+ "\n[bold green]Demo 1:[/bold green] Query filtering [yellow]tenant_id[/yellow] "
227
+ "(16-char default truncate collision)\n"
228
+ )
229
+ _render_scan_report(scan_trunc)
230
+
231
+ console.print(
232
+ "\n[bold green]Demo 2:[/bold green] Query filtering [yellow]trace_key[/yellow] "
233
+ "(column #35 > Iceberg 32-column default metrics limit)\n"
234
+ )
235
+ _render_scan_report(scan_cutoff)
236
+
237
+ console.print("\n[bold green]Demo 3:[/bold green] Table Pruning Health Audit\n")
238
+ _render_audit_report(audit)
239
+ finally:
240
+ shutil.rmtree(tmp_dir, ignore_errors=True)
241
+
242
+
243
+ @app.command()
244
+ def tables(
245
+ namespace: str | None = typer.Option(None, "--namespace", "-n"),
246
+ catalog: str = typer.Option("default", "--catalog", "-c"),
247
+ json_output: bool = typer.Option(False, "--json"),
248
+ ) -> None:
249
+ """List namespaces and tables in the configured catalog."""
250
+ adapter = IcebergCatalogAdapter(catalog_name=catalog)
251
+ ns, tbls = adapter.list_tables(namespace=namespace)
252
+ if json_output:
253
+ console.print_json(json.dumps({"catalog": catalog, "namespaces": ns, "tables": tbls}))
254
+ return
255
+ for t in tbls:
256
+ console.print(t)
257
+
258
+
259
+ @app.command()
260
+ def explain(
261
+ table: str = typer.Argument(..., help="Table identifier, e.g. db.events"),
262
+ where: str = typer.Option(..., "--where", "-w", help="SQL WHERE predicate to simulate"),
263
+ catalog: str = typer.Option("default", "--catalog", "-c"),
264
+ snapshot_id: int | None = typer.Option(None, "--snapshot-id", "-s"),
265
+ max_manifests: int = typer.Option(200, "--max-manifests"),
266
+ json_output: bool = typer.Option(False, "--json"),
267
+ ) -> None:
268
+ """Simulate Iceberg's 4-stage scan planning for a SQL WHERE predicate (metadata-only)."""
269
+ adapter = IcebergCatalogAdapter(catalog_name=catalog)
270
+ tbl = adapter.load_table(table)
271
+ report = explain_scan(
272
+ table=tbl,
273
+ table_identifier=table,
274
+ catalog_name=catalog,
275
+ predicate_sql=where,
276
+ snapshot_id=snapshot_id,
277
+ max_manifests=max_manifests,
278
+ )
279
+ if json_output:
280
+ console.print_json(report.model_dump_json())
281
+ else:
282
+ _render_scan_report(report)
283
+
284
+
285
+ @app.command()
286
+ def audit(
287
+ table: str = typer.Argument(..., help="Table identifier, e.g. db.events"),
288
+ columns: list[str] | None = typer.Option(None, "--column", help="Filter to specific column(s)"),
289
+ catalog: str = typer.Option("default", "--catalog", "-c"),
290
+ snapshot_id: int | None = typer.Option(None, "--snapshot-id", "-s"),
291
+ max_manifests: int = typer.Option(200, "--max-manifests"),
292
+ json_output: bool = typer.Option(False, "--json"),
293
+ ) -> None:
294
+ """Audit per-column pruning readiness, bounds overlap, and table metadata health."""
295
+ adapter = IcebergCatalogAdapter(catalog_name=catalog)
296
+ tbl = adapter.load_table(table)
297
+ report = audit_pruning_health(
298
+ table=tbl,
299
+ table_identifier=table,
300
+ catalog_name=catalog,
301
+ columns=columns,
302
+ snapshot_id=snapshot_id,
303
+ max_manifests=max_manifests,
304
+ )
305
+ if json_output:
306
+ console.print_json(report.model_dump_json())
307
+ else:
308
+ _render_audit_report(report)
309
+
310
+
311
+ @app.command()
312
+ def diff(
313
+ table: str = typer.Argument(..., help="Table identifier, e.g. db.events"),
314
+ from_snapshot: int | None = typer.Option(None, "--from", help="Earlier snapshot ID (defaults to parent)"),
315
+ to_snapshot: int | None = typer.Option(None, "--to", help="Later snapshot ID (defaults to current)"),
316
+ where: str | None = typer.Option(None, "--where", "-w", help="Optional SQL WHERE predicate to diff pruning"),
317
+ catalog: str = typer.Option("default", "--catalog", "-c"),
318
+ json_output: bool = typer.Option(False, "--json"),
319
+ ) -> None:
320
+ """Compare layout health and pruning regressions between two snapshots."""
321
+ adapter = IcebergCatalogAdapter(catalog_name=catalog)
322
+ tbl = adapter.load_table(table)
323
+ report = diff_snapshots(
324
+ table=tbl,
325
+ table_identifier=table,
326
+ catalog_name=catalog,
327
+ from_snapshot_id=from_snapshot,
328
+ to_snapshot_id=to_snapshot,
329
+ predicate_sql=where,
330
+ )
331
+ if json_output:
332
+ console.print_json(report.model_dump_json())
333
+ else:
334
+ _render_diff_report(report)
335
+
336
+
337
+ @app.command()
338
+ def inspect(
339
+ table: str = typer.Argument(..., help="Table identifier, e.g. db.events"),
340
+ catalog: str = typer.Option("default", "--catalog", "-c"),
341
+ json_output: bool = typer.Option(False, "--json"),
342
+ ) -> None:
343
+ """Inspect table metadata.json (schema ordinals, partition specs, sort order, properties)."""
344
+ adapter = IcebergCatalogAdapter(catalog_name=catalog)
345
+ report = adapter.inspect_table_layout(table_identifier=table)
346
+ if json_output:
347
+ console.print_json(report.model_dump_json())
348
+ return
349
+ console.print_json(report.model_dump_json(indent=2))
350
+
351
+
352
+ @app.command()
353
+ def mcp() -> None:
354
+ """Start the icetrace stdio MCP server for Cursor / Claude Code."""
355
+ run_mcp_server()