From 88ba75c4f7b019084cbe5d883bba59b27500c82a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 22:44:37 +0000 Subject: [PATCH 01/25] build(deps): Update duckdb requirement from <2,>=1.1 to >=1.1,<3 Updates the requirements on [duckdb](https://github.com/duckdb/duckdb-python) to permit the latest version. - [Release notes](https://github.com/duckdb/duckdb-python/releases) - [Commits](https://github.com/duckdb/duckdb-python/compare/v1.3.0...v2.0.0) --- updated-dependencies: - dependency-name: duckdb dependency-version: 2.0.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- pyproject.toml | 2 +- requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 83b9382..404ee22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,7 @@ dependencies = [ "openpyxl>=3.1,<4", # .xlsx reader — handles sparse cells correctly (see bathing_water/README.md) "xlrd>=2.0,<3", # legacy .xls, some older SDI deliveries "lxml>=5.2,<7", # ISO 19115-3 metadata records - "duckdb>=1.1,<2", # validate parquet with SQL before it ever leaves the machine + "duckdb>=1.1,<3", # validate parquet with SQL before it ever leaves the machine # geometry: source encoding in, WKB out (see CLAUDE.md). shapely 2.x only — # the from_wkt/from_geojson/to_wkb vectorised API the prepare step uses # does not exist in 1.x. No GDAL/geopandas: reading a GeoPackage or GDB diff --git a/requirements.txt b/requirements.txt index 10b0b32..7d2a58e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,7 +3,7 @@ pyarrow>=25 # parquet writer + the Arrow types the ingest lane e openpyxl>=3.1,<4 # .xlsx reader — handles sparse cells correctly (see bathing_water/README.md) xlrd>=2.0,<3 # legacy .xls, some older SDI deliveries lxml>=5.2,<7 # ISO 19115-3 metadata records -duckdb>=1.1,<2 # validate parquet with SQL before it ever leaves the machine +duckdb>=1.1,<3 # validate parquet with SQL before it ever leaves the machine # --- geometry: source encoding in, WKB out (see CLAUDE.md) ----------------- # shapely 2.x only — the from_wkt/from_geojson/to_wkb vectorised API the From 0bbea9c59894db71fb4cc51e74c263557553d465 Mon Sep 17 00:00:00 2001 From: Oskar Esparza <50017101+oskaresparza@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:21:09 +0100 Subject: [PATCH 02/25] Set default Python env manager in VS Code workspace settings Co-Authored-By: Claude Opus 5.5 --- .vscode/settings.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 500b19c..92669de 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python3" + "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python3", + "python-envs.defaultEnvManager": "ms-python.python:system" } From ddcf3887a5ab383075d458cd204a3353bb354f38 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:11:25 +0100 Subject: [PATCH 03/25] Put %catalog behind a backend interface and add the backend switch First step of the Polaris migration: no behaviour change on Dremio. - catalog/backend.py: CatalogBackend, the operations CatalogSession needs (exists, is_folder, list_datasets/list_dataset_kinds, entry_kind/ entry_exists, drop_entry, ensure_folder_path, require_table_or_view, publish_target/check_publish/publish_dataflow, plus the existing verbs) and the catalog root that starts every absolute path. - Catalog (Dremio) implements it with thin public methods over what the session used to reach into _catalog_rest/_executor/_flight_executor for. - The Dremio publish machinery (PUBLIC_ROOT, plan, backup/rollback) moves unchanged to catalog/dremio_publish.py; the shared folder layout (draft, versions, reference, #public) to catalog/layout.py. Both are still importable from catalog.session. - CatalogSession talks only to CatalogBackend and takes its root from the backend ("catalog" on Dremio) instead of a hard-coded constant. - catalog/settings.py: EEA_CATALOG_BACKEND=polaris|dremio (unset: polaris when POLARIS_URI is set, else dremio), DremioSettings, and PolarisSettings reading the JupyterLab kernel's variable names with the local-stack/.env names as fallbacks. - %catalog builds its session from the settings; the Polaris backend itself comes in the next step and reports so for now. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/__init__.py | 7 + src/eea_datalakehouse/catalog/backend.py | 186 ++++++++ src/eea_datalakehouse/catalog/client.py | 97 +++- .../catalog/dremio_publish.py | 238 ++++++++++ src/eea_datalakehouse/catalog/layout.py | 26 ++ src/eea_datalakehouse/catalog/session.py | 442 ++++-------------- src/eea_datalakehouse/catalog/settings.py | 191 ++++++++ src/eea_datalakehouse/notebook/magics.py | 27 +- tests/catalog/test_settings.py | 145 ++++++ tests/notebook/conftest.py | 8 + tests/notebook/test_magics.py | 25 + 11 files changed, 1043 insertions(+), 349 deletions(-) create mode 100644 src/eea_datalakehouse/catalog/backend.py create mode 100644 src/eea_datalakehouse/catalog/dremio_publish.py create mode 100644 src/eea_datalakehouse/catalog/layout.py create mode 100644 src/eea_datalakehouse/catalog/settings.py create mode 100644 tests/catalog/test_settings.py diff --git a/src/eea_datalakehouse/catalog/__init__.py b/src/eea_datalakehouse/catalog/__init__.py index eb44604..52ef248 100644 --- a/src/eea_datalakehouse/catalog/__init__.py +++ b/src/eea_datalakehouse/catalog/__init__.py @@ -25,6 +25,7 @@ from __future__ import annotations +from .backend import CatalogBackend from .client import Catalog from .errors import CatalogAuthError, CatalogOperationError, EngineStartingError from .foldertree import ( @@ -78,6 +79,7 @@ CatalogSessionError, CommitReport, ) +from .settings import DremioSettings, PolarisSettings, SettingsError, backend_name from .sql import ( FLIGHT_LOCATION_ENV_VAR, TRANSPORT_ENV_VAR, @@ -89,6 +91,11 @@ ) __all__ = [ + "CatalogBackend", + "DremioSettings", + "PolarisSettings", + "SettingsError", + "backend_name", "FLIGHT_LOCATION_ENV_VAR", "TRANSPORT_ENV_VAR", "Catalog", diff --git a/src/eea_datalakehouse/catalog/backend.py b/src/eea_datalakehouse/catalog/backend.py new file mode 100644 index 0000000..b60cc5f --- /dev/null +++ b/src/eea_datalakehouse/catalog/backend.py @@ -0,0 +1,186 @@ +"""`CatalogBackend` — what `CatalogSession` needs from a catalog, whatever runs it. + +`CatalogSession` (and so `%catalog`) only ever calls the methods below. Two +implementations exist: + +* `Catalog` (``client.py``) — Dremio: REST catalog API, REST Jobs SQL and + Arrow Flight. +* `PolarisCatalog` (``polaris.py``) — Apache Polaris (Iceberg REST catalog) + with DuckDB for SQL. + +Which one a notebook gets is decided by ``EEA_CATALOG_BACKEND`` (see +`settings.backend_name`). + +Paths are always dotted and absolute, starting with `root` (``catalog`` on +Dremio, the Polaris catalog name — ``eea_lakehouse`` — on Polaris). The +methods with an ``idempotency_key`` keep the Dremio-era signature; a backend +that has no use for the key ignores it. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, Literal, Protocol + +from .operations import TableInfo, VersionResult + +# `publish(partition_by=...)` once checked: one field tuple for every view, or +# each view's own, keyed by its dotted path below the dataflow folder. +Partitions = tuple[str, ...] | dict[str, tuple[str, ...]] + +# What `publish_dataflow` hands back: how many published tables it replaced, +# and how to undo what it created (dropped tables only — a replaced one is gone). +PublishOutcome = tuple[int, Callable[[], None]] + + +class CatalogBackend(Protocol): + """The catalog operations `CatalogSession` is built on.""" + + # The first segment of every absolute path, e.g. "catalog" or "eea_lakehouse". + root: str + + def close(self) -> None: ... + + # -- what is where -------------------------------------------------------- + + def exists(self, path: str) -> bool: + """Whether a folder, table or view exists at `path`.""" + ... + + def is_folder(self, path: str) -> bool: + """Whether `path` exists and is a folder (not a table or view).""" + ... + + def list_datasets(self, path: str) -> list[str]: + """Full paths of every table and view under the folder `path`, at any depth.""" + ... + + def list_dataset_kinds(self, path: str) -> list[tuple[str, str]]: + """`list_datasets`, each paired with ``"TABLE"`` or ``"VIEW"``.""" + ... + + def entry_kind(self, path: str, *, idempotency_key: str) -> Literal["TABLE", "VIEW"]: + """Whether the table-or-view at `path` is a table or a view.""" + ... + + def entry_exists(self, path: str, *, idempotency_key: str) -> bool: + """Whether a table or view exists at `path`.""" + ... + + def require_table_or_view(self, path: str, verb: str) -> None: + """Raise `CatalogOperationError` unless `path` is a table or view — + `verb` names what was asked, for the message.""" + ... + + def gettableitemsfrom(self, table_path: str, *, idempotency_key: str) -> TableInfo: ... + + # -- folders -------------------------------------------------------------- + + def ensure_folder_path(self, folder: str) -> list[str]: + """Create every missing level of `folder`; the levels created, top first.""" + ... + + def createfolder( + self, path: str, *, create_parents: bool = False, idempotency_key: str + ) -> None: ... + + def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str) -> None: ... + + # -- data ----------------------------------------------------------------- + + def datacopy( + self, + source_path: str, + target_path: str, + *, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> Any: ... + + def datamove( + self, + source_path: str, + target_path: str, + *, + entry_type: Literal["TABLE", "VIEW"] | None = None, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> Any: ... + + def createversion( + self, + source_path: str, + version_name: str, + tables: list[str] | None = None, + *, + target_path: str, + overwrite: bool = False, + create_target_folder: bool = True, + include_views: bool = False, + idempotency_key: str, + ) -> VersionResult: ... + + def createview( + self, + source_path: str, + target_path: str, + *, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> Any: ... + + def deleteview(self, view_path: str, *, idempotency_key: str) -> Any: ... + + def deletetable(self, table_path: str, *, idempotency_key: str) -> Any: ... + + def drop_entry(self, path: str, *, idempotency_key: str) -> None: + """Drop whatever table or view is at `path` — the undo of a copy or a new view.""" + ... + + # -- wiki and tags -------------------------------------------------------- + + def getwikifrom(self, path: str, *, idempotency_key: str) -> str: ... + + def setwikito( + self, + path: str, + text: str, + *, + tags: list[dict[str, str]] | None = None, + idempotency_key: str, + ) -> None: ... + + def deletewiki(self, path: str, *, idempotency_key: str) -> None: ... + + def gettagsfrom(self, path: str, *, idempotency_key: str) -> list[str]: ... + + def settagsto(self, path: str, tags: list[str], *, idempotency_key: str) -> None: ... + + def deletetags(self, path: str, tags: list[str], *, idempotency_key: str) -> None: ... + + # -- publishing ----------------------------------------------------------- + + def publish_target(self, area: str) -> str: + """Where `publish_dataflow` puts the dataflow `area`'s public tables (for messages).""" + ... + + def check_publish(self, area: str, partitions: Partitions, *, idempotency_key: str) -> None: + """Raise `CatalogOperationError` if `publish_dataflow` would refuse + `partitions` for `area` — so a typo fails when `publish` is queued.""" + ... + + def publish_dataflow( + self, + area: str, + *, + overwrite: bool, + partitions: Partitions, + idempotency_key: str, + notes: list[str], + ) -> PublishOutcome: + """Copy every public view of the dataflow folder `area` to the public + store, all or nothing; `notes` gets one line per table.""" + ... diff --git a/src/eea_datalakehouse/catalog/client.py b/src/eea_datalakehouse/catalog/client.py index cc3caf5..095ae39 100644 --- a/src/eea_datalakehouse/catalog/client.py +++ b/src/eea_datalakehouse/catalog/client.py @@ -37,7 +37,8 @@ import pyarrow as pa -from . import foldertree, operations, retry_state +from . import dremio_publish, foldertree, operations, retry_state +from .backend import Partitions, PublishOutcome from .foldertree import FolderTransferReport, FolderTree, ProgressCallback from .operations import CatalogEntry, TableInfo, VersionResult, ViewDefinition from .rest import CatalogRestClient @@ -54,6 +55,10 @@ # in sync with which methods below pass self._flight_executor. _FLIGHT_OPERATIONS = frozenset({"datacopy", "datamove", "createversion"}) +# This deployment's one real top-level Dremio source/space (see e.g. the "catalog." +# prefix on every real path in debugger/test_catalog_magic.ipynb's TEST_ROOT). +DREMIO_ROOT = "catalog" + _open_catalogs: weakref.WeakSet[Catalog] = weakref.WeakSet() _signal_lock = threading.Lock() _signal_handlers_installed = False @@ -159,6 +164,96 @@ def __repr__(self) -> str: # No token here, same reasoning as IngestClient's own __repr__. return f"Catalog(executor={self._executor!r}, flight_executor={self._flight_executor!r})" + # --- the CatalogBackend surface `CatalogSession` uses (see backend.py) --- + # Thin, public names for what the session used to reach into + # `_catalog_rest`/`_executor`/`_flight_executor` for; the behaviour is + # exactly that of the call each one wraps. + + root = DREMIO_ROOT + + def exists(self, path: str) -> bool: + return self._catalog_rest.exists(path) + + def is_folder(self, path: str) -> bool: + return self._catalog_rest.is_folder(path) + + def list_datasets(self, path: str) -> list[str]: + return self._catalog_rest.list_datasets(path.split(".")) + + def list_dataset_kinds(self, path: str) -> list[tuple[str, str]]: + return self._catalog_rest.list_dataset_kinds(path.split(".")) + + def ensure_folder_path(self, folder: str) -> list[str]: + return self._catalog_rest.ensure_folder_path(folder) + + def entry_kind(self, path: str, *, idempotency_key: str) -> Literal["TABLE", "VIEW"]: + return operations._entry_kind( # noqa: SLF001 — same-package internal + self._executor, path, idempotency_key=idempotency_key + ) + + def entry_exists(self, path: str, *, idempotency_key: str) -> bool: + return operations._entry_exists( # noqa: SLF001 — same-package internal + self._executor, path, idempotency_key=idempotency_key + ) + + def require_table_or_view(self, path: str, verb: str) -> None: + operations._require_table_or_view(self._catalog_rest, path, verb) # noqa: SLF001 + + def drop_entry(self, path: str, *, idempotency_key: str) -> None: + """Drop whatever table or view is at `path` — over Flight, like the + `datacopy`/`datamove` it usually undoes (the public `deleteview`/ + `deletetable` go over REST instead).""" + executor = self._flight_executor + kind = operations._entry_kind(executor, path, idempotency_key=idempotency_key) # noqa: SLF001 + executor.execute( + f"DROP {kind} IF EXISTS {operations._quote_path(path)}", # noqa: SLF001 + idempotency_key=idempotency_key, + ) + + def publish_target(self, area: str) -> str: + return f"{dremio_publish.PUBLIC_ROOT}.{area}" + + def check_publish(self, area: str, partitions: Partitions, *, idempotency_key: str) -> None: + dremio_publish.plan_publish( + self._executor, + self._catalog_rest, + area, + self.publish_target(area), + True, + partitions, + idempotency_key, + [], + ) + + def publish_dataflow( + self, + area: str, + *, + overwrite: bool, + partitions: Partitions, + idempotency_key: str, + notes: list[str], + ) -> PublishOutcome: + """Copy the dataflow's ``#public`` views to ``PUBLIC_ROOT`` as Parquet + (see `CatalogSession.publish`) — planned over REST, copied over Flight.""" + target_root = self.publish_target(area) + plan = dremio_publish.plan_publish( + self._executor, + self._catalog_rest, + area, + target_root, + overwrite, + partitions, + idempotency_key, + notes, + ) + publication = dremio_publish.Publication( + self._flight_executor, f"{target_root}{dremio_publish.BACKUP_SUFFIX}", idempotency_key + ) + publication.run(plan, notes) + replaced = sum(existed for _, _, existed, _ in plan) + return replaced, publication.drop_published + def __enter__(self) -> Catalog: return self diff --git a/src/eea_datalakehouse/catalog/dremio_publish.py b/src/eea_datalakehouse/catalog/dremio_publish.py new file mode 100644 index 0000000..95de4ca --- /dev/null +++ b/src/eea_datalakehouse/catalog/dremio_publish.py @@ -0,0 +1,238 @@ +"""Dremio's `publish`: copy a dataflow's ``#public`` views to the public S3 source. + +Each view becomes a Parquet table at ``PUBLIC_ROOT.`` — see `CatalogSession.publish` for the behaviour, and `Catalog. +publish_dataflow` for the entry point. Moved out of ``session.py`` unchanged +when the session stopped talking to Dremio directly (see ``backend.py``). +""" + +from __future__ import annotations + +from . import operations +from .backend import Partitions +from .errors import CatalogAuthError, CatalogOperationError, EngineStartingError +from .layout import NOT_PUBLISHED, PUBLIC_TAG +from .rest import CatalogRestClient +from .sql import SqlExecutor + +# Where publish copies them: PUBLIC_ROOT., so +# catalog.a.b.c.v lands at "public_s3"."dh-prod-data-public"."catalog"."a"."b"."c"."v". +PUBLIC_ROOT = "public_s3.dh-prod-data-public" + +# Where publish keeps a copy of each table it replaces until the publish is done: +# a sibling of the Area's own folder in the bucket. +BACKUP_SUFFIX = "__publish_backup" + + +def _quote(path: str) -> str: + return operations._quote_path(path) # noqa: SLF001 — same-package internal + + +def _quote_name(column: str) -> str: + """A column name as a quoted SQL identifier.""" + return '"' + column.replace('"', '""') + '"' + + +def _published_rows(executor: SqlExecutor, table: str, *, idempotency_key: str) -> int: + """``COUNT(*)`` of a table `publish` just created — proof Dremio can read it.""" + try: + rows = executor.fetch_all( + f'SELECT COUNT(*) AS "row_count" FROM {_quote(table)}', + idempotency_key=idempotency_key, + ) + return int(rows[0]["row_count"]) + except (EngineStartingError, CatalogAuthError): + raise + except Exception as exc: + raise CatalogOperationError(f"{table!r} was not created successfully: {exc}") from exc + + +def _view_columns(executor: SqlExecutor, view: str, *, idempotency_key: str) -> list[str]: + """The column names of `view`, in order, from ``INFORMATION_SCHEMA."COLUMNS"``.""" + schema, _, leaf = view.rpartition(".") + quote = operations._quote_literal # noqa: SLF001 — same-package internal + rows = executor.fetch_all( + 'SELECT "COLUMN_NAME" FROM INFORMATION_SCHEMA."COLUMNS" ' + f'WHERE "TABLE_SCHEMA" = {quote(schema)} AND "TABLE_NAME" = {quote(leaf)} ' + 'ORDER BY "ORDINAL_POSITION"', + idempotency_key=idempotency_key, + ) + return [str(row["COLUMN_NAME"]) for row in rows] + + +def plan_publish( + executor: SqlExecutor, + rest: CatalogRestClient, + area: str, + target_root: str, + overwrite: bool, + partitions: Partitions, + key: str, + notes: list[str], +) -> list[tuple[str, str, bool, tuple[str, ...]]]: + """``(view, target, target_exists, partition columns)`` for every + `PUBLIC_TAG` view under `area` outside its draft, versions and reference + folders — see `CatalogSession.publish`. Checks every target and every + partition field first, so nothing is copied when one is refused.""" + internal = tuple(f"{area}.{folder}." for folder in NOT_PUBLISHED) + plan: list[tuple[str, str, bool, tuple[str, ...]]] = [] + problems: list[str] = [] + for number, (path, kind) in enumerate(rest.list_dataset_kinds(area.split(".")), start=1): + if kind != "VIEW" or path.startswith(internal): + continue + if PUBLIC_TAG not in rest.get_tags(path): + notes.append(f"skipped {path!r}: no {PUBLIC_TAG} tag") + continue + relative = path[len(area) + 1 :] + target = f"{target_root}.{relative}" + existed = operations._entry_exists( # noqa: SLF001 + executor, target, idempotency_key=f"{key}-check-{number}" + ) + if existed and not overwrite: + problems.append(f"{target!r} already exists — pass overwrite=True") + fields = partitions.get(relative, ()) if isinstance(partitions, dict) else partitions + columns: tuple[str, ...] = () + if fields: + # Dremio matches column names ignoring case; use the view's own spelling. + known = { + name.lower(): name + for name in _view_columns(executor, path, idempotency_key=f"{key}-columns-{number}") + } + missing = [field for field in fields if field.lower() not in known] + if missing: + problems.append( + f"{path!r} has no field(s) {', '.join(missing)} to partition by " + f"(its fields: {', '.join(known.values()) or 'none'})" + ) + columns = tuple(known.get(field.lower(), field) for field in fields) + plan.append((path, target, existed, columns)) + if isinstance(partitions, dict): + published = {view[len(area) + 1 :] for view, *_ in plan} + unknown = sorted(set(partitions) - published) + if unknown: + problems.append( + "partition_by names view(s) that are not published: " + + ", ".join(repr(view) for view in unknown) + ) + if problems: + raise CatalogOperationError("nothing published: " + "; ".join(problems)) + if not plan: + raise CatalogOperationError( + f"{area!r} has no views tagged {PUBLIC_TAG!r} — run update_latest_release first" + ) + return plan + + +class Publication: + """One `CatalogSession.publish` run: back up, copy, verify — or roll back. + + `run` first backs up every target that already exists, then publishes each + view. Any failure drops every table it touched, restores the replaced ones + from their backups and raises `CatalogOperationError`; the backups are + dropped at the end either way, unless one could not be restored.""" + + def __init__(self, executor: SqlExecutor, backup_root: str, key: str) -> None: + self._executor = executor + self._target_root, _, _ = backup_root.partition(BACKUP_SUFFIX) + self._backup_root = backup_root + self._key = key + self._statement = 0 + self.touched: list[str] = [] # targets dropped or created, in order + self.backups: list[tuple[str, str]] = [] # (target, its backup) + self.created: list[str] = [] # targets that did not exist before + + def run(self, plan: list[tuple[str, str, bool, tuple[str, ...]]], notes: list[str]) -> None: + current = "the backups" + try: + for _, target, existed, _ in plan: + if existed: + current = f"the backup of {target!r}" + backup = self._backup_of(target) + self.backups.append((target, backup)) + self._copy(target, backup, ()) + for view, target, existed, columns in plan: + current = f"{view!r} to {target!r}" + self.touched.append(target) + rows = self._copy(view, target, columns) + if not existed: + self.created.append(target) + action = "replaced" if existed else "copied" + by = f", partitioned by {', '.join(columns)}" if columns else "" + notes.append(f"{action} {target!r} from {view!r} ({rows} rows{by})") + except Exception as exc: + kept = self._roll_back() + restored = len(self.backups) - len(kept) + outcome = ( + f"rolled back: every table it touched was dropped and {restored} replaced " + "table(s) restored" + if not kept + else "rollback incomplete — restore these by hand from their backups: " + + "; ".join(f"{target!r} from {backup!r}" for target, backup in kept) + ) + raise CatalogOperationError(f"publishing {current} failed: {exc}; {outcome}") from exc + problems = self._drop_backups([backup for _, backup in self.backups]) + notes.extend(f"could not drop backup {problem}" for problem in problems) + + def drop_published(self) -> None: + """Undo: drop the tables this publish created (only reversible ones).""" + for table in reversed(self.created): + self._sql(f"DROP TABLE IF EXISTS {_quote(table)}") + + # -- internals ---------------------------------------------------------- + + def _backup_of(self, target: str) -> str: + return f"{self._backup_root}{target[len(self._target_root) :]}" + + def _sql(self, statement: str) -> None: + self._statement += 1 + self._executor.execute(statement, idempotency_key=f"{self._key}-{self._statement}") + + def _copy(self, source: str, target: str, columns: tuple[str, ...]) -> int: + """Drop `target`, create it from `source` as Parquet, refresh it and + return its row count — raising if any of that fails.""" + self._sql(f"DROP TABLE IF EXISTS {_quote(target)}") + partition = ( + f"PARTITION BY ({', '.join(_quote_name(c) for c in columns)}) " if columns else "" + ) + self._sql( + f"CREATE TABLE {_quote(target)} {partition}" + f"STORE AS (type => 'parquet') AS SELECT * FROM {_quote(source)}" + ) + self._sql(f"ALTER TABLE {_quote(target)} REFRESH METADATA AUTO PROMOTION") + self._statement += 1 + return _published_rows( + self._executor, target, idempotency_key=f"{self._key}-{self._statement}" + ) + + def _roll_back(self) -> list[tuple[str, str]]: + """Drop what was touched, restore what was replaced; the + ``(target, backup)`` pairs that could not be restored (kept).""" + for table in reversed(self.touched): + try: + self._sql(f"DROP TABLE IF EXISTS {_quote(table)}") + except Exception: # noqa: BLE001, S112 — restoring below matters more + continue + replaced = set(self.touched) + kept: list[tuple[str, str]] = [] + restored: list[str] = [] + for target, backup in self.backups: + if target not in replaced: + restored.append(backup) # never dropped: only its backup needs removing + continue + try: + self._copy(backup, target, ()) + restored.append(backup) + except Exception: # noqa: BLE001 — reported by the caller, backup kept + kept.append((target, backup)) + self._drop_backups(restored) + return kept + + def _drop_backups(self, backups: list[str]) -> list[str]: + """Drop `backups`; a ``'path': error`` for each that failed.""" + problems: list[str] = [] + for backup in backups: + try: + self._sql(f"DROP TABLE IF EXISTS {_quote(backup)}") + except Exception as exc: # noqa: BLE001 — a leftover backup is reported, not fatal + problems.append(f"{backup!r}: {exc}") + return problems diff --git a/src/eea_datalakehouse/catalog/layout.py b/src/eea_datalakehouse/catalog/layout.py new file mode 100644 index 0000000..9e43f1b --- /dev/null +++ b/src/eea_datalakehouse/catalog/layout.py @@ -0,0 +1,26 @@ +"""The dataflow folder layout every catalog backend shares. + +An Area (dataflow) folder holds ``draft`` (work in progress), ``versions`` +(frozen copies, one folder per version) and ``reference``/``references`` +(shared reference data); `update_latest_release` puts views over the latest +version at the Area's root and tags them `PUBLIC_TAG`, and `publish` copies +the tagged views out. +""" + +from __future__ import annotations + +DRAFT_FOLDER = "draft" +# Where draft_to_version puts versions: a sibling of the draft folder, as in +# debugger/bathing_water/README.md's layout (…bwd.draft / …bwd.versions). +VERSIONS_FOLDER = "versions" + +# The tag update_latest_release puts on the views it creates (and removes from +# everything under the Area's versions folder); publish copies the views that carry it. +PUBLIC_TAG = "#public" + +# The Area's own folders publish never copies from: work in progress, the +# frozen versions, and the shared reference data. +REFERENCE_FOLDER = "reference" +# Either spelling is a dataflow's reference folder. +REFERENCE_FOLDERS = (REFERENCE_FOLDER, "references") +NOT_PUBLISHED = (DRAFT_FOLDER, VERSIONS_FOLDER, *REFERENCE_FOLDERS) diff --git a/src/eea_datalakehouse/catalog/session.py b/src/eea_datalakehouse/catalog/session.py index 0941153..8071b85 100644 --- a/src/eea_datalakehouse/catalog/session.py +++ b/src/eea_datalakehouse/catalog/session.py @@ -38,10 +38,31 @@ from typing import Any from . import operations -from .client import Catalog +from .backend import CatalogBackend +from .dremio_publish import PUBLIC_ROOT from .errors import CatalogAuthError, CatalogOperationError, EngineStartingError +from .layout import ( + DRAFT_FOLDER, + PUBLIC_TAG, + REFERENCE_FOLDER, + REFERENCE_FOLDERS, + VERSIONS_FOLDER, +) from .operations import TableInfo -from .sql import SqlExecutor + +# Re-exported: these used to live here, and callers import them from here. +__all__ = [ + "DRAFT_FOLDER", + "PUBLIC_ROOT", + "PUBLIC_TAG", + "REFERENCE_FOLDER", + "VERSIONS_FOLDER", + "CatalogCommitError", + "CatalogListing", + "CatalogSession", + "CatalogSessionError", + "CommitReport", +] _Undo = Callable[[], None] @@ -126,12 +147,12 @@ class _Irreversible(Exception): # noqa: N818 — internal control-flow signal, @dataclass class _Step: description: str - run: Callable[[Catalog, str], _Undo | None] + run: Callable[[CatalogBackend, str], _Undo | None] # Filled in by `run`, reported in `CommitReport.notes` once the commit succeeds. notes: list[str] = field(default_factory=list) -def _read_wiki_or_none(catalog: Catalog, path: str, *, idempotency_key: str) -> str | None: +def _read_wiki_or_none(catalog: CatalogBackend, path: str, *, idempotency_key: str) -> str | None: """The wiki text at `path`, or `None` if it doesn't have one (or doesn't exist) — `getwikifrom` can't tell those two apart, and neither needs to here: either way there's nothing to restore on rollback.""" @@ -141,29 +162,12 @@ def _read_wiki_or_none(catalog: Catalog, path: str, *, idempotency_key: str) -> return None -DRAFT_FOLDER = "draft" -# Where draft_to_version puts versions: a sibling of the draft folder, as in -# debugger/bathing_water/README.md's layout (…bwd.draft / …bwd.versions). -VERSIONS_FOLDER = "versions" - -# The tag update_latest_release puts on the views it creates (and removes from -# everything under the Area's versions folder); publish copies the views that carry it. -PUBLIC_TAG = "#public" -# Where publish copies them: PUBLIC_ROOT., so -# catalog.a.b.c.v lands at "public_s3"."dh-prod-data-public"."catalog"."a"."b"."c"."v". -PUBLIC_ROOT = "public_s3.dh-prod-data-public" - -# The Area's own folders publish never copies from: work in progress, the -# frozen versions, and the shared reference data. -REFERENCE_FOLDER = "reference" -# Either spelling is a dataflow's reference folder. -_REFERENCE_FOLDERS = (REFERENCE_FOLDER, "references") -_NOT_PUBLISHED = (DRAFT_FOLDER, VERSIONS_FOLDER, *_REFERENCE_FOLDERS) +_REFERENCE_FOLDERS = REFERENCE_FOLDERS _ROOT_SOURCE = "catalog" -# This deployment's one real top-level source/space (see e.g. the "catalog." prefix -# on every real path in debugger/test_catalog_magic.ipynb's TEST_ROOT) — a bare path -# starting with it is therefore unambiguously absolute, context or not; see +# The Dremio deployment's one real top-level source/space — the root a session +# uses when its catalog doesn't name one (`CatalogBackend.root`). A bare path +# starting with the root is unambiguously absolute, context or not; see # `_resolve_path`. @@ -176,62 +180,21 @@ def _dotted(path: str) -> str: return ".".join(segment for segment in path.split("/") if segment) -def _drop_entry(catalog: Catalog, path: str, *, idempotency_key: str) -> None: - """Drop whatever entity (table or view) now sits at `path`. - - Used to undo a fresh `data_copy`. Reaches into `operations`' own private - helpers (`_entry_kind`, `_quote_path`) rather than a public op, because - the public `deleteview`/`deletetable` (via `Catalog`) run over REST, not - Flight — this needs to stay on `catalog._flight_executor` like the - `data_copy`/`data_move` it's undoing. Acceptable here since this module - lives in the same package as `operations.py`. - """ - executor = catalog._flight_executor # noqa: SLF001 — same-package internal, see docstring - kind = operations._entry_kind(executor, path, idempotency_key=idempotency_key) # noqa: SLF001 - executor.execute( - f"DROP {kind} IF EXISTS {operations._quote_path(path)}", # noqa: SLF001 - idempotency_key=idempotency_key, - ) - - -def _quote(path: str) -> str: - return operations._quote_path(path) # noqa: SLF001 — same-package internal, as in _drop_entry - - -def _quote_name(column: str) -> str: - """A column name as a quoted SQL identifier.""" - return '"' + column.replace('"', '""') + '"' - - -def _published_rows(executor: SqlExecutor, table: str, *, idempotency_key: str) -> int: - """``COUNT(*)`` of a table `publish` just created — proof Dremio can read it.""" - try: - rows = executor.fetch_all( - f'SELECT COUNT(*) AS "row_count" FROM {_quote(table)}', - idempotency_key=idempotency_key, - ) - return int(rows[0]["row_count"]) - except (EngineStartingError, CatalogAuthError): - raise - except Exception as exc: - raise CatalogOperationError(f"{table!r} was not created successfully: {exc}") from exc - - -def _create_folders(catalog: Catalog, folder: str | None) -> list[str]: +def _create_folders(catalog: CatalogBackend, folder: str | None) -> list[str]: """Create every missing level of `folder` (if any); the levels created, top first.""" if folder is None: return [] - return catalog._catalog_rest.ensure_folder_path(folder) # noqa: SLF001 — as in _drop_entry + return catalog.ensure_folder_path(folder) -def _delete_folders(catalog: Catalog, folders: list[str], *, idempotency_key: str) -> None: +def _delete_folders(catalog: CatalogBackend, folders: list[str], *, idempotency_key: str) -> None: """Undo `_create_folders`: delete the levels it created, deepest first.""" for folder in reversed(folders): catalog.deletefolder(folder, idempotency_key=idempotency_key) def _plan_version_views( - catalog: Catalog, + catalog: CatalogBackend, dataflow: str, version: str, overwrite: bool, @@ -241,14 +204,11 @@ def _plan_version_views( """``(table, view, view_exists)`` for every table in `version` — see `CatalogSession.update_latest_release`. Checks every target first, so nothing is created when one of them is refused; skipped views go into `notes`.""" - executor = catalog._executor # noqa: SLF001 — same-package internal, as in _drop_entry plan: list[tuple[str, str, bool]] = [] problems: list[str] = [] - for number, source in enumerate( - catalog._catalog_rest.list_datasets(version.split(".")), start=1 # noqa: SLF001 - ): + for number, source in enumerate(catalog.list_datasets(version), start=1): check_key = f"{key}-check-{number}" - if operations._entry_kind(executor, source, idempotency_key=check_key) == "VIEW": # noqa: SLF001 + if catalog.entry_kind(source, idempotency_key=check_key) == "VIEW": notes.append(f"skipped {source!r}: view — only tables get a view") continue relative = source[len(version) + 1 :] @@ -256,9 +216,9 @@ def _plan_version_views( problems.append(f"{source!r} would put its view inside {dataflow}.{relative}") continue target = f"{dataflow}.{relative}" - existed = operations._entry_exists(executor, target, idempotency_key=check_key) # noqa: SLF001 + existed = catalog.entry_exists(target, idempotency_key=check_key) if existed: - kind = operations._entry_kind(executor, target, idempotency_key=check_key) # noqa: SLF001 + kind = catalog.entry_kind(target, idempotency_key=check_key) if kind == "TABLE": problems.append(f"{target!r} is a table — a view never replaces one") elif not overwrite: @@ -271,7 +231,7 @@ def _plan_version_views( return plan -def _add_tag(catalog: Catalog, path: str, tag: str, *, idempotency_key: str) -> None: +def _add_tag(catalog: CatalogBackend, path: str, tag: str, *, idempotency_key: str) -> None: """Add `tag` to `path`'s tags, keeping the others.""" tags = catalog.gettagsfrom(path, idempotency_key=f"{idempotency_key}-read") if tag not in tags: @@ -279,12 +239,16 @@ def _add_tag(catalog: Catalog, path: str, tag: str, *, idempotency_key: str) -> def _remove_tag_under( - catalog: Catalog, folder: str, tag: str, removed: list[tuple[str, list[str]]], *, key: str + catalog: CatalogBackend, + folder: str, + tag: str, + removed: list[tuple[str, list[str]]], + *, + key: str, ) -> None: """Remove `tag` from every table and view under `folder`, appending ``(path, tags before)`` to `removed` as it goes, so an undo can restore them.""" - rest = catalog._catalog_rest # noqa: SLF001 — same-package internal, as in _drop_entry - for number, path in enumerate(rest.list_datasets(folder.split(".")), start=1): + for number, path in enumerate(catalog.list_datasets(folder), start=1): tags = catalog.gettagsfrom(path, idempotency_key=f"{key}-{number}-read") if tag in tags: catalog.settagsto( @@ -335,207 +299,6 @@ def _partition_plan( return plan -def _view_columns(executor: SqlExecutor, view: str, *, idempotency_key: str) -> list[str]: - """The column names of `view`, in order, from ``INFORMATION_SCHEMA."COLUMNS"``.""" - schema, _, leaf = view.rpartition(".") - quote = operations._quote_literal # noqa: SLF001 — same-package internal - rows = executor.fetch_all( - 'SELECT "COLUMN_NAME" FROM INFORMATION_SCHEMA."COLUMNS" ' - f'WHERE "TABLE_SCHEMA" = {quote(schema)} AND "TABLE_NAME" = {quote(leaf)} ' - 'ORDER BY "ORDINAL_POSITION"', - idempotency_key=idempotency_key, - ) - return [str(row["COLUMN_NAME"]) for row in rows] - - -def _plan_publish( - catalog: Catalog, - area: str, - target_root: str, - overwrite: bool, - partitions: tuple[str, ...] | dict[str, tuple[str, ...]], - key: str, - notes: list[str], -) -> list[tuple[str, str, bool, tuple[str, ...]]]: - """``(view, target, target_exists, partition columns)`` for every - `PUBLIC_TAG` view under `area` outside its draft, versions and reference - folders — see `CatalogSession.publish`. Checks every target and every - partition field first, so nothing is copied when one is refused.""" - executor = catalog._executor # noqa: SLF001 — same-package internal, as in _drop_entry - rest = catalog._catalog_rest # noqa: SLF001 - internal = tuple(f"{area}.{folder}." for folder in _NOT_PUBLISHED) - plan: list[tuple[str, str, bool, tuple[str, ...]]] = [] - problems: list[str] = [] - for number, (path, kind) in enumerate(rest.list_dataset_kinds(area.split(".")), start=1): - if kind != "VIEW" or path.startswith(internal): - continue - if PUBLIC_TAG not in rest.get_tags(path): - notes.append(f"skipped {path!r}: no {PUBLIC_TAG} tag") - continue - relative = path[len(area) + 1 :] - target = f"{target_root}.{relative}" - existed = operations._entry_exists( # noqa: SLF001 - executor, target, idempotency_key=f"{key}-check-{number}" - ) - if existed and not overwrite: - problems.append(f"{target!r} already exists — pass overwrite=True") - fields = partitions.get(relative, ()) if isinstance(partitions, dict) else partitions - columns: tuple[str, ...] = () - if fields: - # Dremio matches column names ignoring case; use the view's own spelling. - known = { - name.lower(): name - for name in _view_columns( - executor, path, idempotency_key=f"{key}-columns-{number}" - ) - } - missing = [field for field in fields if field.lower() not in known] - if missing: - problems.append( - f"{path!r} has no field(s) {', '.join(missing)} to partition by " - f"(its fields: {', '.join(known.values()) or 'none'})" - ) - columns = tuple(known.get(field.lower(), field) for field in fields) - plan.append((path, target, existed, columns)) - if isinstance(partitions, dict): - published = {view[len(area) + 1 :] for view, *_ in plan} - unknown = sorted(set(partitions) - published) - if unknown: - problems.append( - "partition_by names view(s) that are not published: " - + ", ".join(repr(view) for view in unknown) - ) - if problems: - raise CatalogOperationError("nothing published: " + "; ".join(problems)) - if not plan: - raise CatalogOperationError( - f"{area!r} has no views tagged {PUBLIC_TAG!r} — run update_latest_release first" - ) - return plan - - -# Where publish keeps a copy of each table it replaces until the publish is done: -# a sibling of the Area's own folder in the bucket. -_BACKUP_SUFFIX = "__publish_backup" - - -class _Publication: - """One `CatalogSession.publish` run: back up, copy, verify — or roll back. - - `run` first backs up every target that already exists, then publishes each - view. Any failure drops every table it touched, restores the replaced ones - from their backups and raises `CatalogOperationError`; the backups are - dropped at the end either way, unless one could not be restored.""" - - def __init__(self, executor: SqlExecutor, backup_root: str, key: str) -> None: - self._executor = executor - self._target_root, _, _ = backup_root.partition(_BACKUP_SUFFIX) - self._backup_root = backup_root - self._key = key - self._statement = 0 - self.touched: list[str] = [] # targets dropped or created, in order - self.backups: list[tuple[str, str]] = [] # (target, its backup) - self.created: list[str] = [] # targets that did not exist before - - def run( - self, plan: list[tuple[str, str, bool, tuple[str, ...]]], notes: list[str] - ) -> None: - current = "the backups" - try: - for _, target, existed, _ in plan: - if existed: - current = f"the backup of {target!r}" - backup = self._backup_of(target) - self.backups.append((target, backup)) - self._copy(target, backup, ()) - for view, target, existed, columns in plan: - current = f"{view!r} to {target!r}" - self.touched.append(target) - rows = self._copy(view, target, columns) - if not existed: - self.created.append(target) - action = "replaced" if existed else "copied" - by = f", partitioned by {', '.join(columns)}" if columns else "" - notes.append(f"{action} {target!r} from {view!r} ({rows} rows{by})") - except Exception as exc: - kept = self._roll_back() - restored = len(self.backups) - len(kept) - outcome = ( - f"rolled back: every table it touched was dropped and {restored} replaced " - "table(s) restored" - if not kept - else "rollback incomplete — restore these by hand from their backups: " - + "; ".join(f"{target!r} from {backup!r}" for target, backup in kept) - ) - raise CatalogOperationError(f"publishing {current} failed: {exc}; {outcome}") from exc - problems = self._drop_backups([backup for _, backup in self.backups]) - notes.extend(f"could not drop backup {problem}" for problem in problems) - - def drop_published(self) -> None: - """Undo: drop the tables this publish created (only reversible ones).""" - for table in reversed(self.created): - self._sql(f"DROP TABLE IF EXISTS {_quote(table)}") - - # -- internals ---------------------------------------------------------- - - def _backup_of(self, target: str) -> str: - return f"{self._backup_root}{target[len(self._target_root) :]}" - - def _sql(self, statement: str) -> None: - self._statement += 1 - self._executor.execute(statement, idempotency_key=f"{self._key}-{self._statement}") - - def _copy(self, source: str, target: str, columns: tuple[str, ...]) -> int: - """Drop `target`, create it from `source` as Parquet, refresh it and - return its row count — raising if any of that fails.""" - self._sql(f"DROP TABLE IF EXISTS {_quote(target)}") - partition = ( - f"PARTITION BY ({', '.join(_quote_name(c) for c in columns)}) " if columns else "" - ) - self._sql( - f"CREATE TABLE {_quote(target)} {partition}" - f"STORE AS (type => 'parquet') AS SELECT * FROM {_quote(source)}" - ) - self._sql(f"ALTER TABLE {_quote(target)} REFRESH METADATA AUTO PROMOTION") - self._statement += 1 - return _published_rows( - self._executor, target, idempotency_key=f"{self._key}-{self._statement}" - ) - - def _roll_back(self) -> list[tuple[str, str]]: - """Drop what was touched, restore what was replaced; the - ``(target, backup)`` pairs that could not be restored (kept).""" - for table in reversed(self.touched): - try: - self._sql(f"DROP TABLE IF EXISTS {_quote(table)}") - except Exception: # noqa: BLE001, S112 — restoring below matters more - continue - replaced = set(self.touched) - kept: list[tuple[str, str]] = [] - restored: list[str] = [] - for target, backup in self.backups: - if target not in replaced: - restored.append(backup) # never dropped: only its backup needs removing - continue - try: - self._copy(backup, target, ()) - restored.append(backup) - except Exception: # noqa: BLE001 — reported by the caller, backup kept - kept.append((target, backup)) - self._drop_backups(restored) - return kept - - def _drop_backups(self, backups: list[str]) -> list[str]: - """Drop `backups`; a ``'path': error`` for each that failed.""" - problems: list[str] = [] - for backup in backups: - try: - self._sql(f"DROP TABLE IF EXISTS {_quote(backup)}") - except Exception as exc: # noqa: BLE001 — a leftover backup is reported, not fatal - problems.append(f"{backup!r}: {exc}") - return problems - - class CatalogSession: """Queue catalog verbs against `catalog`, then `commit()` them as one batch. @@ -553,8 +316,14 @@ class CatalogSession: class exists to hide (see the design doc's "must be fully encapsulated"). """ - def __init__(self, catalog: Catalog) -> None: + # Class-level default, so a session built without __init__ (tests do) still resolves. + _root: str = _ROOT_SOURCE + + def __init__(self, catalog: CatalogBackend) -> None: self._catalog = catalog + # The first segment of every absolute path: "catalog" on Dremio, the + # catalog's own name ("eea_lakehouse") on Polaris. + self._root = getattr(catalog, "root", None) or _ROOT_SOURCE self._id = uuid.uuid4().hex[:8] self._steps: list[_Step] = [] self._next_step = 1 @@ -564,7 +333,7 @@ def __init__(self, catalog: Catalog) -> None: # they've ever had a chance to set one deliberately. use(None)/ # use("") reset back here explicitly; only set_context(None) can # still clear it to no context at all. - self._context: str | None = _ROOT_SOURCE + self._context: str | None = self._root def __repr__(self) -> str: return f"CatalogSession(pending={len(self._steps)})" @@ -577,7 +346,8 @@ def set_context(self, path: str | None) -> CatalogSession: """Set the "current" catalog path — a later relative path (a leading `.`, e.g. `.water_temperature`) resolves against this. `None` clears it to no context at all (unlike `use(None)`/`use("")`, which reset to - `_ROOT_SOURCE` instead — see `use`'s own docstring for why). `path` + the catalog root (`CatalogBackend.root`) instead — see `use`'s own docstring + for why). `path` here is always taken literally, even if it itself starts with `.` — same as `use`, which differs only in that `None`/`""` handling, plus also making a live existence check (see `use`'s own docstring). @@ -602,7 +372,7 @@ def set_context(self, path: str | None) -> CatalogSession: def use(self, path: str | None) -> CatalogSession: """Set the current path for every call after this one — same as `set_context`, plus a live existence check (below) and different - `None`/`""` handling: either one resets context to `_ROOT_SOURCE` + `None`/`""` handling: either one resets context to the catalog root (`CatalogBackend.root`) (the catalog root — the same starting point a freshly built session already has), rather than clearing it to no context at all the way `set_context(None)` still does (see that method's own docstring for @@ -627,11 +397,11 @@ def use(self, path: str | None) -> CatalogSession: root always exists. """ if path is None or path == "": - self._context = _ROOT_SOURCE + self._context = self._root return self path = _dotted(path) try: - found = self._catalog._catalog_rest.exists(path) # noqa: SLF001 — see module docstring + found = self._catalog.exists(path) except (EngineStartingError, CatalogAuthError) as exc: raise CatalogSessionError(f"could not check whether {path!r} exists: {exc}") from exc if not found: @@ -641,10 +411,10 @@ def use(self, path: str | None) -> CatalogSession: def get_context(self) -> str | None: """The current path — see `use`/`set_context`, the only two ways - it changes after construction. Starts at `_ROOT_SOURCE` (the + it changes after construction. Starts at the catalog root (`CatalogBackend.root`) (the catalog root) for a freshly built session, never `None` — `None` only after an explicit `set_context(None)`. `use(None)`/`use("")` - reset it back to `_ROOT_SOURCE` instead, rather than to `None`.""" + reset it back to the catalog root (`CatalogBackend.root`) instead, rather than to `None`.""" return self._context def _resolve_path(self, path: str) -> str: @@ -658,7 +428,8 @@ def _resolve_path(self, path: str) -> str: same way too (`"water_temperature"` -> `f"{context}.water_temperature"`, same as `".water_temperature"`) — the dot is optional sugar there, not a marker that distinguishes relative from absolute. A bare path - starting with `_ROOT_SOURCE` (e.g. `"catalog.other_root.table"`) is + starting with the catalog root (`CatalogBackend.root`, e.g. + `"catalog.other_root.table"`) is the one unambiguous exception: real absolute paths in this deployment always start there, so it's taken literally as absolute even with a context already set, rather than getting appended to @@ -666,7 +437,7 @@ def _resolve_path(self, path: str) -> str: relative path. Every verb resolves this way, including `data_copy`/ `data_move`/`create_view`'s two paths (each resolved independently against the *same* current context) — since a genuinely absolute - path in this deployment always starts with `_ROOT_SOURCE`, pairing + path in this deployment always starts with the catalog root (`CatalogBackend.root`), pairing a relative one with an unrelated absolute one in the same call is already unambiguous without needing a dot on the absolute side too. Otherwise, a bare path is only ever taken literally as absolute @@ -692,7 +463,7 @@ def _resolve_path(self, path: str) -> str: if path.startswith("./"): path = f".{path[2:]}" # "./name" means the same thing as ".name" if not path.startswith("."): - is_root_absolute = path == _ROOT_SOURCE or path.startswith(f"{_ROOT_SOURCE}.") + is_root_absolute = path == self._root or path.startswith(f"{self._root}.") if self._context is None or is_root_absolute: return path path = f".{path}" @@ -775,7 +546,7 @@ def data_copy( source_path = self._resolve_path(source_path) target_path, folder = self._resolve_target(source_path, target_path) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: created = _create_folders(catalog, folder) try: catalog.datacopy( @@ -792,7 +563,7 @@ def run(catalog: Catalog, key: str) -> _Undo | None: raise _Irreversible("overwrote an existing target; its previous content is gone") def undo() -> None: - _drop_entry(catalog, target_path, idempotency_key=f"{key}-undo") + catalog.drop_entry(target_path, idempotency_key=f"{key}-undo") _delete_folders(catalog, created, idempotency_key=f"{key}-undo-folder") return undo @@ -821,7 +592,7 @@ def data_move( source_path = self._resolve_path(source_path) target_path, folder = self._resolve_target(source_path, target_path) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: created = _create_folders(catalog, folder) try: catalog.datamove( @@ -933,7 +704,7 @@ def _queue_version( lambda catalog, key: None, # replaced below, once `step` exists to report into ) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: result = catalog.createversion( source_path, version_name, @@ -968,7 +739,7 @@ def undo() -> None: catalog.deletefolder(created_top, cascade=True, idempotency_key=f"{key}-undo") return for number, table in enumerate(new_tables, start=1): - _drop_entry(catalog, table, idempotency_key=f"{key}-undo-{number}") + catalog.drop_entry(table, idempotency_key=f"{key}-undo-{number}") return undo @@ -1032,7 +803,7 @@ def _find_draft(self) -> str: return ".".join(segments[: nearest + 1]) candidate = f"{self._context}.{DRAFT_FOLDER}" try: - found = self._catalog._catalog_rest.exists(candidate) # noqa: SLF001 + found = self._catalog.exists(candidate) except (EngineStartingError, CatalogAuthError) as exc: raise CatalogSessionError( f"could not check whether {candidate!r} exists: {exc}" @@ -1098,7 +869,7 @@ def update_latest_release( lambda catalog, key: None, # replaced below, once `step` exists to report into ) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: plan = _plan_version_views(catalog, dataflow, version, overwrite, key, step.notes) new_views: list[str] = [] new_folders: list[str] = [] @@ -1108,7 +879,7 @@ def undo() -> None: for number, (path, tags) in enumerate(untagged, start=1): catalog.settagsto(path, tags, idempotency_key=f"{key}-undo-tag-{number}") for number, view in enumerate(new_views, start=1): - _drop_entry(catalog, view, idempotency_key=f"{key}-undo-{number}") + catalog.drop_entry(view, idempotency_key=f"{key}-undo-{number}") for folder in reversed(new_folders): catalog.deletefolder(folder, idempotency_key=f"{key}-undo-folder") @@ -1116,7 +887,7 @@ def undo() -> None: for number, (source, target, existed) in enumerate(plan, start=1): parent = operations._parent_path(target) # noqa: SLF001 if parent is not None and parent != dataflow: - new_folders.extend(catalog._catalog_rest.ensure_folder_path(parent)) # noqa: SLF001 + new_folders.extend(catalog.ensure_folder_path(parent)) catalog.createview( source, target, overwrite=existed, idempotency_key=f"{key}-{number}" ) @@ -1211,12 +982,12 @@ def publish( any table is irreversible (see `CatalogCommitError`).""" partitions = _partition_plan(partition_by) area = self._require_publish_dataflow(path) - target_root = f"{PUBLIC_ROOT}.{area}" + target_root = self._catalog.publish_target(area) if partitions: # Fields are checked now, so a typo fails here rather than at commit. try: - _plan_publish( - self._catalog, area, target_root, True, partitions, self._key("-fields"), [] + self._catalog.check_publish( + area, partitions, idempotency_key=self._key("-fields") ) except (CatalogOperationError, EngineStartingError, CatalogAuthError) as exc: raise CatalogSessionError(str(exc)) from exc @@ -1225,20 +996,17 @@ def publish( lambda catalog, key: None, # replaced below, once `step` exists to report into ) - def run(catalog: Catalog, key: str) -> _Undo | None: - plan = _plan_publish( - catalog, area, target_root, overwrite, partitions, key, step.notes - ) - publication = _Publication( - catalog._flight_executor, # noqa: SLF001 — Flight, as Catalog.datacopy - f"{target_root}{_BACKUP_SUFFIX}", - key, + def run(catalog: CatalogBackend, key: str) -> _Undo | None: + replaced, drop_published = catalog.publish_dataflow( + area, + overwrite=overwrite, + partitions=partitions, + idempotency_key=key, + notes=step.notes, ) - publication.run(plan, step.notes) - replaced = sum(existed for _, _, existed, _ in plan) if replaced: raise _Irreversible(f"replaced {replaced} published table(s)") - return publication.drop_published + return drop_published step.run = run self._steps.append(step) @@ -1252,11 +1020,11 @@ def _require_publish_dataflow(self, path: str | None) -> str: if not isinstance(path, str) or not path.strip(" ./"): raise CatalogSessionError(f"path must be a catalog folder path, not {path!r}") dataflow = self._resolve_path(path.strip()) - elif self._context is None or self._context == _ROOT_SOURCE: + elif self._context is None or self._context == self._root: raise CatalogSessionError( "no dataflow folder: run %catalog use(...) on the dataflow folder (the one with " "draft, versions and reference folders) first, or pass path=, e.g. " - 'publish(path="catalog...")' + f'publish(path="{self._root}...")' ) else: dataflow = self._context @@ -1295,7 +1063,7 @@ def _require_area(self) -> str: def _is_folder(self, path: str) -> bool: """Whether `path` is a folder, checked against Dremio now.""" try: - return self._catalog._catalog_rest.is_folder(path) # noqa: SLF001 + return self._catalog.is_folder(path) except (EngineStartingError, CatalogAuthError) as exc: raise CatalogSessionError(f"could not check whether {path!r} exists: {exc}") from exc @@ -1304,7 +1072,7 @@ def _require_dataflow_context(self) -> str: if self._context is None: raise CatalogSessionError( "no context is set — use() the Area folder " - f"({_ROOT_SOURCE}...) first" + f"({self._root}...) first" ) return self._context @@ -1330,7 +1098,7 @@ def create_view( source_path = self._resolve_path(source_path) target_path = self._resolve_path(target_path) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: catalog.createview( source_path, target_path, @@ -1342,7 +1110,7 @@ def run(catalog: Catalog, key: str) -> _Undo | None: raise _Irreversible("overwrote an existing target; its previous content is gone") def undo() -> None: - _drop_entry(catalog, target_path, idempotency_key=f"{key}-undo") + catalog.drop_entry(target_path, idempotency_key=f"{key}-undo") return undo @@ -1357,7 +1125,7 @@ def set_tags(self, path: str, tags: list[str]) -> CatalogSession: context — see `set_context`. Does not change the context itself — only `use` does that.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo: + def run(catalog: CatalogBackend, key: str) -> _Undo: existing = catalog.gettagsfrom(path, idempotency_key=f"{key}-read") catalog.settagsto(path, tags, idempotency_key=key) @@ -1377,7 +1145,7 @@ def delete_tags(self, path: str, tags: list[str]) -> CatalogSession: context — see `set_context`. Does not change the context itself — only `use` does that.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo: + def run(catalog: CatalogBackend, key: str) -> _Undo: existing = catalog.gettagsfrom(path, idempotency_key=f"{key}-read") catalog.deletetags(path, tags, idempotency_key=key) @@ -1404,7 +1172,7 @@ def set_wiki( context — see `set_context`. Does not change the context itself — only `use` does that.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo: + def run(catalog: CatalogBackend, key: str) -> _Undo: existing = _read_wiki_or_none(catalog, path, idempotency_key=f"{key}-read") catalog.setwikito(path, text, tags=tags, idempotency_key=key) @@ -1428,7 +1196,7 @@ def delete_wiki(self, path: str) -> CatalogSession: context — see `set_context`. Does not change the context itself — only `use` does that.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: existing = _read_wiki_or_none(catalog, path, idempotency_key=f"{key}-read") catalog.deletewiki(path, idempotency_key=key) if existing is None: @@ -1452,8 +1220,8 @@ def create_folder(self, path: str, *, create_parents: bool = False) -> CatalogSe `use` does that.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo | None: - already_there = catalog._catalog_rest.exists(path) # noqa: SLF001 — see module docstring + def run(catalog: CatalogBackend, key: str) -> _Undo | None: + already_there = catalog.exists(path) catalog.createfolder(path, create_parents=create_parents, idempotency_key=key) if already_there: return None @@ -1476,7 +1244,7 @@ def delete_folder(self, path: str, *, cascade: bool = False) -> CatalogSession: there's nothing meaningful to navigate into once it's deleted.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo | None: + def run(catalog: CatalogBackend, key: str) -> _Undo | None: catalog.deletefolder(path, cascade=cascade, idempotency_key=key) raise _Irreversible("deleted folder contents cannot be recreated") @@ -1496,8 +1264,8 @@ def delete_view(self, path: str) -> CatalogSession: there's nothing meaningful to navigate into once it's deleted.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo | None: - if not catalog._catalog_rest.exists(path): # noqa: SLF001 — see module docstring + def run(catalog: CatalogBackend, key: str) -> _Undo | None: + if not catalog.exists(path): raise CatalogOperationError(f"{path!r} does not exist") catalog.deleteview(path, idempotency_key=key) raise _Irreversible("dropped view's definition cannot be recreated") @@ -1518,8 +1286,8 @@ def delete_table(self, path: str) -> CatalogSession: there's nothing meaningful to navigate into once it's deleted.""" path = self._resolve_path(path) - def run(catalog: Catalog, key: str) -> _Undo | None: - if not catalog._catalog_rest.exists(path): # noqa: SLF001 — see module docstring + def run(catalog: CatalogBackend, key: str) -> _Undo | None: + if not catalog.exists(path): raise CatalogOperationError(f"{path!r} does not exist") catalog.deletetable(path, idempotency_key=key) raise _Irreversible("dropped table's data cannot be recreated") @@ -1577,7 +1345,7 @@ def list(self, path: str = "") -> CatalogListing: else: path = self._resolve_path(path) return CatalogListing( - self._catalog._catalog_rest.list_dataset_kinds(path.split(".")) # noqa: SLF001 + self._catalog.list_dataset_kinds(path) ) def schema(self, path: str) -> TableInfo: @@ -1591,11 +1359,7 @@ def schema(self, path: str) -> TableInfo: `path` may be relative — with or without a leading `.` — to the session's current context — see `set_context`.""" path = self._resolve_path(path) - operations._require_table_or_view( # noqa: SLF001 — see module docstring - self._catalog._catalog_rest, # noqa: SLF001 - path, - "schema", - ) + self._catalog.require_table_or_view(path, "schema") return self._catalog.gettableitemsfrom(path, idempotency_key=self._key()) # -- commit ------------------------------------------------------------- diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py new file mode 100644 index 0000000..8365481 --- /dev/null +++ b/src/eea_datalakehouse/catalog/settings.py @@ -0,0 +1,191 @@ +"""Which catalog backend a notebook uses, and its connection settings. + +``EEA_CATALOG_BACKEND`` picks the backend: ``polaris`` or ``dremio``. Unset, +it is ``polaris`` when ``POLARIS_URI`` is set and ``dremio`` otherwise, so a +kernel that only has the Dremio variables keeps working unchanged. + +Polaris settings use the names the JupyterLab kernel receives in the EEA +Lakehouse stack (``POLARIS_URI``, ``POLARIS_CATALOG``, ``KEYCLOAK_ACCESS_TOKEN``, +``S3_ENDPOINT``, …). Where the stack's ``local-stack/.env`` spells a setting +differently, that name is read as a fallback (``POLARIS_CATALOG_NAME``, +``POLARIS_ROOT_CLIENT_ID``, ``POLARIS_CATALOG_S3_*``, …), so a debugger run +can load that file as it is. See `PolarisSettings` for the full list. +""" + +from __future__ import annotations + +import os +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Literal + +from .client import DREMIO_ROOT + +Backend = Literal["polaris", "dremio"] +BACKENDS: tuple[Backend, ...] = ("polaris", "dremio") + +DEFAULT_POLARIS_CATALOG = "eea_lakehouse" +DEFAULT_INGEST_PREFIX = "_ingestion" +DEFAULT_ROLE_ARN = "arn:aws:iam:::role/eea-datalakehouse" +DEFAULT_FLIGHT_PORT = 8815 +_TRUE = ("1", "true", "yes", "on") + + +class SettingsError(RuntimeError): + """A backend setting is missing or invalid; the message names the variable.""" + + +def _get(environ: Mapping[str, str], *names: str) -> str: + """The first of `names` set to a non-blank value in `environ`, stripped; ``""`` if none.""" + for name in names: + value = (environ.get(name) or "").strip() + if value: + return value + return "" + + +def backend_name(environ: Mapping[str, str] | None = None) -> Backend: + """``EEA_CATALOG_BACKEND``, or the backend the environment implies (module docstring).""" + env = os.environ if environ is None else environ + chosen = _get(env, "EEA_CATALOG_BACKEND").lower() + if not chosen: + return "polaris" if _get(env, "POLARIS_URI") else "dremio" + if chosen not in BACKENDS: + raise SettingsError( + f"EEA_CATALOG_BACKEND={chosen!r} is not a catalog backend — use one of: " + + ", ".join(BACKENDS) + ) + return chosen + + +def user_token(environ: Mapping[str, str] | None = None) -> str | None: + """The signed-in user's Keycloak access token (``KEYCLOAK_ACCESS_TOKEN``), or None. + + Read on every call, not once: the Kubernetes deployment refreshes it in the + server's environment, and a kernel started later sees the new one.""" + env = os.environ if environ is None else environ + return _get(env, "KEYCLOAK_ACCESS_TOKEN") or None + + +@dataclass(frozen=True) +class DremioSettings: + """``DREMIO_BASE_URL``, ``DREMIO_TOKEN`` (a PAT) and ``DREMIO_USERNAME`` (for Flight).""" + + base_url: str + token: str + username: str | None + root: str = DREMIO_ROOT + + @classmethod + def from_env(cls, environ: Mapping[str, str] | None = None) -> DremioSettings: + env = os.environ if environ is None else environ + base_url = _get(env, "DREMIO_BASE_URL") + token = _get(env, "DREMIO_TOKEN") + if not base_url or not token: + raise SettingsError( + "%catalog needs DREMIO_BASE_URL and DREMIO_TOKEN set in the kernel environment" + ) + return cls(base_url=base_url, token=token, username=_get(env, "DREMIO_USERNAME") or None) + + +def _with_scheme(endpoint: str) -> str: + """``host:port`` (the stack's ``S3_ENDPOINT`` shape) as ``http://host:port``.""" + return endpoint if "://" in endpoint else f"http://{endpoint}" + + +@dataclass(frozen=True) +class PolarisSettings: + """Everything the Polaris backend reads from the environment. + + Each setting, its variable (the ``local-stack/.env`` fallback in brackets) + and its default: + + - ``uri``: ``POLARIS_URI``; without it, ``http://localhost: + /api/catalog`` when ``POLARIS_HOST_PORT`` is set — otherwise an error. + - ``catalog``: ``POLARIS_CATALOG`` (``POLARIS_CATALOG_NAME``); ``eea_lakehouse``. + Also the root of every `%catalog` path. + - ``client_id``/``client_secret``: ``POLARIS_CLIENT_ID``/``POLARIS_CLIENT_SECRET`` + (``POLARIS_ROOT_CLIENT_ID``/``POLARIS_ROOT_CLIENT_SECRET``) — only used when + there is no user token. + - ``vended_credentials``: ``POLARIS_VENDED_CREDENTIALS``; off. + - ``s3_endpoint``: ``S3_ENDPOINT`` (``POLARIS_CATALOG_S3_ENDPOINT_URL`` plus + ``POLARIS_CATALOG_S3_ENDPOINT_PORT``); ``http://localhost:``. + - ``s3_region``: ``AWS_REGION`` (``POLARIS_CATALOG_S3_REGION``); ``us-east-1``. + - ``s3_access_key``/``s3_secret_key``: ``RUSTFS_ACCESS_KEY``/``RUSTFS_SECRET_KEY`` + (``POLARIS_CATALOG_S3_ACCESS_KEY_ID``/``POLARIS_CATALOG_S3_SECRET_ACCESS_KEY``) — + the static key, used when vended credentials are off or STS fails. + - ``ingest_bucket``: ``POLARIS_CATALOG_S3_BUCKET``; the target namespace's bucket. + - ``ingest_prefix``: ``POLARIS_INGEST_S3_PREFIX``; ``_ingestion``. + - ``role_arn``: ``RUSTFS_ROLE_ARN``; ``arn:aws:iam:::role/eea-datalakehouse``. + - ``flight_host``/``flight_port``: ``FLIGHT_HOST``/``FLIGHT_HOST_PORT``; + ``localhost``/``8815``. + + The user's own identity, ``KEYCLOAK_ACCESS_TOKEN``, is not stored here — + see `user_token`, read on every request. + """ + + uri: str + catalog: str = DEFAULT_POLARIS_CATALOG + client_id: str = "" + client_secret: str = "" + vended_credentials: bool = False + s3_endpoint: str = "http://localhost:9100" + s3_region: str = "us-east-1" + s3_access_key: str = "" + s3_secret_key: str = "" + ingest_bucket: str = "" + ingest_prefix: str = DEFAULT_INGEST_PREFIX + role_arn: str = DEFAULT_ROLE_ARN + flight_host: str = "localhost" + flight_port: int = DEFAULT_FLIGHT_PORT + + @property + def root(self) -> str: + """The first segment of every absolute `%catalog` path: the catalog's name.""" + return self.catalog + + @property + def flight_location(self) -> str: + return f"grpc://{self.flight_host}:{self.flight_port}" + + @classmethod + def from_env(cls, environ: Mapping[str, str] | None = None) -> PolarisSettings: + env = os.environ if environ is None else environ + uri = _get(env, "POLARIS_URI") + if not uri and _get(env, "POLARIS_HOST_PORT"): + uri = f"http://localhost:{_get(env, 'POLARIS_HOST_PORT')}/api/catalog" + if not uri: + raise SettingsError( + "%catalog on Polaris needs POLARIS_URI (e.g. http://localhost:8181/api/catalog) " + "set in the kernel environment" + ) + s3_endpoint = _get(env, "S3_ENDPOINT") + if not s3_endpoint and _get(env, "POLARIS_CATALOG_S3_ENDPOINT_URL"): + # local-stack/.env splits it: a URL, and optionally its port on its own. + s3_endpoint = _get(env, "POLARIS_CATALOG_S3_ENDPOINT_URL").rstrip("/") + port_only = _get(env, "POLARIS_CATALOG_S3_ENDPOINT_PORT") + if port_only and ":" not in s3_endpoint.split("://", 1)[-1]: + s3_endpoint = f"{s3_endpoint}:{port_only}" + if not s3_endpoint: + s3_endpoint = f"localhost:{_get(env, 'RUSTFS_API_PORT') or '9100'}" + flight_port = _get(env, "FLIGHT_HOST_PORT") + try: + port = int(flight_port) if flight_port else DEFAULT_FLIGHT_PORT + except ValueError: + raise SettingsError(f"FLIGHT_HOST_PORT={flight_port!r} is not a port number") from None + return cls( + uri=uri.rstrip("/"), + catalog=_get(env, "POLARIS_CATALOG", "POLARIS_CATALOG_NAME") or DEFAULT_POLARIS_CATALOG, + client_id=_get(env, "POLARIS_CLIENT_ID", "POLARIS_ROOT_CLIENT_ID"), + client_secret=_get(env, "POLARIS_CLIENT_SECRET", "POLARIS_ROOT_CLIENT_SECRET"), + vended_credentials=_get(env, "POLARIS_VENDED_CREDENTIALS").lower() in _TRUE, + s3_endpoint=_with_scheme(s3_endpoint).rstrip("/"), + s3_region=_get(env, "AWS_REGION", "POLARIS_CATALOG_S3_REGION") or "us-east-1", + s3_access_key=_get(env, "RUSTFS_ACCESS_KEY", "POLARIS_CATALOG_S3_ACCESS_KEY_ID"), + s3_secret_key=_get(env, "RUSTFS_SECRET_KEY", "POLARIS_CATALOG_S3_SECRET_ACCESS_KEY"), + ingest_bucket=_get(env, "POLARIS_CATALOG_S3_BUCKET"), + ingest_prefix=_get(env, "POLARIS_INGEST_S3_PREFIX").strip("/") or DEFAULT_INGEST_PREFIX, + role_arn=_get(env, "RUSTFS_ROLE_ARN") or DEFAULT_ROLE_ARN, + flight_host=_get(env, "FLIGHT_HOST") or "localhost", + flight_port=port, + ) diff --git a/src/eea_datalakehouse/notebook/magics.py b/src/eea_datalakehouse/notebook/magics.py index d4fd0e5..2337a64 100644 --- a/src/eea_datalakehouse/notebook/magics.py +++ b/src/eea_datalakehouse/notebook/magics.py @@ -93,7 +93,6 @@ import ast import inspect -import os import re from html import escape as _escape from typing import Any @@ -102,7 +101,14 @@ from IPython.display import HTML, display from ..catalog import Catalog +from ..catalog.backend import CatalogBackend from ..catalog.session import CatalogSession, CatalogSessionError +from ..catalog.settings import ( + DremioSettings, + PolarisSettings, + SettingsError, + backend_name, +) from ..dds_documents.controller import DdsFolder, PushReport, closest_folder, valid_folders_hint from ..dds_documents.session import DdsSession, DdsSessionError from ..dds_ingestion.session import IngestSession, IngestSessionError @@ -594,14 +600,17 @@ def _dds_unknown_folder(line: str, exc: NameError | AttributeError) -> str | Non def _build_catalog_session() -> CatalogSession: - base_url = os.environ.get("DREMIO_BASE_URL") - token = os.environ.get("DREMIO_TOKEN") - username = os.environ.get("DREMIO_USERNAME") - if not base_url or not token: - raise RuntimeError( - "%catalog needs DREMIO_BASE_URL and DREMIO_TOKEN set in the kernel environment" + """A `CatalogSession` on the backend `EEA_CATALOG_BACKEND` names (see + `catalog.settings`) — a `SettingsError` (a `RuntimeError`) names whatever + variable is missing.""" + if backend_name() == "polaris": + PolarisSettings.from_env() # a missing variable is reported first + raise SettingsError( + "%catalog: the Polaris backend is not implemented yet on this branch — " + "set EEA_CATALOG_BACKEND=dremio to use Dremio" ) - return CatalogSession(Catalog(base_url, token, username=username)) + dremio = DremioSettings.from_env() + return CatalogSession(Catalog(dremio.base_url, dremio.token, username=dremio.username)) def _build_sdi_session() -> SdiSession: @@ -1146,7 +1155,7 @@ def dds(self, line: str) -> Any: _notify_dds_pushed(self.shell, dds_path) return None if result is _DISPATCH_FAILED else result - def _catalog_for_gpkg(self) -> Catalog: + def _catalog_for_gpkg(self) -> CatalogBackend: """`%catalog`'s own Catalog, building its session if need be.""" if self._catalog_session is None: self._catalog_session = _build_catalog_session() # raises without credentials diff --git a/tests/catalog/test_settings.py b/tests/catalog/test_settings.py new file mode 100644 index 0000000..6663b60 --- /dev/null +++ b/tests/catalog/test_settings.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import pytest + +from eea_datalakehouse.catalog.settings import ( + DremioSettings, + PolarisSettings, + SettingsError, + backend_name, + user_token, +) + + +@pytest.mark.parametrize( + ("env", "expected"), + [ + ({}, "dremio"), + ({"DREMIO_BASE_URL": "https://dremio"}, "dremio"), + ({"POLARIS_URI": "http://polaris:8181/api/catalog"}, "polaris"), + ({"POLARIS_URI": "http://p/api/catalog", "EEA_CATALOG_BACKEND": "dremio"}, "dremio"), + ({"EEA_CATALOG_BACKEND": " Polaris "}, "polaris"), + ({"POLARIS_URI": " "}, "dremio"), + ], +) +def test_backend_name(env: dict[str, str], expected: str) -> None: + assert backend_name(env) == expected + + +def test_backend_name_rejects_an_unknown_backend() -> None: + with pytest.raises(SettingsError, match="EEA_CATALOG_BACKEND='trino'"): + backend_name({"EEA_CATALOG_BACKEND": "trino"}) + + +def test_dremio_settings_need_url_and_token() -> None: + with pytest.raises(SettingsError, match="DREMIO_BASE_URL and DREMIO_TOKEN"): + DremioSettings.from_env({"DREMIO_BASE_URL": "https://dremio"}) + settings = DremioSettings.from_env( + {"DREMIO_BASE_URL": "https://dremio", "DREMIO_TOKEN": "pat", "DREMIO_USERNAME": "ana"} + ) + assert (settings.base_url, settings.token, settings.username, settings.root) == ( + "https://dremio", + "pat", + "ana", + "catalog", + ) + + +def test_polaris_settings_need_a_uri() -> None: + with pytest.raises(SettingsError, match="POLARIS_URI"): + PolarisSettings.from_env({}) + + +def test_polaris_settings_kernel_names() -> None: + settings = PolarisSettings.from_env( + { + "POLARIS_URI": "http://polaris:8181/api/catalog/", + "POLARIS_CATALOG": "lake", + "POLARIS_CLIENT_ID": "root", + "POLARIS_CLIENT_SECRET": "s3cr3t", + "POLARIS_VENDED_CREDENTIALS": "true", + "S3_ENDPOINT": "rustfs:9000", + "AWS_REGION": "eu-west-1", + "RUSTFS_ACCESS_KEY": "ak", + "RUSTFS_SECRET_KEY": "sk", + "POLARIS_CATALOG_S3_BUCKET": "dh-test-catalog", + "POLARIS_INGEST_S3_PREFIX": "/_staging/", + "RUSTFS_ROLE_ARN": "arn:aws:iam:::role/x", + "FLIGHT_HOST": "flight", + "FLIGHT_HOST_PORT": "9815", + } + ) + assert settings == PolarisSettings( + uri="http://polaris:8181/api/catalog", + catalog="lake", + client_id="root", + client_secret="s3cr3t", + vended_credentials=True, + s3_endpoint="http://rustfs:9000", + s3_region="eu-west-1", + s3_access_key="ak", + s3_secret_key="sk", + ingest_bucket="dh-test-catalog", + ingest_prefix="_staging", + role_arn="arn:aws:iam:::role/x", + flight_host="flight", + flight_port=9815, + ) + assert settings.root == "lake" + assert settings.flight_location == "grpc://flight:9815" + + +def test_polaris_settings_fall_back_to_local_stack_env_names() -> None: + """local-stack/.env, loaded as it is (no POLARIS_URI there).""" + settings = PolarisSettings.from_env( + { + "POLARIS_HOST_PORT": "8181", + "POLARIS_CATALOG_NAME": "eea_lakehouse", + "POLARIS_ROOT_CLIENT_ID": "root", + "POLARIS_ROOT_CLIENT_SECRET": "secret", + "POLARIS_CATALOG_S3_ENDPOINT_URL": "http://rustfs.local", + "POLARIS_CATALOG_S3_ENDPOINT_PORT": "9100", + "POLARIS_CATALOG_S3_REGION": "us-east-1", + "POLARIS_CATALOG_S3_ACCESS_KEY_ID": "ak", + "POLARIS_CATALOG_S3_SECRET_ACCESS_KEY": "sk", + } + ) + assert settings.uri == "http://localhost:8181/api/catalog" + assert settings.catalog == "eea_lakehouse" + assert (settings.client_id, settings.client_secret) == ("root", "secret") + assert settings.s3_endpoint == "http://rustfs.local:9100" + assert (settings.s3_access_key, settings.s3_secret_key) == ("ak", "sk") + + +def test_polaris_settings_defaults() -> None: + settings = PolarisSettings.from_env( + {"POLARIS_URI": "http://p/api/catalog", "RUSTFS_API_PORT": "9200"} + ) + assert settings.catalog == "eea_lakehouse" + assert settings.s3_endpoint == "http://localhost:9200" + assert settings.vended_credentials is False + assert settings.ingest_prefix == "_ingestion" + assert settings.flight_location == "grpc://localhost:8815" + + +def test_kernel_name_wins_over_local_stack_name() -> None: + settings = PolarisSettings.from_env( + { + "POLARIS_URI": "http://p/api/catalog", + "POLARIS_CATALOG": "kernel", + "POLARIS_CATALOG_NAME": "dotenv", + "S3_ENDPOINT": "kernel:9000", + "POLARIS_CATALOG_S3_ENDPOINT_URL": "http://dotenv:9100", + } + ) + assert (settings.catalog, settings.s3_endpoint) == ("kernel", "http://kernel:9000") + + +def test_bad_flight_port() -> None: + with pytest.raises(SettingsError, match="FLIGHT_HOST_PORT"): + PolarisSettings.from_env({"POLARIS_URI": "http://p", "FLIGHT_HOST_PORT": "x"}) + + +def test_user_token() -> None: + assert user_token({}) is None + assert user_token({"KEYCLOAK_ACCESS_TOKEN": " jwt "}) == "jwt" diff --git a/tests/notebook/conftest.py b/tests/notebook/conftest.py index c814d9d..9d8041f 100644 --- a/tests/notebook/conftest.py +++ b/tests/notebook/conftest.py @@ -17,3 +17,11 @@ def shell() -> Any: their own and getting `None`. """ return globalipapp.start_ipython() + + +@pytest.fixture(autouse=True) +def _dremio_backend(monkeypatch: pytest.MonkeyPatch) -> None: + """These tests exercise the Dremio-backed `%catalog`: keep a developer's own + Polaris variables (which would switch the backend) out of them.""" + monkeypatch.delenv("EEA_CATALOG_BACKEND", raising=False) + monkeypatch.delenv("POLARIS_URI", raising=False) diff --git a/tests/notebook/test_magics.py b/tests/notebook/test_magics.py index 48e3014..54216de 100644 --- a/tests/notebook/test_magics.py +++ b/tests/notebook/test_magics.py @@ -200,6 +200,31 @@ def test_missing_credentials_prints_a_friendly_message( assert "DREMIO_BASE_URL" in out +def test_polaris_backend_without_its_uri_names_the_variable( + ip: Any, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("EEA_CATALOG_BACKEND", "polaris") + monkeypatch.delenv("POLARIS_HOST_PORT", raising=False) + + ip.run_line_magic("catalog", 'data_copy("a.b", "c.d")') + + out = capsys.readouterr().out + assert "catalog error:" in out + assert "POLARIS_URI" in out + + +def test_unknown_backend_names_the_choices( + ip: Any, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("EEA_CATALOG_BACKEND", "trino") + + ip.run_line_magic("catalog", 'data_copy("a.b", "c.d")') + + out = capsys.readouterr().out + assert "catalog error:" in out + assert "polaris, dremio" in out + + def test_catalog_cell_magic_runs_the_magic_line_then_each_cell_line_in_order( ip: Any, monkeypatch: pytest.MonkeyPatch ) -> None: From 9df0cb89190f18426686c14df1aada618defe979 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:24:17 +0100 Subject: [PATCH 04/25] Add the Polaris REST client, the DuckDB engine and the PolarisCatalog backend Second step of the Polaris migration. - catalog/polaris_rest.py: PolarisRestClient over the Iceberg REST catalog (/v1/{prefix}, prefix from /v1/config) and Polaris generic tables (/polaris/v1): namespaces (list with paging, HEAD exists, properties, create - 409 is "already there" -, drop), tables and views (list, exists, load, drop with purge, view registration with SQL and schema, property commits) and read-only Parquet tables. Authenticates as the signed-in user (KEYCLOAK_ACCESS_TOKEN, read per request) or with Polaris client credentials (scope PRINCIPAL_ROLE:ALL, minted once, re-minted on 401). 401/403 -> CatalogAuthError, 404 -> PolarisNotFoundError, other failures -> PolarisHttpError with the status and Polaris' message. - catalog/duckdb_engine.py: DuckDbEngine, one lazy DuckDB connection with iceberg + httpfs (spatial when available), the S3 and Polaris secrets and the catalog ATTACHed under its own name, as datalakehouse.duckdb() does; vended credentials when POLARIS_VENDED_CREDENTIALS is on. table_ref() writes catalog."ns.parts"."name". Works with DuckDB 1 and 2. - catalog/polaris.py: PolarisCatalog, the CatalogBackend for Polaris. Root = the catalog name (eea_lakehouse); folders are namespaces, tables Iceberg tables or read-only Parquet tables, views Iceberg views. exists/is_folder/entry_kind/entry_exists/require_table_or_view and the recursive listing work; the other verbs say they are not on Polaris yet. - %catalog builds a PolarisCatalog session when the backend is polaris, so use(), list() and relative paths work against Polaris. - CatalogBackend.root is a read-only property. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/backend.py | 6 +- .../catalog/duckdb_engine.py | 246 +++++++++ src/eea_datalakehouse/catalog/polaris.py | 286 ++++++++++ src/eea_datalakehouse/catalog/polaris_rest.py | 493 ++++++++++++++++++ src/eea_datalakehouse/notebook/magics.py | 8 +- tests/catalog/polaris_fakes.py | 242 +++++++++ tests/catalog/test_duckdb_engine.py | 186 +++++++ tests/catalog/test_polaris_catalog.py | 174 +++++++ tests/catalog/test_polaris_rest.py | 467 +++++++++++++++++ 9 files changed, 2100 insertions(+), 8 deletions(-) create mode 100644 src/eea_datalakehouse/catalog/duckdb_engine.py create mode 100644 src/eea_datalakehouse/catalog/polaris.py create mode 100644 src/eea_datalakehouse/catalog/polaris_rest.py create mode 100644 tests/catalog/polaris_fakes.py create mode 100644 tests/catalog/test_duckdb_engine.py create mode 100644 tests/catalog/test_polaris_catalog.py create mode 100644 tests/catalog/test_polaris_rest.py diff --git a/src/eea_datalakehouse/catalog/backend.py b/src/eea_datalakehouse/catalog/backend.py index b60cc5f..1c48054 100644 --- a/src/eea_datalakehouse/catalog/backend.py +++ b/src/eea_datalakehouse/catalog/backend.py @@ -36,8 +36,10 @@ class CatalogBackend(Protocol): """The catalog operations `CatalogSession` is built on.""" - # The first segment of every absolute path, e.g. "catalog" or "eea_lakehouse". - root: str + @property + def root(self) -> str: + """The first segment of every absolute path: "catalog" or "eea_lakehouse".""" + ... def close(self) -> None: ... diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py new file mode 100644 index 0000000..7e858e9 --- /dev/null +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -0,0 +1,246 @@ +"""`DuckDbEngine` — SQL over the Polaris catalog, in this kernel. + +One DuckDB connection, opened on first use, with the ``iceberg`` and ``httpfs`` +extensions loaded and the catalog ATTACHed under its own name — the same setup +as the EEA Lakehouse's ``datalakehouse.duckdb()``:: + + CREATE SECRET … (TYPE s3, …) -- unless Polaris vends credentials + CREATE SECRET … (TYPE iceberg, TOKEN '', ENDPOINT …) + ATTACH 'eea_lakehouse' AS eea_lakehouse (TYPE iceberg, ENDPOINT …, SECRET …, + ACCESS_DELEGATION_MODE 'none' | 'vended_credentials') + +**Names.** DuckDB takes a two-part name inside an Iceberg catalog, so a nested +namespace is ONE quoted identifier with its parts joined by dots: +``eea_lakehouse."water.bwd.draft"."stations"`` (see `table_ref`). Chaining the +parts as separate identifiers fails. + +**Identity.** Your own Keycloak token when ``KEYCLOAK_ACCESS_TOKEN`` is set, so +Polaris applies your grants; otherwise Polaris client credentials. The token is +fixed when the connection opens: `reset` drops the connection, and the next +query opens a new one with whatever token is current then. + +**Storage.** By default a static S3 key (``RUSTFS_ACCESS_KEY``/``_SECRET_KEY``) +and ``ACCESS_DELEGATION_MODE 'none'`` — the local stack's catalog advertises a +storage endpoint a container can't reach. With ``POLARIS_VENDED_CREDENTIALS`` +Polaris hands out per-table credentials instead and the static key is unused. +""" + +from __future__ import annotations + +import threading +from collections.abc import Callable, Sequence +from typing import Any + +import pyarrow as pa + +from .errors import CatalogAuthError, CatalogOperationError +from .settings import PolarisSettings, user_token + +_EXTENSIONS = ("iceberg", "httpfs") +# Loaded when available: Iceberg tables with geometry columns need it to be read. +_OPTIONAL_EXTENSIONS = ("spatial",) +_S3_SECRET = "eea_catalog_s3" +_POLARIS_SECRET = "eea_catalog_polaris" + + +def quote_identifier(name: str) -> str: + """`name` as a double-quoted SQL identifier.""" + return '"' + name.replace('"', '""') + '"' + + +def quote_literal(value: str) -> str: + """`value` as a single-quoted SQL string literal.""" + return "'" + value.replace("'", "''") + "'" + + +def _connect() -> Any: + import duckdb + + return duckdb.connect() + + +class DuckDbEngine: + """SQL against the Polaris catalog — see the module docstring. + + `connect` builds the raw DuckDB connection (a test passes a fake); + `token_provider` returns the user's token or None (default: + ``KEYCLOAK_ACCESS_TOKEN``).""" + + def __init__( + self, + settings: PolarisSettings, + *, + connect: Callable[[], Any] = _connect, + token_provider: Callable[[], str | None] = user_token, + ) -> None: + self._settings = settings + self._connect = connect + self._token_provider = token_provider + self._connection: Any = None + self._lock = threading.Lock() + + def __repr__(self) -> str: + return f"DuckDbEngine(catalog={self._settings.catalog!r})" + + @property + def catalog(self) -> str: + return self._settings.catalog + + def table_ref(self, namespace: Sequence[str], name: str) -> str: + """The SQL name of table or view `name` in `namespace`: + ``eea_lakehouse."a.b.c"."name"``.""" + if not namespace: + raise CatalogOperationError( + f"{name!r} is not inside a namespace — tables live in a namespace below " + f"{self.catalog!r}" + ) + return ( + f"{quote_identifier(self.catalog)}." + f"{quote_identifier('.'.join(namespace))}.{quote_identifier(name)}" + ) + + # -- connection --------------------------------------------------------- + + @property + def connection(self) -> Any: + """The DuckDB connection, opened (and the catalog attached) on first use.""" + with self._lock: + if self._connection is None: + self._connection = self._open() + return self._connection + + def reset(self) -> None: + """Close the connection; the next query opens a new one (with a fresh token).""" + with self._lock: + connection, self._connection = self._connection, None + if connection is not None: + connection.close() + + close = reset + + def _open(self) -> Any: + settings = self._settings + connection = self._connect() + try: + for extension in _EXTENSIONS: + connection.execute(f"INSTALL {extension}") + connection.execute(f"LOAD {extension}") + for extension in _OPTIONAL_EXTENSIONS: + try: + connection.execute(f"INSTALL {extension}") + connection.execute(f"LOAD {extension}") + except Exception: # noqa: BLE001, S112 — optional: only geometry columns need it + continue + for statement in self.setup_statements(): + connection.execute(statement) + except CatalogOperationError: + connection.close() + raise + except Exception as exc: + connection.close() + message = str(exc) + if any(word in message for word in ("401", "403", "Unauthorized", "Forbidden")): + raise CatalogAuthError( + f"Polaris refused DuckDB's connection to {settings.catalog!r}: {message}" + ) from exc + raise CatalogOperationError( + f"DuckDB could not attach the Polaris catalog {settings.catalog!r} " + f"({settings.uri}): {message}" + ) from exc + return connection + + def setup_statements(self) -> list[str]: + """The secrets and the ATTACH that `connection` runs, in order.""" + settings = self._settings + statements: list[str] = [] + if not settings.vended_credentials: + scheme, _, host = settings.s3_endpoint.partition("://") + key = ( + f"KEY_ID {quote_literal(settings.s3_access_key)}, " + f"SECRET {quote_literal(settings.s3_secret_key)}, " + if settings.s3_access_key + else "" + ) + statements.append( + f"CREATE OR REPLACE SECRET {_S3_SECRET} (TYPE s3, {key}" + f"ENDPOINT {quote_literal(host or scheme)}, URL_STYLE 'path', " + f"USE_SSL {'true' if scheme == 'https' else 'false'}, " + f"REGION {quote_literal(settings.s3_region)})" + ) + token = self._token_provider() + if token: + identity = f"TOKEN {quote_literal(token)}" + elif settings.client_id and settings.client_secret: + identity = ( + f"CLIENT_ID {quote_literal(settings.client_id)}, " + f"CLIENT_SECRET {quote_literal(settings.client_secret)}" + ) + else: + raise CatalogAuthError( + "no Polaris identity: KEYCLOAK_ACCESS_TOKEN (your own sign-in) is not set, and " + "neither are POLARIS_CLIENT_ID/POLARIS_CLIENT_SECRET" + ) + statements.append( + f"CREATE OR REPLACE SECRET {_POLARIS_SECRET} (TYPE iceberg, {identity}, " + f"ENDPOINT {quote_literal(settings.uri)})" + ) + delegation = "vended_credentials" if settings.vended_credentials else "none" + statements.append( + f"ATTACH {quote_literal(settings.catalog)} AS {quote_identifier(settings.catalog)} " + f"(TYPE iceberg, ENDPOINT {quote_literal(settings.uri)}, SECRET {_POLARIS_SECRET}, " + f"ACCESS_DELEGATION_MODE '{delegation}')" + ) + return statements + + # -- queries -------------------------------------------------------------- + + def _run(self, sql: str, query: Callable[[Any], Any] | None = None) -> Any: + """`query(connection)` (default: execute `sql`), with DuckDB's errors + turned into catalog errors that say what was refused.""" + try: + connection = self.connection + return query(connection) if query else connection.execute(sql) + except CatalogOperationError: + raise + except Exception as exc: + message = str(exc) + if any(word in message for word in ("401", "Unauthorized")): + raise CatalogAuthError( + f"Polaris refused the query (your sign-in may have expired — sign in again " + f"and restart the kernel): {message}" + ) from exc + if any(word in message for word in ("403", "Forbidden", "not authorized")): + raise CatalogAuthError(f"no permission for this in Polaris: {message}") from exc + raise CatalogOperationError(f"DuckDB: {message}\n in: {sql}") from exc + + def execute(self, sql: str) -> None: + """Run a statement and discard any result.""" + self._run(sql) + + def fetch_all(self, sql: str) -> list[dict[str, Any]]: + """The rows of `sql`, as dicts keyed by column name.""" + cursor = self._run(sql) + columns = [column[0] for column in cursor.description or []] + return [dict(zip(columns, row, strict=True)) for row in cursor.fetchall()] + + def fetch_arrow(self, sql: str) -> pa.Table: + """The result of `sql` as an Arrow table.""" + + def query(connection: Any) -> pa.Table: + relation = connection.sql(sql) + # DuckDB 2 renamed fetch_arrow_table to to_arrow_table; both are supported. + fetch = getattr(relation, "to_arrow_table", None) or relation.fetch_arrow_table + return fetch() + + return self._run(sql, query) + + def record_batches(self, sql: str, batch_size: int = 100_000) -> pa.RecordBatchReader: + """The result of `sql`, streamed as Arrow record batches.""" + + def query(connection: Any) -> pa.RecordBatchReader: + relation = connection.sql(sql) + # DuckDB 2: to_arrow_reader; DuckDB 1: fetch_arrow_reader. + reader = getattr(relation, "to_arrow_reader", None) or relation.fetch_arrow_reader + return reader(batch_size) + + return self._run(sql, query) diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py new file mode 100644 index 0000000..b57839a --- /dev/null +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -0,0 +1,286 @@ +"""`PolarisCatalog` — the `CatalogBackend` for Apache Polaris. + +`%catalog` paths keep their Dremio shape, with the Polaris catalog's own name as +the root: ``eea_lakehouse....draft.stations``. Every +segment after the root but the last is an Iceberg namespace level; a folder is +a namespace, a table an Iceberg table — or a read-only Parquet table (a Polaris +generic table, as the Polaris Navigator registers them) — and a view an Iceberg +view. + +Lookups and metadata go through `PolarisRestClient` (Iceberg REST); SQL goes +through `DuckDbEngine`, in this kernel, as the signed-in user. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, Literal, NoReturn + +from .backend import Partitions, PublishOutcome +from .duckdb_engine import DuckDbEngine +from .errors import CatalogOperationError +from .operations import TableInfo, VersionResult +from .polaris_rest import PARQUET_FORMAT, PolarisRestClient +from .settings import PolarisSettings + +Kind = Literal["TABLE", "VIEW"] + + +class PolarisCatalog: + """`CatalogBackend` on Polaris — see the module docstring. + + `rest`/`engine` let a test (or a caller sharing connections) pass its own.""" + + def __init__( + self, + settings: PolarisSettings, + *, + rest: PolarisRestClient | None = None, + engine: DuckDbEngine | None = None, + ) -> None: + self._settings = settings + self.rest = rest or PolarisRestClient(settings) + self.engine = engine or DuckDbEngine(settings) + + def __repr__(self) -> str: + return f"PolarisCatalog(uri={self._settings.uri!r}, catalog={self.root!r})" + + @property + def root(self) -> str: + return self._settings.catalog + + def close(self) -> None: + self.engine.close() + self.rest.close() + + # -- paths ---------------------------------------------------------------- + + def parts(self, path: str) -> list[str]: + """`path` below the root, as segments: ``eea_lakehouse.a.b`` → ``["a", "b"]``; + the root itself → ``[]``.""" + if path == self.root: + return [] + prefix = f"{self.root}." + if not path.startswith(prefix): + raise CatalogOperationError( + f"{path!r} is not in the {self.root!r} catalog — Polaris paths start with " + f"{prefix!r}" + ) + parts = path[len(prefix) :].split(".") + if any(not part for part in parts): + raise CatalogOperationError(f"{path!r} has an empty segment") + return parts + + def path_of(self, parts: Sequence[str]) -> str: + """The dotted `%catalog` path of `parts` (the inverse of `parts`).""" + return ".".join([self.root, *parts]) + + def _split(self, path: str) -> tuple[list[str], str]: + """``(namespace, name)`` of the table or view `path`.""" + parts = self.parts(path) + if len(parts) < 2: + raise CatalogOperationError( + f"{path!r} can't be a table or view: tables live in a namespace below " + f"{self.root!r}, e.g. {self.root}.." + ) + return parts[:-1], parts[-1] + + # -- what is where ------------------------------------------------------------ + + def _kind_of(self, path: str) -> Kind | None: + """``"TABLE"``/``"VIEW"`` for a table or view at `path`, None if there is none.""" + parts = self.parts(path) + if len(parts) < 2: + return None + namespace, name = parts[:-1], parts[-1] + if self.rest.table_exists(namespace, name): + return "TABLE" + if self.rest.view_exists(namespace, name): + return "VIEW" + if self.rest.namespace_exists(namespace) and name in self._parquet_tables(namespace): + return "TABLE" + return None + + def _parquet_tables(self, namespace: Sequence[str]) -> list[str]: + """The read-only Parquet tables (generic tables of format parquet) in `namespace`.""" + names = [] + for name in self.rest.list_generic(namespace): + if self.rest.load_generic(namespace, name).get("format") == PARQUET_FORMAT: + names.append(name) + return names + + def exists(self, path: str) -> bool: + return self.is_folder(path) or self._kind_of(path) is not None + + def is_folder(self, path: str) -> bool: + parts = self.parts(path) + return not parts or self.rest.namespace_exists(parts) + + def entry_exists(self, path: str, *, idempotency_key: str) -> bool: + return self._kind_of(path) is not None + + def entry_kind(self, path: str, *, idempotency_key: str) -> Kind: + kind = self._kind_of(path) + if kind is None: + raise CatalogOperationError(f"{path!r} does not exist") + return kind + + def require_table_or_view(self, path: str, verb: str) -> None: + if self._kind_of(path) is not None: + return + if self.is_folder(path): + raise CatalogOperationError( + f"{verb} only works on tables/views — {path!r} is a folder (namespace)" + ) + raise CatalogOperationError(f"{path!r} does not exist") + + def list_dataset_kinds(self, path: str) -> list[tuple[str, str]]: + """Every table and view under the folder `path`, at any depth, sorted + by path — or just `path` itself when it is a table or view.""" + if not self.is_folder(path): + kind = self._kind_of(path) + if kind is None: + raise CatalogOperationError(f"{path!r} does not exist") + return [(path, kind)] + found: list[tuple[str, str]] = [] + pending = [self.parts(path)] + while pending: + namespace = pending.pop() + if namespace: + found.extend( + (self.path_of([*namespace, n]), "TABLE") + for n in self.rest.list_tables(namespace) + ) + found.extend( + (self.path_of([*namespace, n]), "TABLE") + for n in self._parquet_tables(namespace) + ) + found.extend( + (self.path_of([*namespace, n]), "VIEW") for n in self.rest.list_views(namespace) + ) + pending.extend(self.rest.list_namespaces(namespace)) + return sorted(found) + + def list_datasets(self, path: str) -> list[str]: + return [entry for entry, _ in self.list_dataset_kinds(path)] + + # -- not on Polaris yet (next steps of the migration) ---------------------------- + + def _not_yet(self, verb: str) -> NoReturn: + raise CatalogOperationError( + f"{verb} is not available on the Polaris backend yet — set " + "EEA_CATALOG_BACKEND=dremio to run it on Dremio" + ) + + def gettableitemsfrom(self, table_path: str, *, idempotency_key: str) -> TableInfo: + self._not_yet("schema") + + def ensure_folder_path(self, folder: str) -> list[str]: + self._not_yet("creating folders") + + def createfolder( + self, path: str, *, create_parents: bool = False, idempotency_key: str + ) -> None: + self._not_yet("create_folder") + + def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str) -> None: + self._not_yet("delete_folder") + + def datacopy( + self, + source_path: str, + target_path: str, + *, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> Any: + self._not_yet("data_copy") + + def datamove( + self, + source_path: str, + target_path: str, + *, + entry_type: Kind | None = None, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> Any: + self._not_yet("data_move") + + def createversion( + self, + source_path: str, + version_name: str, + tables: list[str] | None = None, + *, + target_path: str, + overwrite: bool = False, + create_target_folder: bool = True, + include_views: bool = False, + idempotency_key: str, + ) -> VersionResult: + self._not_yet("create_version") + + def createview( + self, + source_path: str, + target_path: str, + *, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> Any: + self._not_yet("create_view") + + def deleteview(self, view_path: str, *, idempotency_key: str) -> Any: + self._not_yet("delete_view") + + def deletetable(self, table_path: str, *, idempotency_key: str) -> Any: + self._not_yet("delete_table") + + def drop_entry(self, path: str, *, idempotency_key: str) -> None: + self._not_yet("dropping a table or view") + + def getwikifrom(self, path: str, *, idempotency_key: str) -> str: + self._not_yet("get_wiki") + + def setwikito( + self, + path: str, + text: str, + *, + tags: list[dict[str, str]] | None = None, + idempotency_key: str, + ) -> None: + self._not_yet("set_wiki") + + def deletewiki(self, path: str, *, idempotency_key: str) -> None: + self._not_yet("delete_wiki") + + def gettagsfrom(self, path: str, *, idempotency_key: str) -> list[str]: + self._not_yet("get_tags") + + def settagsto(self, path: str, tags: list[str], *, idempotency_key: str) -> None: + self._not_yet("set_tags") + + def deletetags(self, path: str, tags: list[str], *, idempotency_key: str) -> None: + self._not_yet("delete_tags") + + def publish_target(self, area: str) -> str: + return f"the public data store ({area})" + + def check_publish(self, area: str, partitions: Partitions, *, idempotency_key: str) -> None: + self._not_yet("publish") + + def publish_dataflow( + self, + area: str, + *, + overwrite: bool, + partitions: Partitions, + idempotency_key: str, + notes: list[str], + ) -> PublishOutcome: + self._not_yet("publish") diff --git a/src/eea_datalakehouse/catalog/polaris_rest.py b/src/eea_datalakehouse/catalog/polaris_rest.py new file mode 100644 index 0000000..e434a91 --- /dev/null +++ b/src/eea_datalakehouse/catalog/polaris_rest.py @@ -0,0 +1,493 @@ +"""`PolarisRestClient` — the Apache Polaris calls the Polaris backend makes. + +Two APIs under ``POLARIS_URI`` (``…/api/catalog``): + +* the Iceberg REST catalog, ``/v1/{prefix}/…`` — namespaces, tables, views, + and their properties; +* Polaris' own generic tables, ``/polaris/v1/{prefix}/…`` — a folder of Parquet + files registered as a read-only table (format ``parquet``), as the EEA + Lakehouse's Polaris Navigator does. + +``{prefix}`` comes from ``GET /v1/config?warehouse=`` (the catalog's +name on Polaris), asked once. + +**Who is calling.** The signed-in user's own Keycloak token +(``KEYCLOAK_ACCESS_TOKEN``, read on every request — see `settings.user_token`) +when there is one, so Polaris applies that user's grants. Otherwise a Polaris +client-credentials token (``POLARIS_CLIENT_ID``/``_SECRET``, scope +``PRINCIPAL_ROLE:ALL`` — the only scope Polaris accepts), minted from +``/v1/oauth/tokens`` and kept until shortly before it expires. + +**Names.** A namespace is a list of parts (``["water", "bwd", "draft"]``); in a +URL the parts are joined with ``\\x1f`` and percent-encoded (``%1F``). + +**Errors.** 401/403 raise `CatalogAuthError`; a missing namespace, table or +view raises `PolarisNotFoundError`; anything else `CatalogOperationError` — +each with Polaris' own message when it sent one. +""" + +from __future__ import annotations + +import time +import urllib.parse +from collections.abc import Callable, Iterator, Mapping, Sequence +from typing import Any + +import httpx + +from .errors import CatalogAuthError, CatalogOperationError +from .settings import PolarisSettings, user_token + +SEP = "\x1f" # between nested namespace parts in Iceberg REST URLs +DEFAULT_TIMEOUT = 60.0 +_TOKEN_MARGIN = 30.0 # seconds: mint a new token this long before the old one expires +_PAGE_SIZE = 1000 + +PARQUET_FORMAT = "parquet" # a generic table: a folder of Parquet files, read-only + +Namespace = Sequence[str] + + +class PolarisHttpError(CatalogOperationError): + """Polaris refused or failed a request; `status` is its HTTP status.""" + + def __init__(self, message: str, *, status: int) -> None: + super().__init__(message) + self.status = status + + +class PolarisNotFoundError(PolarisHttpError): + """Polaris answered 404: the namespace, table or view does not exist.""" + + def __init__(self, message: str) -> None: + super().__init__(message, status=404) + + +# Statuses that mean "this catalog doesn't offer that" (views or generic tables off). +_NOT_OFFERED = (400, 404, 405, 501) + + +def ns_param(namespace: Namespace) -> str: + """`namespace` as one URL path segment / query value: parts joined with ``\\x1f``, encoded.""" + return urllib.parse.quote(SEP.join(namespace), safe="") + + +def _quote(name: str) -> str: + return urllib.parse.quote(name, safe="") + + +def _message(response: httpx.Response) -> str: + """Polaris' own error message (``{"error": {"message": …}}``), else the status.""" + try: + body = response.json() + except ValueError: + body = None + if isinstance(body, dict): + error = body.get("error") + if isinstance(error, dict) and error.get("message"): + return str(error["message"]) + if body.get("error_description"): # the OAuth token endpoint's shape + return str(body["error_description"]) + text = response.text.strip() + return text[:300] if text else f"HTTP {response.status_code}" + + +class PolarisRestClient: + """Iceberg REST + Polaris generic-table calls for one catalog — see the module docstring. + + `http` lets a test (or a caller with its own transport) pass an + `httpx.Client`; `token_provider` returns the user's token or None (default: + `settings.user_token`, reading ``KEYCLOAK_ACCESS_TOKEN``).""" + + def __init__( + self, + settings: PolarisSettings, + *, + http: httpx.Client | None = None, + token_provider: Callable[[], str | None] = user_token, + timeout: float = DEFAULT_TIMEOUT, + ) -> None: + self._settings = settings + self._owns_http = http is None + self._http = http or httpx.Client(timeout=timeout) + self._token_provider = token_provider + self._minted: tuple[str, float] | None = None # (token, renew after) + self._prefix: str | None = None + + def __repr__(self) -> str: + return f"PolarisRestClient(uri={self._settings.uri!r}, catalog={self._settings.catalog!r})" + + @property + def catalog(self) -> str: + return self._settings.catalog + + def close(self) -> None: + if self._owns_http: + self._http.close() + + # -- authentication --------------------------------------------------- + + def token(self) -> str: + """The bearer token for the next request — see the module docstring.""" + user = self._token_provider() + if user: + return user + if self._minted and time.monotonic() < self._minted[1]: + return self._minted[0] + return self._mint() + + def _mint(self) -> str: + settings = self._settings + if not settings.client_id or not settings.client_secret: + raise CatalogAuthError( + "no Polaris identity: KEYCLOAK_ACCESS_TOKEN (your own sign-in) is not set, and " + "neither are POLARIS_CLIENT_ID/POLARIS_CLIENT_SECRET" + ) + try: + response = self._http.post( + f"{settings.uri}/v1/oauth/tokens", + data={ + "grant_type": "client_credentials", + "client_id": settings.client_id, + "client_secret": settings.client_secret, + "scope": "PRINCIPAL_ROLE:ALL", + }, + ) + except httpx.HTTPError as exc: + raise CatalogOperationError( + f"Polaris can't be reached at {settings.uri}: {exc}" + ) from exc + if response.status_code >= 400: + raise CatalogAuthError( + f"Polaris refused the client credentials of {settings.client_id!r}: " + f"{_message(response)}" + ) + body = response.json() + token = body.get("access_token") + if not token: + raise CatalogAuthError("Polaris' token response has no access_token") + ttl = float(body.get("expires_in") or 3600) + self._minted = (str(token), time.monotonic() + max(ttl - _TOKEN_MARGIN, 0.0)) + return str(token) + + # -- plumbing ----------------------------------------------------------- + + @property + def prefix(self) -> str: + """The catalog's URL prefix, from ``/v1/config`` (asked once); its name if not given.""" + if self._prefix is None: + config = self._send( + "GET", f"{self._settings.uri}/v1/config", params={"warehouse": self.catalog} + ).json() + prefix = (config.get("overrides") or {}).get("prefix") or ( + config.get("defaults") or {} + ).get("prefix") + self._prefix = str(prefix) if prefix else self.catalog + return self._prefix + + def _url(self, path: str, api: str) -> str: + return f"{self._settings.uri}/{api}/{_quote(self.prefix)}{path}" + + def _send( + self, + method: str, + url: str, + *, + json: Any = None, + params: Mapping[str, str] | None = None, + ) -> httpx.Response: + """One request with the current token; a minted token that Polaris + refuses (401) is minted again once — a user token is not ours to renew.""" + for attempt in (1, 2): + token = self.token() + try: + response = self._http.request( + method, + url, + json=json, + params=params, + headers={"Authorization": f"Bearer {token}", "Accept": "application/json"}, + ) + except httpx.HTTPError as exc: + raise CatalogOperationError( + f"Polaris can't be reached ({method} {url}): {exc}" + ) from exc + minted_refused = ( + response.status_code == 401 + and attempt == 1 + and self._minted is not None + and self._minted[0] == token + ) + if minted_refused: + self._minted = None + continue + break + if response.status_code < 400: + return response + where = f"{method} {urllib.parse.urlsplit(url).path}" + message = _message(response) + if response.status_code == 401: + hint = ( + " — your sign-in has expired: sign in to JupyterHub again and restart the kernel" + if self._token_provider() + else "" + ) + raise CatalogAuthError(f"Polaris refused the request ({where}): {message}{hint}") + if response.status_code == 403: + raise CatalogAuthError(f"no permission for this in Polaris ({where}): {message}") + if response.status_code == 404: + raise PolarisNotFoundError(message) + raise PolarisHttpError( + f"Polaris {where} failed (HTTP {response.status_code}): {message}", + status=response.status_code, + ) + + def _call( + self, + method: str, + path: str, + *, + json: Any = None, + params: Mapping[str, str] | None = None, + api: str = "v1", + ) -> Any: + response = self._send(method, self._url(path, api), json=json, params=params) + if not response.content: + return None + return response.json() + + def _exists(self, path: str) -> bool: + """``HEAD`` `path`: True on 2xx, False on 404.""" + try: + self._send("HEAD", self._url(path, "v1")) + except PolarisNotFoundError: + return False + return True + + def _pages(self, path: str, key: str, params: Mapping[str, str] | None = None) -> Iterator[Any]: + """Every item of the list `key`, following ``next-page-token``.""" + query = dict(params or {}) + while True: + body = self._call("GET", path, params=query) or {} + yield from body.get(key) or [] + token = body.get("next-page-token") + if not token: + return + query = {**query, "pageToken": str(token), "pageSize": str(_PAGE_SIZE)} + + # -- namespaces --------------------------------------------------------- + + @staticmethod + def _ns_path(namespace: Namespace) -> str: + return f"/namespaces/{ns_param(namespace)}" + + def list_namespaces(self, parent: Namespace = ()) -> list[list[str]]: + """The namespaces just below `parent` (the top level when empty), as part lists.""" + params = {"parent": SEP.join(parent)} if parent else None + return [list(ns) for ns in self._pages("/namespaces", "namespaces", params)] + + def namespace_exists(self, namespace: Namespace) -> bool: + return bool(namespace) and self._exists(self._ns_path(namespace)) + + def namespace_properties(self, namespace: Namespace) -> dict[str, str]: + body = self._call("GET", self._ns_path(namespace)) or {} + return dict(body.get("properties") or {}) + + def create_namespace( + self, namespace: Namespace, properties: Mapping[str, str] | None = None + ) -> bool: + """Create `namespace` (its parent must exist); False if it already did.""" + try: + self._call( + "POST", + "/namespaces", + json={"namespace": list(namespace), "properties": dict(properties or {})}, + ) + except PolarisHttpError as exc: + if exc.status == 409: + return False + raise + return True + + def drop_namespace(self, namespace: Namespace) -> None: + """Delete `namespace` — Polaris refuses one that still holds anything.""" + self._call("DELETE", self._ns_path(namespace)) + + def update_namespace_properties( + self, + namespace: Namespace, + updates: Mapping[str, str] | None = None, + removals: Sequence[str] = (), + ) -> None: + self._call( + "POST", + f"{self._ns_path(namespace)}/properties", + json={"updates": dict(updates or {}), "removals": list(removals)}, + ) + + # -- tables and views --------------------------------------------------- + + def list_tables(self, namespace: Namespace) -> list[str]: + """Iceberg table names directly in `namespace`.""" + return [i["name"] for i in self._pages(f"{self._ns_path(namespace)}/tables", "identifiers")] + + def list_views(self, namespace: Namespace) -> list[str]: + """View names directly in `namespace`; empty where views aren't enabled.""" + try: + return [ + i["name"] for i in self._pages(f"{self._ns_path(namespace)}/views", "identifiers") + ] + except PolarisHttpError as exc: + # 404 too, as the Navigator does: views off answers it on some servers. + # Callers list tables first, which reports a missing namespace. + if exc.status in _NOT_OFFERED: + return [] + raise + + def _entry_path(self, namespace: Namespace, name: str, kind: str) -> str: + return f"{self._ns_path(namespace)}/{kind}/{_quote(name)}" + + def table_exists(self, namespace: Namespace, name: str) -> bool: + return self._exists(self._entry_path(namespace, name, "tables")) + + def view_exists(self, namespace: Namespace, name: str) -> bool: + try: + return self._exists(self._entry_path(namespace, name, "views")) + except PolarisHttpError as exc: + if exc.status in _NOT_OFFERED: + return False # views not enabled here + raise + + def load_table(self, namespace: Namespace, name: str) -> dict[str, Any]: + """The table's metadata (``schemas``, ``snapshots``, ``properties``, ``location``…).""" + body = self._call("GET", self._entry_path(namespace, name, "tables")) or {} + return dict(body.get("metadata") or {}) + + def load_view(self, namespace: Namespace, name: str) -> dict[str, Any]: + """The view's metadata (``versions``, ``schemas``, ``properties``…).""" + body = self._call("GET", self._entry_path(namespace, name, "views")) or {} + return dict(body.get("metadata") or {}) + + def drop_table(self, namespace: Namespace, name: str, *, purge: bool = True) -> None: + """Drop the table; `purge` also deletes its data files (Polaris' default keeps them).""" + self._call( + "DELETE", + self._entry_path(namespace, name, "tables"), + params={"purgeRequested": "true"} if purge else None, + ) + + def drop_view(self, namespace: Namespace, name: str) -> None: + self._call("DELETE", self._entry_path(namespace, name, "views")) + + def create_view( + self, + namespace: Namespace, + name: str, + *, + sql: str, + fields: Sequence[Mapping[str, Any]], + default_namespace: Namespace = (), + dialect: str = "duckdb", + properties: Mapping[str, str] | None = None, + ) -> None: + """Register a view: its SQL, and the Iceberg schema `fields` of what it + returns (``{"id", "name", "type", "required"}`` each).""" + self._call( + "POST", + f"{self._ns_path(namespace)}/views", + json={ + "name": name, + "schema": {"type": "struct", "schema-id": 0, "fields": [dict(f) for f in fields]}, + "view-version": { + "version-id": 1, + "schema-id": 0, + "timestamp-ms": int(time.time() * 1000), + "summary": {"engine-name": dialect, "engine-version": "eea_datalakehouse"}, + "default-namespace": list(default_namespace), + "representations": [{"type": "sql", "sql": sql, "dialect": dialect}], + }, + "properties": dict(properties or {}), + }, + ) + + def _commit_properties( + self, + namespace: Namespace, + name: str, + kind: str, + updates: Mapping[str, str], + removals: Sequence[str], + ) -> None: + changes: list[dict[str, Any]] = [] + if updates: + changes.append({"action": "set-properties", "updates": dict(updates)}) + if removals: + changes.append({"action": "remove-properties", "removals": list(removals)}) + if changes: + self._call( + "POST", + self._entry_path(namespace, name, kind), + json={"requirements": [], "updates": changes}, + ) + + def update_table_properties( + self, + namespace: Namespace, + name: str, + updates: Mapping[str, str] | None = None, + removals: Sequence[str] = (), + ) -> None: + self._commit_properties(namespace, name, "tables", updates or {}, removals) + + def update_view_properties( + self, + namespace: Namespace, + name: str, + updates: Mapping[str, str] | None = None, + removals: Sequence[str] = (), + ) -> None: + self._commit_properties(namespace, name, "views", updates or {}, removals) + + # -- generic tables (read-only Parquet folders) ------------------------- + + def _generic_path(self, namespace: Namespace, name: str | None = None) -> str: + path = f"{self._ns_path(namespace)}/generic-tables" + return f"{path}/{_quote(name)}" if name else path + + def list_generic(self, namespace: Namespace) -> list[str]: + """Generic table names in `namespace`; empty where generic tables aren't enabled.""" + try: + body = self._call("GET", self._generic_path(namespace), api="polaris/v1") or {} + except PolarisHttpError as exc: + if exc.status in _NOT_OFFERED: + return [] + raise + return [i["name"] for i in body.get("identifiers") or []] + + def load_generic(self, namespace: Namespace, name: str) -> dict[str, Any]: + """``{"name", "format", "base-location", "doc", "properties"}``.""" + body = self._call("GET", self._generic_path(namespace, name), api="polaris/v1") or {} + return dict(body.get("table") or {}) + + def create_generic( + self, + namespace: Namespace, + name: str, + *, + fmt: str, + base_location: str | None = None, + doc: str | None = None, + properties: Mapping[str, str] | None = None, + ) -> None: + body: dict[str, Any] = { + "name": name, + "format": fmt, + "doc": doc or None, + "properties": dict(properties or {}), + } + if base_location: + body["base-location"] = base_location + self._call("POST", self._generic_path(namespace), json=body, api="polaris/v1") + + def drop_generic(self, namespace: Namespace, name: str) -> None: + self._call("DELETE", self._generic_path(namespace, name), api="polaris/v1") diff --git a/src/eea_datalakehouse/notebook/magics.py b/src/eea_datalakehouse/notebook/magics.py index 2337a64..8eed059 100644 --- a/src/eea_datalakehouse/notebook/magics.py +++ b/src/eea_datalakehouse/notebook/magics.py @@ -102,11 +102,11 @@ from ..catalog import Catalog from ..catalog.backend import CatalogBackend +from ..catalog.polaris import PolarisCatalog from ..catalog.session import CatalogSession, CatalogSessionError from ..catalog.settings import ( DremioSettings, PolarisSettings, - SettingsError, backend_name, ) from ..dds_documents.controller import DdsFolder, PushReport, closest_folder, valid_folders_hint @@ -604,11 +604,7 @@ def _build_catalog_session() -> CatalogSession: `catalog.settings`) — a `SettingsError` (a `RuntimeError`) names whatever variable is missing.""" if backend_name() == "polaris": - PolarisSettings.from_env() # a missing variable is reported first - raise SettingsError( - "%catalog: the Polaris backend is not implemented yet on this branch — " - "set EEA_CATALOG_BACKEND=dremio to use Dremio" - ) + return CatalogSession(PolarisCatalog(PolarisSettings.from_env())) dremio = DremioSettings.from_env() return CatalogSession(Catalog(dremio.base_url, dremio.token, username=dremio.username)) diff --git a/tests/catalog/polaris_fakes.py b/tests/catalog/polaris_fakes.py new file mode 100644 index 0000000..c55688b --- /dev/null +++ b/tests/catalog/polaris_fakes.py @@ -0,0 +1,242 @@ +"""An in-memory stand-in for `PolarisRestClient`, for `PolarisCatalog` tests. + +Holds namespaces (with properties), Iceberg tables, views and generic tables, +and answers the client's calls the way Polaris does: a missing namespace is +`PolarisNotFoundError`, an existing one on create is False (409), a namespace +that still holds anything can't be dropped (400). +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any + +from eea_datalakehouse.catalog.polaris_rest import PolarisHttpError, PolarisNotFoundError + +Key = tuple[str, ...] + + +@dataclass +class FakeEntry: + properties: dict[str, str] = field(default_factory=dict) + metadata: dict[str, Any] = field(default_factory=dict) + + +class FakePolarisRest: + def __init__(self, catalog: str = "eea_lakehouse") -> None: + self.catalog = catalog + self.namespaces: dict[Key, dict[str, str]] = {} + self.tables: dict[tuple[Key, str], FakeEntry] = {} + self.views: dict[tuple[Key, str], FakeEntry] = {} + self.generic: dict[tuple[Key, str], dict[str, Any]] = {} + self.calls: list[tuple[Any, ...]] = [] + self.closed = False + + # -- building a catalog for a test ------------------------------------- + + def add_namespace(self, *parts: str, **properties: str) -> FakePolarisRest: + for depth in range(1, len(parts) + 1): + self.namespaces.setdefault(tuple(parts[:depth]), {}) + self.namespaces[tuple(parts)].update(properties) + return self + + def add_table(self, dotted: str, **properties: str) -> FakePolarisRest: + *namespace, name = dotted.split(".") + self.add_namespace(*namespace) + self.tables[(tuple(namespace), name)] = FakeEntry(dict(properties)) + return self + + def add_view(self, dotted: str, sql: str = "SELECT 1", **properties: str) -> FakePolarisRest: + *namespace, name = dotted.split(".") + self.add_namespace(*namespace) + self.views[(tuple(namespace), name)] = FakeEntry(dict(properties), {"sql": sql}) + return self + + def add_parquet(self, dotted: str, location: str = "s3://b/x/") -> FakePolarisRest: + *namespace, name = dotted.split(".") + self.add_namespace(*namespace) + self.generic[(tuple(namespace), name)] = { + "name": name, + "format": "parquet", + "base-location": location, + "properties": {}, + } + return self + + # -- the PolarisRestClient surface ---------------------------------------- + + def close(self) -> None: + self.closed = True + + def _need(self, namespace: Sequence[str]) -> Key: + key = tuple(namespace) + if key not in self.namespaces: + raise PolarisNotFoundError(f"Namespace does not exist: {'.'.join(key)}") + return key + + def list_namespaces(self, parent: Sequence[str] = ()) -> list[list[str]]: + parent_key = tuple(parent) + if parent_key: + self._need(parent_key) + return [ + list(key) + for key in sorted(self.namespaces) + if len(key) == len(parent_key) + 1 and key[: len(parent_key)] == parent_key + ] + + def namespace_exists(self, namespace: Sequence[str]) -> bool: + return bool(namespace) and tuple(namespace) in self.namespaces + + def namespace_properties(self, namespace: Sequence[str]) -> dict[str, str]: + return dict(self.namespaces[self._need(namespace)]) + + def create_namespace( + self, namespace: Sequence[str], properties: Mapping[str, str] | None = None + ) -> bool: + self.calls.append(("create_namespace", tuple(namespace))) + key = tuple(namespace) + if key in self.namespaces: + return False + if len(key) > 1: + self._need(key[:-1]) + self.namespaces[key] = dict(properties or {}) + return True + + def drop_namespace(self, namespace: Sequence[str]) -> None: + self.calls.append(("drop_namespace", tuple(namespace))) + key = self._need(namespace) + holds = ( + any(k[: len(key)] == key and k != key for k in self.namespaces) + or any(ns == key for ns, _ in self.tables) + or any(ns == key for ns, _ in self.views) + or any(ns == key for ns, _ in self.generic) + ) + if holds: + raise PolarisHttpError(f"Namespace {'.'.join(key)} is not empty", status=400) + del self.namespaces[key] + + def update_namespace_properties( + self, + namespace: Sequence[str], + updates: Mapping[str, str] | None = None, + removals: Sequence[str] = (), + ) -> None: + self.calls.append(("update_namespace_properties", tuple(namespace))) + properties = self.namespaces[self._need(namespace)] + properties.update(updates or {}) + for key in removals: + properties.pop(key, None) + + def list_tables(self, namespace: Sequence[str]) -> list[str]: + key = self._need(namespace) + return sorted(name for ns, name in self.tables if ns == key) + + def list_views(self, namespace: Sequence[str]) -> list[str]: + key = self._need(namespace) + return sorted(name for ns, name in self.views if ns == key) + + def table_exists(self, namespace: Sequence[str], name: str) -> bool: + return (tuple(namespace), name) in self.tables + + def view_exists(self, namespace: Sequence[str], name: str) -> bool: + return (tuple(namespace), name) in self.views + + def load_table(self, namespace: Sequence[str], name: str) -> dict[str, Any]: + entry = self.tables.get((tuple(namespace), name)) + if entry is None: + raise PolarisNotFoundError(f"Table does not exist: {name}") + return {"properties": dict(entry.properties), **entry.metadata} + + def load_view(self, namespace: Sequence[str], name: str) -> dict[str, Any]: + entry = self.views.get((tuple(namespace), name)) + if entry is None: + raise PolarisNotFoundError(f"View does not exist: {name}") + return {"properties": dict(entry.properties), **entry.metadata} + + def drop_table(self, namespace: Sequence[str], name: str, *, purge: bool = True) -> None: + self.calls.append(("drop_table", tuple(namespace), name)) + if self.tables.pop((tuple(namespace), name), None) is None: + raise PolarisNotFoundError(f"Table does not exist: {name}") + + def drop_view(self, namespace: Sequence[str], name: str) -> None: + self.calls.append(("drop_view", tuple(namespace), name)) + if self.views.pop((tuple(namespace), name), None) is None: + raise PolarisNotFoundError(f"View does not exist: {name}") + + def create_view( + self, + namespace: Sequence[str], + name: str, + *, + sql: str, + fields: Sequence[Mapping[str, Any]], + default_namespace: Sequence[str] = (), + dialect: str = "duckdb", + properties: Mapping[str, str] | None = None, + ) -> None: + self.calls.append(("create_view", tuple(namespace), name)) + key = self._need(namespace) + if (key, name) in self.views or (key, name) in self.tables: + raise PolarisHttpError(f"{name} already exists", status=409) + self.views[(key, name)] = FakeEntry( + dict(properties or {}), {"sql": sql, "fields": [dict(f) for f in fields]} + ) + + def update_table_properties( + self, + namespace: Sequence[str], + name: str, + updates: Mapping[str, str] | None = None, + removals: Sequence[str] = (), + ) -> None: + entry = self.tables[(tuple(namespace), name)] + entry.properties.update(updates or {}) + for key in removals: + entry.properties.pop(key, None) + + def update_view_properties( + self, + namespace: Sequence[str], + name: str, + updates: Mapping[str, str] | None = None, + removals: Sequence[str] = (), + ) -> None: + entry = self.views[(tuple(namespace), name)] + entry.properties.update(updates or {}) + for key in removals: + entry.properties.pop(key, None) + + def list_generic(self, namespace: Sequence[str]) -> list[str]: + key = tuple(namespace) + return sorted(name for ns, name in self.generic if ns == key) + + def load_generic(self, namespace: Sequence[str], name: str) -> dict[str, Any]: + entry = self.generic.get((tuple(namespace), name)) + if entry is None: + raise PolarisNotFoundError(f"Generic table does not exist: {name}") + return dict(entry) + + def create_generic( + self, + namespace: Sequence[str], + name: str, + *, + fmt: str, + base_location: str | None = None, + doc: str | None = None, + properties: Mapping[str, str] | None = None, + ) -> None: + self.calls.append(("create_generic", tuple(namespace), name)) + self.generic[(self._need(namespace), name)] = { + "name": name, + "format": fmt, + "base-location": base_location, + "doc": doc, + "properties": dict(properties or {}), + } + + def drop_generic(self, namespace: Sequence[str], name: str) -> None: + self.calls.append(("drop_generic", tuple(namespace), name)) + if self.generic.pop((tuple(namespace), name), None) is None: + raise PolarisNotFoundError(f"Generic table does not exist: {name}") diff --git a/tests/catalog/test_duckdb_engine.py b/tests/catalog/test_duckdb_engine.py new file mode 100644 index 0000000..b68c4cd --- /dev/null +++ b/tests/catalog/test_duckdb_engine.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +from typing import Any + +import duckdb +import pytest + +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine, quote_identifier, quote_literal +from eea_datalakehouse.catalog.errors import CatalogAuthError, CatalogOperationError +from eea_datalakehouse.catalog.settings import PolarisSettings + +URI = "http://polaris.test/api/catalog" + + +class FakeConnection: + """Records statements; `fail_on` makes the first statement containing it raise.""" + + def __init__(self, fail_on: dict[str, str] | None = None) -> None: + self.statements: list[str] = [] + self.fail_on = fail_on or {} + self.closed = False + + def execute(self, sql: str) -> FakeConnection: + self.statements.append(sql) + for needle, message in self.fail_on.items(): + if needle in sql: + raise duckdb.Error(message) + return self + + def close(self) -> None: + self.closed = True + + +def _engine( + settings: PolarisSettings | None = None, + token: str | None = "user-jwt", + connection: FakeConnection | None = None, +) -> tuple[DuckDbEngine, list[FakeConnection]]: + made: list[FakeConnection] = [] + + def connect() -> Any: + made.append(connection or FakeConnection()) + return made[-1] + + engine = DuckDbEngine( + settings or PolarisSettings(uri=URI, s3_access_key="ak", s3_secret_key="sk"), + connect=connect, + token_provider=lambda: token, + ) + return engine, made + + +def test_quoting() -> None: + assert quote_identifier('a"b') == '"a""b"' + assert quote_literal("it's") == "'it''s'" + + +def test_table_ref_puts_the_whole_namespace_in_one_identifier() -> None: + engine, _ = _engine() + assert engine.table_ref(["water", "bwd", "draft"], "stations") == ( + '"eea_lakehouse"."water.bwd.draft"."stations"' + ) + with pytest.raises(CatalogOperationError, match="not inside a namespace"): + engine.table_ref([], "stations") + + +def test_connection_loads_extensions_creates_secrets_and_attaches_once() -> None: + engine, made = _engine() + + engine.execute("SELECT 1") + engine.execute("SELECT 2") + + assert len(made) == 1 + statements = made[0].statements + assert statements[:4] == ["INSTALL iceberg", "LOAD iceberg", "INSTALL httpfs", "LOAD httpfs"] + s3, polaris, attach = (s for s in statements if s.startswith(("CREATE", "ATTACH"))) + assert s3 == ( + "CREATE OR REPLACE SECRET eea_catalog_s3 (TYPE s3, KEY_ID 'ak', SECRET 'sk', " + "ENDPOINT 'localhost:9100', URL_STYLE 'path', USE_SSL false, REGION 'us-east-1')" + ) + assert polaris == ( + "CREATE OR REPLACE SECRET eea_catalog_polaris (TYPE iceberg, TOKEN 'user-jwt', " + f"ENDPOINT '{URI}')" + ) + assert attach == ( + "ATTACH 'eea_lakehouse' AS \"eea_lakehouse\" (TYPE iceberg, " + f"ENDPOINT '{URI}', SECRET eea_catalog_polaris, ACCESS_DELEGATION_MODE 'none')" + ) + assert statements[-2:] == ["SELECT 1", "SELECT 2"] + + +def test_client_credentials_without_a_user_token() -> None: + settings = PolarisSettings(uri=URI, client_id="root", client_secret="s'cret") + engine, _ = _engine(settings, token=None) + polaris = engine.setup_statements()[1] + assert "CLIENT_ID 'root', CLIENT_SECRET 's''cret'" in polaris + assert "TOKEN" not in polaris + + +def test_no_identity_is_an_auth_error() -> None: + engine, _ = _engine(PolarisSettings(uri=URI), token=None) + with pytest.raises(CatalogAuthError, match="KEYCLOAK_ACCESS_TOKEN"): + engine.execute("SELECT 1") + + +def test_vended_credentials_skip_the_static_key() -> None: + engine, _ = _engine(PolarisSettings(uri=URI, vended_credentials=True)) + statements = engine.setup_statements() + assert not any("TYPE s3" in s for s in statements) + assert "ACCESS_DELEGATION_MODE 'vended_credentials'" in statements[-1] + + +def test_https_endpoint_turns_ssl_on() -> None: + engine, _ = _engine(PolarisSettings(uri=URI, s3_endpoint="https://s3.example:443")) + assert ( + "ENDPOINT 's3.example:443', URL_STYLE 'path', USE_SSL true" in engine.setup_statements()[0] + ) + + +def test_a_missing_optional_extension_is_skipped() -> None: + engine, made = _engine(connection=FakeConnection(fail_on={"INSTALL spatial": "offline"})) + engine.execute("SELECT 1") + assert "SELECT 1" in made[0].statements + + +def test_a_failed_attach_closes_the_connection_and_explains() -> None: + connection = FakeConnection(fail_on={"ATTACH": "Could not connect to server"}) + engine, _ = _engine(connection=connection) + with pytest.raises(CatalogOperationError, match="could not attach the Polaris catalog"): + engine.execute("SELECT 1") + assert connection.closed + + +def test_a_refused_attach_is_an_auth_error() -> None: + connection = FakeConnection(fail_on={"ATTACH": "HTTP 401 Unauthorized"}) + engine, _ = _engine(connection=connection) + with pytest.raises(CatalogAuthError): + engine.execute("SELECT 1") + + +def test_reset_opens_a_new_connection_with_the_current_token() -> None: + tokens = iter(["first", "second"]) + current = {"token": next(tokens)} + made: list[FakeConnection] = [] + + def connect() -> FakeConnection: + made.append(FakeConnection()) + return made[-1] + + engine = DuckDbEngine( + PolarisSettings(uri=URI), connect=connect, token_provider=lambda: current["token"] + ) + engine.execute("SELECT 1") + current["token"] = next(tokens) + engine.reset() + engine.execute("SELECT 1") + + assert made[0].closed + assert any("TOKEN 'first'" in s for s in made[0].statements) + assert any("TOKEN 'second'" in s for s in made[1].statements) + + +def _real_engine() -> DuckDbEngine: + """An engine on a plain in-memory DuckDB, without the catalog (no Polaris here).""" + engine = DuckDbEngine(PolarisSettings(uri=URI), token_provider=lambda: "t") + engine._connection = duckdb.connect() # noqa: SLF001 — skip the ATTACH + return engine + + +def test_queries_on_real_duckdb() -> None: + engine = _real_engine() + assert engine.fetch_all("SELECT 1 AS a, 'x' AS b") == [{"a": 1, "b": "x"}] + assert engine.fetch_arrow("SELECT 1 AS a").to_pylist() == [{"a": 1}] + assert engine.record_batches("SELECT range AS n FROM range(5)", 2).read_all().num_rows == 5 + + +def test_sql_errors_name_the_statement() -> None: + engine = _real_engine() + with pytest.raises(CatalogOperationError, match="in: SELECT \\* FROM nope"): + engine.execute("SELECT * FROM nope") + + +def test_query_refusals_are_auth_errors() -> None: + engine, _ = _engine(connection=FakeConnection(fail_on={"SELECT": "HTTP 403 Forbidden"})) + with pytest.raises(CatalogAuthError, match="no permission"): + engine.execute("SELECT 1") diff --git a/tests/catalog/test_polaris_catalog.py b/tests/catalog/test_polaris_catalog.py new file mode 100644 index 0000000..fb469d9 --- /dev/null +++ b/tests/catalog/test_polaris_catalog.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +from typing import Any, cast + +import pytest + +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogOperationError +from eea_datalakehouse.catalog.polaris import PolarisCatalog +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.session import CatalogSession, CatalogSessionError +from eea_datalakehouse.catalog.settings import PolarisSettings + +from .polaris_fakes import FakePolarisRest + +SETTINGS = PolarisSettings(uri="http://polaris.test/api/catalog") +AREA = "eea_lakehouse.water.bathing.bwd" + + +def _catalog(rest: FakePolarisRest | None = None) -> tuple[PolarisCatalog, FakePolarisRest]: + rest = rest or FakePolarisRest() + engine = DuckDbEngine(SETTINGS, connect=lambda: None, token_provider=lambda: "t") + catalog = PolarisCatalog(SETTINGS, rest=cast(PolarisRestClient, rest), engine=engine) + return catalog, rest + + +def _bwd() -> FakePolarisRest: + return ( + FakePolarisRest() + .add_table("water.bathing.bwd.draft.stations") + .add_table("water.bathing.bwd.draft.raw.samples") + .add_view("water.bathing.bwd.draft.latest_samples") + .add_parquet("water.bathing.bwd.reference.countries") + .add_namespace("water", "bathing", "bwd", "versions") + ) + + +def test_root_is_the_catalog_name() -> None: + catalog, _ = _catalog() + assert catalog.root == "eea_lakehouse" + assert CatalogSession(catalog).get_context() == "eea_lakehouse" + + +def test_parts_and_path_of() -> None: + catalog, _ = _catalog() + assert catalog.parts("eea_lakehouse") == [] + assert catalog.parts("eea_lakehouse.water.bwd") == ["water", "bwd"] + assert catalog.path_of(["water", "bwd"]) == "eea_lakehouse.water.bwd" + + +@pytest.mark.parametrize("path", ["catalog.water", "eea_lakehousex.water", "eea_lakehouse..a"]) +def test_paths_outside_the_catalog_are_refused(path: str) -> None: + catalog, _ = _catalog() + with pytest.raises(CatalogOperationError): + catalog.parts(path) + + +def test_exists_and_is_folder() -> None: + catalog, _ = _catalog(_bwd()) + + assert catalog.is_folder("eea_lakehouse") + assert catalog.is_folder(f"{AREA}.draft") + assert not catalog.is_folder(f"{AREA}.draft.stations") + for present in ( + AREA, + f"{AREA}.draft.stations", + f"{AREA}.draft.latest_samples", + f"{AREA}.reference.countries", + ): + assert catalog.exists(present), present + assert not catalog.exists(f"{AREA}.draft.nope") + assert not catalog.exists("eea_lakehouse.nowhere.x") + + +def test_entry_kind() -> None: + catalog, _ = _catalog(_bwd()) + + assert catalog.entry_kind(f"{AREA}.draft.stations", idempotency_key="k") == "TABLE" + assert catalog.entry_kind(f"{AREA}.draft.latest_samples", idempotency_key="k") == "VIEW" + assert catalog.entry_kind(f"{AREA}.reference.countries", idempotency_key="k") == "TABLE" + assert catalog.entry_exists(f"{AREA}.draft.stations", idempotency_key="k") + assert not catalog.entry_exists(f"{AREA}.draft", idempotency_key="k") + with pytest.raises(CatalogOperationError, match="does not exist"): + catalog.entry_kind(f"{AREA}.draft.nope", idempotency_key="k") + + +def test_require_table_or_view() -> None: + catalog, _ = _catalog(_bwd()) + + catalog.require_table_or_view(f"{AREA}.draft.stations", "schema") + with pytest.raises(CatalogOperationError, match="is a folder"): + catalog.require_table_or_view(f"{AREA}.draft", "schema") + with pytest.raises(CatalogOperationError, match="does not exist"): + catalog.require_table_or_view(f"{AREA}.draft.nope", "schema") + + +def test_list_dataset_kinds_walks_every_level_sorted() -> None: + catalog, _ = _catalog(_bwd()) + + assert catalog.list_dataset_kinds(AREA) == [ + (f"{AREA}.draft.latest_samples", "VIEW"), + (f"{AREA}.draft.raw.samples", "TABLE"), + (f"{AREA}.draft.stations", "TABLE"), + (f"{AREA}.reference.countries", "TABLE"), + ] + assert catalog.list_datasets(f"{AREA}.draft.raw") == [f"{AREA}.draft.raw.samples"] + assert catalog.list_datasets(f"{AREA}.versions") == [] + + +def test_list_from_the_root() -> None: + catalog, _ = _catalog(FakePolarisRest().add_table("air.aq.t").add_table("water.w.t")) + assert catalog.list_datasets("eea_lakehouse") == [ + "eea_lakehouse.air.aq.t", + "eea_lakehouse.water.w.t", + ] + + +def test_list_of_a_table_is_that_table() -> None: + catalog, _ = _catalog(_bwd()) + assert catalog.list_dataset_kinds(f"{AREA}.draft.stations") == [ + (f"{AREA}.draft.stations", "TABLE") + ] + with pytest.raises(CatalogOperationError, match="does not exist"): + catalog.list_dataset_kinds(f"{AREA}.nope") + + +def test_close_closes_both_connections() -> None: + catalog, rest = _catalog() + catalog.close() + assert rest.closed + + +# -- through the session, as %catalog uses it --------------------------------------- + + +def test_session_use_list_and_relative_paths() -> None: + catalog, _ = _catalog(_bwd()) + session = CatalogSession(catalog) + + session.use(AREA) + assert session.get_context() == AREA + assert session.list("draft.raw") == [f"{AREA}.draft.raw.samples"] + assert session.list("draft").kinds[f"{AREA}.draft.latest_samples"] == "VIEW" + session.use("eea_lakehouse.water.bathing.bwd.draft") + assert session.list("../reference") == [f"{AREA}.reference.countries"] + session.use(None) + assert session.get_context() == "eea_lakehouse" + + +def test_session_use_of_a_missing_path() -> None: + catalog, _ = _catalog(_bwd()) + with pytest.raises(CatalogSessionError, match="does not exist"): + CatalogSession(catalog).use(f"{AREA}.nope") + + +def test_verbs_not_ported_yet_say_so() -> None: + catalog, _ = _catalog(_bwd()) + session = CatalogSession(catalog) + with pytest.raises(CatalogOperationError, match="not available on the Polaris backend yet"): + session.get_wiki(AREA) + + +def test_magic_builds_a_polaris_session(monkeypatch: pytest.MonkeyPatch) -> None: + from eea_datalakehouse.notebook import magics + + monkeypatch.setenv("EEA_CATALOG_BACKEND", "polaris") + monkeypatch.setenv("POLARIS_URI", "http://polaris.test/api/catalog") + monkeypatch.setenv("POLARIS_CATALOG", "lake") + session: Any = magics._build_catalog_session() # noqa: SLF001 + try: + assert isinstance(session._catalog, PolarisCatalog) # noqa: SLF001 + assert session.get_context() == "lake" + finally: + session._catalog.close() # noqa: SLF001 diff --git a/tests/catalog/test_polaris_rest.py b/tests/catalog/test_polaris_rest.py new file mode 100644 index 0000000..39bd4c4 --- /dev/null +++ b/tests/catalog/test_polaris_rest.py @@ -0,0 +1,467 @@ +from __future__ import annotations + +import json + +import httpx +import pytest +import respx + +from eea_datalakehouse.catalog.errors import CatalogAuthError, CatalogOperationError +from eea_datalakehouse.catalog.polaris_rest import ( + PolarisHttpError, + PolarisNotFoundError, + PolarisRestClient, + ns_param, +) +from eea_datalakehouse.catalog.settings import PolarisSettings + +URI = "http://polaris.test/api/catalog" +V1 = f"{URI}/v1/eea_lakehouse" +GENERIC = f"{URI}/polaris/v1/eea_lakehouse" +SETTINGS = PolarisSettings(uri=URI, client_id="root", client_secret="s3cr3t") + + +def _client( + token: str | None = "user-jwt", settings: PolarisSettings = SETTINGS +) -> PolarisRestClient: + return PolarisRestClient(settings, token_provider=lambda: token) + + +def _config(prefix: str | None = "eea_lakehouse") -> None: + overrides = {"prefix": prefix} if prefix else {} + respx.get(f"{URI}/v1/config").mock( + return_value=httpx.Response(200, json={"defaults": {}, "overrides": overrides}) + ) + + +def test_ns_param_joins_with_unit_separator_and_encodes() -> None: + assert ns_param(["water", "bwd", "draft"]) == "water%1Fbwd%1Fdraft" + + +# -- authentication ------------------------------------------------------------ + + +@respx.mock +def test_user_token_is_sent_as_bearer() -> None: + _config() + route = respx.get(f"{V1}/namespaces").mock( + return_value=httpx.Response(200, json={"namespaces": [["water"], ["air"]]}) + ) + + assert _client().list_namespaces() == [["water"], ["air"]] + assert route.calls[0].request.headers["Authorization"] == "Bearer user-jwt" + + +@respx.mock +def test_without_user_token_mints_client_credentials_once() -> None: + _config() + mint = respx.post(f"{URI}/v1/oauth/tokens").mock( + return_value=httpx.Response(200, json={"access_token": "minted", "expires_in": 3600}) + ) + route = respx.get(f"{V1}/namespaces").mock( + return_value=httpx.Response(200, json={"namespaces": []}) + ) + client = _client(token=None) + + client.list_namespaces() + client.list_namespaces() + + assert mint.call_count == 1 + form = dict(x.split("=") for x in mint.calls[0].request.content.decode().split("&")) + assert form["grant_type"] == "client_credentials" + assert form["client_id"] == "root" + assert form["scope"] == "PRINCIPAL_ROLE%3AALL" + assert route.calls[-1].request.headers["Authorization"] == "Bearer minted" + + +@respx.mock +def test_a_refused_minted_token_is_minted_again_once() -> None: + _config() + respx.post(f"{URI}/v1/oauth/tokens").mock( + side_effect=[ + httpx.Response(200, json={"access_token": "old"}), + httpx.Response(200, json={"access_token": "new"}), + ] + ) + route = respx.get(f"{V1}/namespaces").mock( + side_effect=[httpx.Response(401), httpx.Response(200, json={"namespaces": [["a"]]})] + ) + + assert _client(token=None).list_namespaces() == [["a"]] + assert route.calls[-1].request.headers["Authorization"] == "Bearer new" + + +def test_no_identity_at_all_is_an_auth_error() -> None: + client = _client(token=None, settings=PolarisSettings(uri=URI)) + with pytest.raises(CatalogAuthError, match="KEYCLOAK_ACCESS_TOKEN"): + client.token() + + +@respx.mock +def test_refused_client_credentials_is_an_auth_error() -> None: + respx.post(f"{URI}/v1/oauth/tokens").mock( + return_value=httpx.Response(401, json={"error_description": "bad secret"}) + ) + with pytest.raises(CatalogAuthError, match="bad secret"): + _client(token=None).token() + + +@respx.mock +def test_expired_user_token_says_to_sign_in_again() -> None: + _config() + respx.get(f"{V1}/namespaces").mock( + return_value=httpx.Response(401, json={"error": {"message": "token expired"}}) + ) + with pytest.raises(CatalogAuthError, match="token expired.*sign in to JupyterHub again"): + _client().list_namespaces() + + +@respx.mock +def test_forbidden_is_an_auth_error_with_polaris_message() -> None: + _config() + respx.post(f"{V1}/namespaces").mock( + return_value=httpx.Response( + 403, json={"error": {"message": "Principal 'ana' is not authorized"}} + ) + ) + with pytest.raises(CatalogAuthError, match="not authorized"): + _client().create_namespace(["water"]) + + +# -- prefix -------------------------------------------------------------------- + + +@respx.mock +def test_prefix_comes_from_config_and_is_asked_once() -> None: + config = respx.get(f"{URI}/v1/config").mock( + return_value=httpx.Response(200, json={"overrides": {"prefix": "lake_prefix"}}) + ) + respx.get(f"{URI}/v1/lake_prefix/namespaces").mock( + return_value=httpx.Response(200, json={"namespaces": []}) + ) + client = _client() + + client.list_namespaces() + client.list_namespaces() + + assert config.call_count == 1 + assert config.calls[0].request.url.params["warehouse"] == "eea_lakehouse" + + +@respx.mock +def test_prefix_falls_back_to_the_catalog_name() -> None: + _config(prefix=None) + respx.get(f"{V1}/namespaces").mock(return_value=httpx.Response(200, json={"namespaces": []})) + + assert _client().list_namespaces() == [] + + +# -- namespaces ------------------------------------------------------------------ + + +@respx.mock +def test_list_namespaces_below_a_parent_follows_pages() -> None: + _config() + route = respx.get(f"{V1}/namespaces").mock( + side_effect=[ + httpx.Response(200, json={"namespaces": [["water", "bwd"]], "next-page-token": "p2"}), + httpx.Response(200, json={"namespaces": [["water", "uwwtd"]]}), + ] + ) + + assert _client().list_namespaces(["water"]) == [["water", "bwd"], ["water", "uwwtd"]] + assert route.calls[0].request.url.params["parent"] == "water" + assert route.calls[1].request.url.params["pageToken"] == "p2" + + +@respx.mock +def test_namespace_exists_uses_head() -> None: + _config() + respx.head(f"{V1}/namespaces/water%1Fbwd").mock(return_value=httpx.Response(204)) + respx.head(f"{V1}/namespaces/water%1Fnope").mock(return_value=httpx.Response(404)) + client = _client() + + assert client.namespace_exists(["water", "bwd"]) is True + assert client.namespace_exists(["water", "nope"]) is False + assert client.namespace_exists([]) is False + + +@respx.mock +def test_namespace_exists_does_not_hide_a_refusal() -> None: + _config() + respx.head(f"{V1}/namespaces/water").mock(return_value=httpx.Response(401)) + with pytest.raises(CatalogAuthError): + _client().namespace_exists(["water"]) + + +@respx.mock +def test_create_namespace_reports_whether_it_was_created() -> None: + _config() + route = respx.post(f"{V1}/namespaces").mock( + side_effect=[ + httpx.Response(200, json={"namespace": ["water"], "properties": {}}), + httpx.Response(409, json={"error": {"message": "Namespace already exists"}}), + ] + ) + client = _client() + + assert client.create_namespace(["water"], {"owner": "ana"}) is True + assert client.create_namespace(["water"]) is False + assert json.loads(route.calls[0].request.content) == { + "namespace": ["water"], + "properties": {"owner": "ana"}, + } + + +@respx.mock +def test_namespace_properties_and_their_update() -> None: + _config() + respx.get(f"{V1}/namespaces/water").mock( + return_value=httpx.Response( + 200, json={"namespace": ["water"], "properties": {"wiki": "# Water\n"}} + ) + ) + update = respx.post(f"{V1}/namespaces/water/properties").mock( + return_value=httpx.Response(200, json={"updated": ["tags"], "removed": ["wiki"]}) + ) + client = _client() + + assert client.namespace_properties(["water"]) == {"wiki": "# Water\n"} + client.update_namespace_properties(["water"], {"tags": "public"}, ["wiki"]) + assert json.loads(update.calls[0].request.content) == { + "updates": {"tags": "public"}, + "removals": ["wiki"], + } + + +@respx.mock +def test_missing_namespace_is_not_found() -> None: + _config() + respx.get(f"{V1}/namespaces/nope").mock( + return_value=httpx.Response( + 404, json={"error": {"message": "Namespace does not exist: nope"}} + ) + ) + with pytest.raises(PolarisNotFoundError, match="does not exist"): + _client().namespace_properties(["nope"]) + + +@respx.mock +def test_drop_namespace() -> None: + _config() + route = respx.delete(f"{V1}/namespaces/water%1Fbwd").mock(return_value=httpx.Response(204)) + _client().drop_namespace(["water", "bwd"]) + assert route.called + + +@respx.mock +def test_other_failures_carry_the_status() -> None: + _config() + respx.delete(f"{V1}/namespaces/water").mock( + return_value=httpx.Response(400, json={"error": {"message": "Namespace is not empty"}}) + ) + with pytest.raises(PolarisHttpError, match="not empty") as caught: + _client().drop_namespace(["water"]) + assert caught.value.status == 400 + + +@respx.mock +def test_unreachable_polaris_is_a_clear_error() -> None: + respx.get(f"{URI}/v1/config").mock(side_effect=httpx.ConnectError("refused")) + with pytest.raises(CatalogOperationError, match="can't be reached"): + _client().list_namespaces() + + +# -- tables and views ---------------------------------------------------------------- + + +@respx.mock +def test_list_tables_and_views() -> None: + _config() + respx.get(f"{V1}/namespaces/water%1Fbwd/tables").mock( + return_value=httpx.Response( + 200, json={"identifiers": [{"namespace": ["water", "bwd"], "name": "stations"}]} + ) + ) + respx.get(f"{V1}/namespaces/water%1Fbwd/views").mock( + return_value=httpx.Response( + 200, json={"identifiers": [{"namespace": ["water", "bwd"], "name": "latest"}]} + ) + ) + client = _client() + + assert client.list_tables(["water", "bwd"]) == ["stations"] + assert client.list_views(["water", "bwd"]) == ["latest"] + + +@respx.mock +@pytest.mark.parametrize("status", [400, 404, 501]) +def test_views_not_offered_list_as_empty(status: int) -> None: + _config() + respx.get(f"{V1}/namespaces/water/views").mock(return_value=httpx.Response(status)) + assert _client().list_views(["water"]) == [] + + +@respx.mock +def test_views_refused_is_still_an_auth_error() -> None: + _config() + respx.get(f"{V1}/namespaces/water/views").mock(return_value=httpx.Response(403)) + with pytest.raises(CatalogAuthError): + _client().list_views(["water"]) + + +@respx.mock +def test_table_and_view_exists() -> None: + _config() + respx.head(f"{V1}/namespaces/water/tables/t").mock(return_value=httpx.Response(204)) + respx.head(f"{V1}/namespaces/water/views/t").mock(return_value=httpx.Response(404)) + respx.head(f"{V1}/namespaces/water/views/v").mock(return_value=httpx.Response(501)) + client = _client() + + assert client.table_exists(["water"], "t") is True + assert client.view_exists(["water"], "t") is False + assert client.view_exists(["water"], "v") is False + + +@respx.mock +def test_load_table_and_view_return_the_metadata() -> None: + _config() + respx.get(f"{V1}/namespaces/water/tables/t").mock( + return_value=httpx.Response(200, json={"metadata": {"format-version": 2}}) + ) + respx.get(f"{V1}/namespaces/water/views/v").mock( + return_value=httpx.Response(200, json={"metadata": {"current-version-id": 1}}) + ) + client = _client() + + assert client.load_table(["water"], "t") == {"format-version": 2} + assert client.load_view(["water"], "v") == {"current-version-id": 1} + + +@respx.mock +def test_drop_table_purges_by_default() -> None: + _config() + route = respx.delete(f"{V1}/namespaces/water/tables/t").mock(return_value=httpx.Response(204)) + client = _client() + + client.drop_table(["water"], "t") + client.drop_table(["water"], "t", purge=False) + + assert route.calls[0].request.url.params["purgeRequested"] == "true" + assert "purgeRequested" not in route.calls[1].request.url.params + + +@respx.mock +def test_create_view_registers_sql_and_schema() -> None: + _config() + route = respx.post(f"{V1}/namespaces/water%1Fbwd/views").mock( + return_value=httpx.Response(200, json={"metadata": {}}) + ) + fields = [{"id": 1, "name": "id", "type": "long", "required": False}] + + _client().create_view( + ["water", "bwd"], + "latest", + sql='SELECT * FROM eea_lakehouse."water.bwd.versions.v1"."t"', + fields=fields, + default_namespace=["water", "bwd"], + properties={"tags": "public"}, + ) + + body = json.loads(route.calls[0].request.content) + assert body["name"] == "latest" + assert body["schema"] == {"type": "struct", "schema-id": 0, "fields": fields} + assert body["view-version"]["representations"] == [ + { + "type": "sql", + "sql": 'SELECT * FROM eea_lakehouse."water.bwd.versions.v1"."t"', + "dialect": "duckdb", + } + ] + assert body["view-version"]["default-namespace"] == ["water", "bwd"] + assert body["properties"] == {"tags": "public"} + + +@respx.mock +def test_table_properties_commit() -> None: + _config() + route = respx.post(f"{V1}/namespaces/water/tables/t").mock( + return_value=httpx.Response(200, json={"metadata": {}}) + ) + client = _client() + + client.update_table_properties(["water"], "t", {"wiki": "text"}, ["old"]) + client.update_table_properties(["water"], "t") # nothing to change: no call + + assert route.call_count == 1 + assert json.loads(route.calls[0].request.content) == { + "requirements": [], + "updates": [ + {"action": "set-properties", "updates": {"wiki": "text"}}, + {"action": "remove-properties", "removals": ["old"]}, + ], + } + + +@respx.mock +def test_view_properties_commit() -> None: + _config() + route = respx.post(f"{V1}/namespaces/water/views/v").mock( + return_value=httpx.Response(200, json={"metadata": {}}) + ) + _client().update_view_properties(["water"], "v", removals=["wiki"]) + assert json.loads(route.calls[0].request.content)["updates"] == [ + {"action": "remove-properties", "removals": ["wiki"]} + ] + + +# -- generic tables -------------------------------------------------------------------- + + +@respx.mock +def test_generic_tables_round_trip() -> None: + _config() + respx.get(f"{GENERIC}/namespaces/water/generic-tables").mock( + return_value=httpx.Response( + 200, json={"identifiers": [{"namespace": ["water"], "name": "p"}]} + ) + ) + respx.get(f"{GENERIC}/namespaces/water/generic-tables/p").mock( + return_value=httpx.Response( + 200, + json={"table": {"name": "p", "format": "parquet", "base-location": "s3://b/water/p/"}}, + ) + ) + create = respx.post(f"{GENERIC}/namespaces/water/generic-tables").mock( + return_value=httpx.Response(200, json={"table": {}}) + ) + drop = respx.delete(f"{GENERIC}/namespaces/water/generic-tables/p").mock( + return_value=httpx.Response(204) + ) + client = _client() + + assert client.list_generic(["water"]) == ["p"] + assert client.load_generic(["water"], "p")["base-location"] == "s3://b/water/p/" + client.create_generic( + ["water"], "q", fmt="parquet", base_location="s3://b/water/q/", properties={"a": "b"} + ) + client.drop_generic(["water"], "p") + + assert json.loads(create.calls[0].request.content) == { + "name": "q", + "format": "parquet", + "doc": None, + "properties": {"a": "b"}, + "base-location": "s3://b/water/q/", + } + assert drop.called + + +@respx.mock +@pytest.mark.parametrize("status", [400, 404, 501]) +def test_generic_tables_not_offered_list_as_empty(status: int) -> None: + _config() + respx.get(f"{GENERIC}/namespaces/water/generic-tables").mock( + return_value=httpx.Response(status) + ) + assert _client().list_generic(["water"]) == [] From 498ca8c449cdd04ec35acf09731dabdd418df848 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:31:55 +0100 Subject: [PATCH 05/25] Polaris backend: schema, folders, wiki and tags Third step of the Polaris migration: the metadata verbs of %catalog on Polaris. - schema: an Iceberg table's column types and row count come from its metadata (the current snapshot's total-records; COUNT(*) in DuckDB when it has delete files). A view's row count runs its own stored SQL (DuckDB can't read Iceberg views); a read-only Parquet table is read with read_parquet over its location. - create_folder / ensure_folder_path create namespaces, checking each level before creating it; delete_folder drops an empty namespace, or with cascade=True every view, table (purged), Parquet registration and sub-namespace inside, deepest first. - wiki: the "wiki" property of the namespace, table, view or Parquet table (re-registered, since generic tables can't be updated in place). Folder Meta Data tags are rendered into the text as on Dremio. - tags: kept as the Polaris Navigator does - property "tags" of a namespace, "tags:" on the parent namespace for a table or view - lower case without "#"; "#public" and "public" are the same tag. Folders can be tagged too. - source_sql()/view_sql(): what to SELECT FROM for a table, view or Parquet table, for the data verbs that come next. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/polaris.py | 423 ++++++++++++++++++++--- tests/catalog/polaris_fakes.py | 37 +- tests/catalog/test_polaris_catalog.py | 11 +- tests/catalog/test_polaris_metadata.py | 393 +++++++++++++++++++++ 4 files changed, 810 insertions(+), 54 deletions(-) create mode 100644 tests/catalog/test_polaris_metadata.py diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index b57839a..8b047cf 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -13,17 +13,104 @@ from __future__ import annotations -from collections.abc import Sequence +import re +from collections.abc import Iterable, Sequence from typing import Any, Literal, NoReturn +from . import operations from .backend import Partitions, PublishOutcome -from .duckdb_engine import DuckDbEngine -from .errors import CatalogOperationError +from .duckdb_engine import DuckDbEngine, quote_literal +from .errors import CatalogAuthError, CatalogOperationError from .operations import TableInfo, VersionResult -from .polaris_rest import PARQUET_FORMAT, PolarisRestClient +from .polaris_rest import PARQUET_FORMAT, PolarisHttpError, PolarisRestClient from .settings import PolarisSettings Kind = Literal["TABLE", "VIEW"] +EntryType = Literal["table", "view", "parquet"] +_KINDS: dict[str, Kind] = {"table": "TABLE", "view": "VIEW", "parquet": "TABLE"} +_KIND_NAMES = {"table": "table", "view": "view", "parquet": "read-only Parquet table"} + +# Where a wiki and tags live, as the Polaris Navigator keeps them (see PolarisCatalog). +WIKI_PROPERTY = "wiki" +TAGS_PROPERTY = "tags" +_TAG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$") + + +def normalise_tags(tags: Iterable[str]) -> list[str]: + """Tags as stored: no leading "#", lower case, no repeats, in order. Raises + `CatalogOperationError` for one that isn't letters, digits, "-" and "_" (up to 40).""" + if isinstance(tags, str): + raise CatalogOperationError(f"tags must be a list of tags, e.g. ['{tags}'], not a string") + out: list[str] = [] + for raw in tags: + tag = str(raw).strip().lstrip("#").lower() + if not tag: + continue + if not _TAG_RE.match(tag): + raise CatalogOperationError( + f"tag {raw!r}: use letters, digits, '-' and '_' (up to 40 characters)" + ) + if tag not in out: + out.append(tag) + return out + + +def parse_tags(value: str | None) -> list[str]: + """A stored ``tags`` property value as a list.""" + return [tag for tag in (value or "").split(",") if tag] + + +def _type_name(value: Any) -> str: + """An Iceberg type (a name, or a struct/list/map object) as text.""" + if isinstance(value, str): + return value + kind = value.get("type") if isinstance(value, dict) else None + if kind == "list": + return f"list<{_type_name(value['element'])}>" + if kind == "map": + return f"map<{_type_name(value['key'])}, {_type_name(value['value'])}>" + if kind == "struct": + fields = ", ".join(f"{f['name']}: {_type_name(f['type'])}" for f in value.get("fields", [])) + return f"struct<{fields}>" + return str(kind or value) + + +def _column_types(schema: dict[str, Any]) -> dict[str, str]: + return {str(f["name"]): _type_name(f["type"]) for f in schema.get("fields") or []} + + +def _current_table_schema(metadata: dict[str, Any]) -> dict[str, Any]: + current = metadata.get("current-schema-id", 0) + schemas = metadata.get("schemas") or [] + return next( + (s for s in schemas if s.get("schema-id") == current), schemas[0] if schemas else {} + ) + + +def _current_view_version(metadata: dict[str, Any]) -> dict[str, Any]: + current = metadata.get("current-version-id") + versions = metadata.get("versions") or [] + return next( + (v for v in versions if v.get("version-id") == current), versions[-1] if versions else {} + ) + + +def _snapshot_rows(metadata: dict[str, Any]) -> int | None: + """The table's row count from its current snapshot's summary — None when + that can't be trusted (delete files) or isn't there.""" + current = metadata.get("current-snapshot-id") + if current in (None, -1): + return 0 + snapshot = next( + (s for s in metadata.get("snapshots") or [] if s.get("snapshot-id") == current), None + ) + summary = (snapshot or {}).get("summary") or {} + deletes = int(summary.get("total-position-deletes", 0) or 0) + int( + summary.get("total-equality-deletes", 0) or 0 + ) + if deletes or "total-records" not in summary: + return None + return int(summary["total-records"]) class PolarisCatalog: @@ -87,20 +174,27 @@ def _split(self, path: str) -> tuple[list[str], str]: # -- what is where ------------------------------------------------------------ - def _kind_of(self, path: str) -> Kind | None: - """``"TABLE"``/``"VIEW"`` for a table or view at `path`, None if there is none.""" - parts = self.parts(path) - if len(parts) < 2: + def _entry_type(self, namespace: Sequence[str], name: str) -> EntryType | None: + """What `name` in `namespace` is: an Iceberg "table", a "view", a read-only + "parquet" table, or None when it is none of them (or the namespace is missing).""" + if not namespace: return None - namespace, name = parts[:-1], parts[-1] if self.rest.table_exists(namespace, name): - return "TABLE" + return "table" if self.rest.view_exists(namespace, name): - return "VIEW" + return "view" if self.rest.namespace_exists(namespace) and name in self._parquet_tables(namespace): - return "TABLE" + return "parquet" return None + def _kind_of(self, path: str) -> Kind | None: + """``"TABLE"``/``"VIEW"`` for a table or view at `path`, None if there is none.""" + parts = self.parts(path) + if len(parts) < 2: + return None + entry = self._entry_type(parts[:-1], parts[-1]) + return None if entry is None else _KINDS[entry] + def _parquet_tables(self, namespace: Sequence[str]) -> list[str]: """The read-only Parquet tables (generic tables of format parquet) in `namespace`.""" names = [] @@ -164,27 +258,289 @@ def list_dataset_kinds(self, path: str) -> list[tuple[str, str]]: def list_datasets(self, path: str) -> list[str]: return [entry for entry, _ in self.list_dataset_kinds(path)] - # -- not on Polaris yet (next steps of the migration) ---------------------------- + # -- reading a table or view -------------------------------------------------- + + def source_sql(self, path: str) -> str: + """What to ``SELECT … FROM`` to read the table or view at `path` in DuckDB: + the table's name, a view's own SQL in parentheses (DuckDB can't read an + Iceberg view), or ``read_parquet(…)`` over a read-only Parquet table's files.""" + namespace, name = self._split(path) + kind = self._entry_type(namespace, name) + if kind == "table": + return self.engine.table_ref(namespace, name) + if kind == "view": + return f"({self.view_sql(path)})" + if kind == "parquet": + location = str(self.rest.load_generic(namespace, name).get("base-location") or "") + if not location: + raise CatalogOperationError(f"{path!r} has no storage location") + files = f"{location.rstrip('/')}/**/*.parquet" + return f"read_parquet({quote_literal(files)}, union_by_name = true)" + raise CatalogOperationError(f"{path!r} does not exist") - def _not_yet(self, verb: str) -> NoReturn: - raise CatalogOperationError( - f"{verb} is not available on the Polaris backend yet — set " - "EEA_CATALOG_BACKEND=dremio to run it on Dremio" + def view_sql(self, path: str) -> str: + """The SQL of the view at `path` — its DuckDB version when it has one.""" + namespace, name = self._split(path) + metadata = self.rest.load_view(namespace, name) + version = _current_view_version(metadata) + sql = [r for r in version.get("representations") or [] if r.get("type") == "sql"] + if not sql: + raise CatalogOperationError(f"view {path!r} has no SQL") + preferred = next((r for r in sql if r.get("dialect") == "duckdb"), sql[0]) + return str(preferred["sql"]) + + def _count(self, path: str) -> int: + rows = self.engine.fetch_all( + f'SELECT COUNT(*) AS "row_count" FROM {self.source_sql(path)} AS "source"' ) + return int(rows[0]["row_count"]) if rows else 0 def gettableitemsfrom(self, table_path: str, *, idempotency_key: str) -> TableInfo: - self._not_yet("schema") + """Column types and row count of a table or view. An Iceberg table's + come from its metadata (the snapshot's ``total-records``, unless it has + delete files); a view's and a Parquet table's row count is a ``COUNT(*)``.""" + namespace, name = self._split(table_path) + kind = self._entry_type(namespace, name) + if kind == "table": + metadata = self.rest.load_table(namespace, name) + schema = _column_types(_current_table_schema(metadata)) + rows = _snapshot_rows(metadata) + return TableInfo( + schema=schema, row_count=self._count(table_path) if rows is None else rows + ) + if kind == "view": + metadata = self.rest.load_view(namespace, name) + version = _current_view_version(metadata) + schema_id = version.get("schema-id") + view_schema: dict[str, Any] = next( + (s for s in metadata.get("schemas") or [] if s.get("schema-id") == schema_id), {} + ) + return TableInfo(schema=_column_types(view_schema), row_count=self._count(table_path)) + if kind == "parquet": + described = self.engine.fetch_all( + f"DESCRIBE SELECT * FROM {self.source_sql(table_path)}" + ) + schema = {str(r["column_name"]): str(r["column_type"]) for r in described} + return TableInfo(schema=schema, row_count=self._count(table_path)) + raise CatalogOperationError(f"{table_path!r} does not exist") + + # -- folders (namespaces) ------------------------------------------------------ def ensure_folder_path(self, folder: str) -> list[str]: - self._not_yet("creating folders") + """Create every missing namespace level of `folder`; the levels created, top + first. Existing levels are only checked, never re-created (creating needs a + grant on the parent that reading doesn't).""" + parts = self.parts(folder) + if not parts: + return [] + kind = self._entry_type(parts[:-1], parts[-1]) if len(parts) > 1 else None + if kind is not None: + raise CatalogOperationError(f"{folder!r} is a {_KIND_NAMES[kind]}, not a folder") + created: list[str] = [] + for depth in range(1, len(parts) + 1): + namespace = parts[:depth] + if not self.rest.namespace_exists(namespace) and self.rest.create_namespace(namespace): + created.append(self.path_of(namespace)) + return created def createfolder( self, path: str, *, create_parents: bool = False, idempotency_key: str ) -> None: - self._not_yet("create_folder") + """Create the namespace `path`; one that already exists is left alone. + Without `create_parents`, its parent must exist.""" + parts = self.parts(path) + if not parts or self.rest.namespace_exists(parts): + return + if create_parents: + self.ensure_folder_path(path) + return + parent = parts[:-1] + if parent and not self.rest.namespace_exists(parent): + raise CatalogOperationError( + f"parent {self.path_of(parent)!r} does not exist — pass create_parents=True " + "to create missing levels automatically" + ) + kind = self._entry_type(parent, parts[-1]) if parent else None + if kind is not None: + raise CatalogOperationError(f"{path!r} is a {_KIND_NAMES[kind]}, not a folder") + self.rest.create_namespace(parts) def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str) -> None: - self._not_yet("delete_folder") + """Delete the namespace `path`; one that is already gone is not an error. + Without `cascade` it must be empty. With it, every table (its data files + too), view, read-only Parquet table (the catalog entry — its files stay in + the bucket) and sub-namespace inside goes first, deepest first.""" + parts = self.parts(path) + if not parts: + raise CatalogOperationError(f"{path!r} is the catalog itself and can't be deleted") + if not self.rest.namespace_exists(parts): + return + if not cascade: + try: + self.rest.drop_namespace(parts) + except PolarisHttpError as exc: + if exc.status in (400, 409): + raise CatalogOperationError( + f"{path!r} is not empty — pass cascade=True to delete everything in it" + ) from exc + raise + return + order: list[list[str]] = [] + pending = [parts] + while pending: + namespace = pending.pop() + order.append(namespace) + pending.extend(self.rest.list_namespaces(namespace)) + for namespace in sorted(order, key=len, reverse=True): + for name in self.rest.list_views(namespace): + self.rest.drop_view(namespace, name) + for name in self.rest.list_tables(namespace): + self.rest.drop_table(namespace, name) + for name in self.rest.list_generic(namespace): + self.rest.drop_generic(namespace, name) + self.rest.drop_namespace(namespace) + + # -- wiki ------------------------------------------------------------------------ + + def _properties(self, path: str) -> tuple[str, dict[str, str]]: + """``(kind, properties)`` of whatever is at `path`; kind is "namespace", + "table", "view" or "parquet".""" + parts = self.parts(path) + if not parts: + raise CatalogOperationError(f"{path!r} is the catalog itself — it has no properties") + if self.rest.namespace_exists(parts): + return "namespace", self.rest.namespace_properties(parts) + namespace, name = parts[:-1], parts[-1] + kind = self._entry_type(namespace, name) if namespace else None + if kind == "table": + return kind, dict(self.rest.load_table(namespace, name).get("properties") or {}) + if kind == "view": + return kind, dict(self.rest.load_view(namespace, name).get("properties") or {}) + if kind == "parquet": + return kind, dict(self.rest.load_generic(namespace, name).get("properties") or {}) + raise CatalogOperationError(f"{path!r} does not exist") + + def _set_property(self, path: str, kind: str, key: str, value: str | None) -> None: + """Set (or, with None, remove) one property of whatever is at `path`.""" + parts = self.parts(path) + updates = {key: value} if value is not None else {} + removals = [] if value is not None else [key] + if kind == "namespace": + self.rest.update_namespace_properties(parts, updates, removals) + return + namespace, name = parts[:-1], parts[-1] + if kind == "table": + self.rest.update_table_properties(namespace, name, updates, removals) + elif kind == "view": + self.rest.update_view_properties(namespace, name, updates, removals) + else: # a generic table can't be updated in place: register it again + entry = self.rest.load_generic(namespace, name) + properties = dict(entry.get("properties") or {}) + properties.update(updates) + for removed in removals: + properties.pop(removed, None) + self.rest.drop_generic(namespace, name) + try: + self._register_generic(namespace, name, entry, properties) + except Exception: + self._register_generic(namespace, name, entry, entry.get("properties") or {}) + raise + + def _register_generic( + self, namespace: list[str], name: str, entry: dict[str, Any], properties: dict[str, str] + ) -> None: + self.rest.create_generic( + namespace, + name, + fmt=str(entry.get("format") or PARQUET_FORMAT), + base_location=entry.get("base-location"), + doc=entry.get("doc"), + properties=properties, + ) + + def getwikifrom(self, path: str, *, idempotency_key: str) -> str: + """The wiki text (property ``wiki``) of a folder, table or view; raises if + `path` doesn't exist or has no wiki.""" + _, properties = self._properties(path) + text = properties.get(WIKI_PROPERTY) + if not text: + raise CatalogOperationError(f"{path!r} has no wiki") + return text + + def setwikito( + self, + path: str, + text: str, + *, + tags: list[dict[str, str]] | None = None, + idempotency_key: str, + ) -> None: + """Set the wiki text. On a folder, `tags` is rendered into a "# Meta Data" + section exactly as on Dremio; on a table or view it is ignored (use + `settagsto`).""" + kind, _ = self._properties(path) + if tags and kind == "namespace": + operations._validate_tags(tags) # noqa: SLF001 — same-package internal + text = f"{text}\n\n{operations._render_wiki_metadata(tags)}" # noqa: SLF001 + self._set_property(path, kind, WIKI_PROPERTY, text if text else None) + + def deletewiki(self, path: str, *, idempotency_key: str) -> None: + """Remove the wiki; a missing `path`, or one without a wiki, is a no-op.""" + try: + kind, properties = self._properties(path) + except CatalogAuthError: + raise + except CatalogOperationError: + return + if WIKI_PROPERTY in properties: + self._set_property(path, kind, WIKI_PROPERTY, None) + + # -- tags ------------------------------------------------------------------------ + # As the Polaris Navigator keeps them: a folder's tags are its namespace's + # property "tags"; a table's or view's are the property "tags:" of the + # namespace holding it. Comma-separated, lower case, without the "#". + + def _tag_location(self, path: str, verb: str) -> tuple[list[str], str]: + """``(namespace holding the tags, property name)`` for `path`.""" + parts = self.parts(path) + if not parts: + raise CatalogOperationError(f"{verb}: the catalog itself has no tags") + if self.rest.namespace_exists(parts): + return parts, TAGS_PROPERTY + namespace, name = parts[:-1], parts[-1] + if not namespace or self._entry_type(namespace, name) is None: + raise CatalogOperationError(f"{path!r} does not exist") + return namespace, f"{TAGS_PROPERTY}:{name}" + + def gettagsfrom(self, path: str, *, idempotency_key: str) -> list[str]: + """The tags of a folder, table or view, lower case and without "#".""" + namespace, key = self._tag_location(path, "gettagsfrom") + return parse_tags(self.rest.namespace_properties(namespace).get(key)) + + def settagsto(self, path: str, tags: list[str], *, idempotency_key: str) -> None: + """Replace the tags (a leading "#" is dropped, letters made lower case).""" + namespace, key = self._tag_location(path, "settagsto") + normalised = normalise_tags(tags) + if normalised: + self.rest.update_namespace_properties(namespace, {key: ",".join(normalised)}) + else: + self.rest.update_namespace_properties(namespace, removals=[key]) + + def deletetags(self, path: str, tags: list[str], *, idempotency_key: str) -> None: + """Remove `tags` (spelled with or without "#"), keeping the others.""" + drop = set(normalise_tags(tags)) + current = self.gettagsfrom(path, idempotency_key=idempotency_key) + remaining = [tag for tag in current if tag not in drop] + if remaining != current: + self.settagsto(path, remaining, idempotency_key=idempotency_key) + + # -- not on Polaris yet (next steps of the migration) ---------------------------- + + def _not_yet(self, verb: str) -> NoReturn: + raise CatalogOperationError( + f"{verb} is not available on the Polaris backend yet — set " + "EEA_CATALOG_BACKEND=dremio to run it on Dremio" + ) def datacopy( self, @@ -243,31 +599,6 @@ def deletetable(self, table_path: str, *, idempotency_key: str) -> Any: def drop_entry(self, path: str, *, idempotency_key: str) -> None: self._not_yet("dropping a table or view") - def getwikifrom(self, path: str, *, idempotency_key: str) -> str: - self._not_yet("get_wiki") - - def setwikito( - self, - path: str, - text: str, - *, - tags: list[dict[str, str]] | None = None, - idempotency_key: str, - ) -> None: - self._not_yet("set_wiki") - - def deletewiki(self, path: str, *, idempotency_key: str) -> None: - self._not_yet("delete_wiki") - - def gettagsfrom(self, path: str, *, idempotency_key: str) -> list[str]: - self._not_yet("get_tags") - - def settagsto(self, path: str, tags: list[str], *, idempotency_key: str) -> None: - self._not_yet("set_tags") - - def deletetags(self, path: str, tags: list[str], *, idempotency_key: str) -> None: - self._not_yet("delete_tags") - def publish_target(self, area: str) -> str: return f"the public data store ({area})" diff --git a/tests/catalog/polaris_fakes.py b/tests/catalog/polaris_fakes.py index c55688b..046137e 100644 --- a/tests/catalog/polaris_fakes.py +++ b/tests/catalog/polaris_fakes.py @@ -23,6 +23,23 @@ class FakeEntry: metadata: dict[str, Any] = field(default_factory=dict) +def view_metadata( + sql: str, fields: Sequence[Mapping[str, Any]] = (), dialect: str = "duckdb" +) -> dict[str, Any]: + """Iceberg view metadata with one version holding `sql`.""" + return { + "current-version-id": 1, + "versions": [ + { + "version-id": 1, + "schema-id": 0, + "representations": [{"type": "sql", "sql": sql, "dialect": dialect}], + } + ], + "schemas": [{"schema-id": 0, "type": "struct", "fields": [dict(f) for f in fields]}], + } + + class FakePolarisRest: def __init__(self, catalog: str = "eea_lakehouse") -> None: self.catalog = catalog @@ -41,16 +58,26 @@ def add_namespace(self, *parts: str, **properties: str) -> FakePolarisRest: self.namespaces[tuple(parts)].update(properties) return self - def add_table(self, dotted: str, **properties: str) -> FakePolarisRest: + def add_table( + self, dotted: str, metadata: dict[str, Any] | None = None, **properties: str + ) -> FakePolarisRest: *namespace, name = dotted.split(".") self.add_namespace(*namespace) - self.tables[(tuple(namespace), name)] = FakeEntry(dict(properties)) + self.tables[(tuple(namespace), name)] = FakeEntry(dict(properties), dict(metadata or {})) return self - def add_view(self, dotted: str, sql: str = "SELECT 1", **properties: str) -> FakePolarisRest: + def add_view( + self, + dotted: str, + sql: str = "SELECT 1", + fields: Sequence[Mapping[str, Any]] = (), + **properties: str, + ) -> FakePolarisRest: *namespace, name = dotted.split(".") self.add_namespace(*namespace) - self.views[(tuple(namespace), name)] = FakeEntry(dict(properties), {"sql": sql}) + self.views[(tuple(namespace), name)] = FakeEntry( + dict(properties), view_metadata(sql, fields) + ) return self def add_parquet(self, dotted: str, location: str = "s3://b/x/") -> FakePolarisRest: @@ -180,7 +207,7 @@ def create_view( if (key, name) in self.views or (key, name) in self.tables: raise PolarisHttpError(f"{name} already exists", status=409) self.views[(key, name)] = FakeEntry( - dict(properties or {}), {"sql": sql, "fields": [dict(f) for f in fields]} + dict(properties or {}), view_metadata(sql, fields, dialect) ) def update_table_properties( diff --git a/tests/catalog/test_polaris_catalog.py b/tests/catalog/test_polaris_catalog.py index fb469d9..ce58dc7 100644 --- a/tests/catalog/test_polaris_catalog.py +++ b/tests/catalog/test_polaris_catalog.py @@ -8,7 +8,11 @@ from eea_datalakehouse.catalog.errors import CatalogOperationError from eea_datalakehouse.catalog.polaris import PolarisCatalog from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient -from eea_datalakehouse.catalog.session import CatalogSession, CatalogSessionError +from eea_datalakehouse.catalog.session import ( + CatalogCommitError, + CatalogSession, + CatalogSessionError, +) from eea_datalakehouse.catalog.settings import PolarisSettings from .polaris_fakes import FakePolarisRest @@ -156,8 +160,9 @@ def test_session_use_of_a_missing_path() -> None: def test_verbs_not_ported_yet_say_so() -> None: catalog, _ = _catalog(_bwd()) session = CatalogSession(catalog) - with pytest.raises(CatalogOperationError, match="not available on the Polaris backend yet"): - session.get_wiki(AREA) + session.data_copy(f"{AREA}.draft.stations", f"{AREA}.draft.copy") + with pytest.raises(CatalogCommitError, match="not available on the Polaris backend yet"): + session.commit() def test_magic_builds_a_polaris_session(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/catalog/test_polaris_metadata.py b/tests/catalog/test_polaris_metadata.py new file mode 100644 index 0000000..827f80e --- /dev/null +++ b/tests/catalog/test_polaris_metadata.py @@ -0,0 +1,393 @@ +"""Step 3 of the Polaris backend: schema, folders, wiki and tags.""" + +from __future__ import annotations + +from typing import Any, cast + +import pytest + +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogOperationError +from eea_datalakehouse.catalog.polaris import PolarisCatalog, normalise_tags, parse_tags +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.session import ( + CatalogCommitError, + CatalogSession, + CatalogSessionError, +) +from eea_datalakehouse.catalog.settings import PolarisSettings + +from .polaris_fakes import FakePolarisRest + +SETTINGS = PolarisSettings(uri="http://polaris.test/api/catalog") +AREA = "eea_lakehouse.water.bathing.bwd" +K = "key" + + +class FakeEngine(DuckDbEngine): + """Records SQL; `fetch_all` answers a COUNT with `count` and a DESCRIBE with `columns`.""" + + def __init__(self, count: int = 7, columns: list[dict[str, Any]] | None = None) -> None: + super().__init__(SETTINGS, connect=lambda: None, token_provider=lambda: "t") + self.sql: list[str] = [] + self.count = count + self.columns = columns or [] + + def fetch_all(self, sql: str) -> list[dict[str, Any]]: + self.sql.append(sql) + if sql.startswith("DESCRIBE"): + return self.columns + return [{"row_count": self.count}] + + def execute(self, sql: str) -> None: + self.sql.append(sql) + + +def _catalog(rest: FakePolarisRest, engine: FakeEngine | None = None) -> PolarisCatalog: + return PolarisCatalog( + SETTINGS, rest=cast(PolarisRestClient, rest), engine=engine or FakeEngine() + ) + + +def _table_metadata(summary: dict[str, str] | None, snapshot: bool = True) -> dict[str, Any]: + metadata: dict[str, Any] = { + "current-schema-id": 1, + "schemas": [ + {"schema-id": 0, "fields": [{"id": 1, "name": "old", "type": "int"}]}, + { + "schema-id": 1, + "fields": [ + {"id": 1, "name": "id", "type": "long"}, + {"id": 2, "name": "site", "type": "string"}, + {"id": 3, "name": "tags", "type": {"type": "list", "element": "string"}}, + ], + }, + ], + "current-snapshot-id": 5 if snapshot else -1, + "snapshots": [{"snapshot-id": 5, "summary": summary or {}}] if snapshot else [], + } + return metadata + + +def _bwd() -> FakePolarisRest: + return ( + FakePolarisRest() + .add_table("water.bathing.bwd.draft.stations", _table_metadata({"total-records": "42"})) + .add_view( + "water.bathing.bwd.draft.latest", + sql='SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations"', + fields=[{"id": 1, "name": "id", "type": "long"}], + ) + .add_parquet("water.bathing.bwd.reference.countries", "s3://lake/water/bwd/countries/") + .add_namespace("water", "bathing", "bwd", "versions") + ) + + +# -- tags helpers ---------------------------------------------------------------------- + + +def test_normalise_tags() -> None: + assert normalise_tags(["#Public", "public", " reviewed ", "", "#"]) == ["public", "reviewed"] + with pytest.raises(CatalogOperationError, match="letters, digits"): + normalise_tags(["two words"]) + with pytest.raises(CatalogOperationError, match="not a string"): + normalise_tags("public") # type: ignore[arg-type] + + +def test_parse_tags() -> None: + assert parse_tags(None) == [] + assert parse_tags("a,b") == ["a", "b"] + + +# -- schema -------------------------------------------------------------------------------- + + +def test_schema_of_a_table_comes_from_its_metadata() -> None: + engine = FakeEngine() + info = _catalog(_bwd(), engine).gettableitemsfrom(f"{AREA}.draft.stations", idempotency_key=K) + + assert info.schema == {"id": "long", "site": "string", "tags": "list"} + assert info.row_count == 42 + assert engine.sql == [] # no query needed + + +def test_schema_of_a_table_with_delete_files_counts_rows() -> None: + rest = FakePolarisRest().add_table( + "water.t", _table_metadata({"total-records": "42", "total-position-deletes": "3"}) + ) + engine = FakeEngine(count=39) + info = _catalog(rest, engine).gettableitemsfrom("eea_lakehouse.water.t", idempotency_key=K) + + assert info.row_count == 39 + assert engine.sql == [ + 'SELECT COUNT(*) AS "row_count" FROM "eea_lakehouse"."water"."t" AS "source"' + ] + + +def test_schema_of_an_empty_table() -> None: + rest = FakePolarisRest().add_table("water.t", _table_metadata(None, snapshot=False)) + assert ( + _catalog(rest).gettableitemsfrom("eea_lakehouse.water.t", idempotency_key=K).row_count == 0 + ) + + +def test_schema_of_a_view_runs_its_sql() -> None: + engine = FakeEngine(count=3) + info = _catalog(_bwd(), engine).gettableitemsfrom(f"{AREA}.draft.latest", idempotency_key=K) + + assert info.schema == {"id": "long"} + assert info.row_count == 3 + assert engine.sql == [ + 'SELECT COUNT(*) AS "row_count" FROM ' + '(SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations") AS "source"' + ] + + +def test_schema_of_a_parquet_table_reads_its_files() -> None: + engine = FakeEngine(count=27, columns=[{"column_name": "code", "column_type": "VARCHAR"}]) + info = _catalog(_bwd(), engine).gettableitemsfrom( + f"{AREA}.reference.countries", idempotency_key=K + ) + + assert info.schema == {"code": "VARCHAR"} + assert info.row_count == 27 + assert engine.sql[0] == ( + "DESCRIBE SELECT * FROM " + "read_parquet('s3://lake/water/bwd/countries/**/*.parquet', union_by_name = true)" + ) + + +def test_schema_through_the_session() -> None: + session = CatalogSession(_catalog(_bwd())) + session.use(AREA) + + assert session.schema("draft.stations").row_count == 42 + with pytest.raises(CatalogOperationError, match="is a folder"): + session.schema("draft") + with pytest.raises(CatalogOperationError, match="does not exist"): + session.schema("draft.nope") + + +def test_view_sql_prefers_the_duckdb_dialect() -> None: + rest = FakePolarisRest().add_view("water.v") + rest.views[(("water",), "v")].metadata["versions"][0]["representations"] = [ + {"type": "sql", "sql": "SELECT 'trino'", "dialect": "trino"}, + {"type": "sql", "sql": "SELECT 'duckdb'", "dialect": "duckdb"}, + ] + assert _catalog(rest).view_sql("eea_lakehouse.water.v") == "SELECT 'duckdb'" + + +# -- folders ----------------------------------------------------------------------------------- + + +def test_ensure_folder_path_creates_only_missing_levels() -> None: + rest = FakePolarisRest().add_namespace("water") + catalog = _catalog(rest) + + assert catalog.ensure_folder_path("eea_lakehouse.water.bwd.draft") == [ + "eea_lakehouse.water.bwd", + "eea_lakehouse.water.bwd.draft", + ] + assert catalog.ensure_folder_path("eea_lakehouse.water.bwd.draft") == [] + assert ("create_namespace", ("water",)) not in rest.calls + + +def test_ensure_folder_path_refuses_a_table() -> None: + with pytest.raises(CatalogOperationError, match="is a table, not a folder"): + _catalog(_bwd()).ensure_folder_path(f"{AREA}.draft.stations") + + +def test_createfolder() -> None: + rest = _bwd() + catalog = _catalog(rest) + + catalog.createfolder(f"{AREA}.archive", idempotency_key=K) + assert rest.namespace_exists(["water", "bathing", "bwd", "archive"]) + catalog.createfolder(f"{AREA}.archive", idempotency_key=K) # already there: fine + with pytest.raises(CatalogOperationError, match="create_parents=True"): + catalog.createfolder(f"{AREA}.x.y", idempotency_key=K) + catalog.createfolder(f"{AREA}.x.y", create_parents=True, idempotency_key=K) + assert rest.namespace_exists(["water", "bathing", "bwd", "x", "y"]) + with pytest.raises(CatalogOperationError, match="is a table, not a folder"): + catalog.createfolder(f"{AREA}.draft.stations", idempotency_key=K) + + +def test_deletefolder() -> None: + rest = _bwd() + catalog = _catalog(rest) + + catalog.deletefolder(f"{AREA}.versions", idempotency_key=K) + assert not rest.namespace_exists(["water", "bathing", "bwd", "versions"]) + catalog.deletefolder(f"{AREA}.versions", idempotency_key=K) # already gone: fine + with pytest.raises(CatalogOperationError, match="not empty — pass cascade=True"): + catalog.deletefolder(f"{AREA}.draft", idempotency_key=K) + with pytest.raises(CatalogOperationError, match="can't be deleted"): + catalog.deletefolder("eea_lakehouse", idempotency_key=K) + + +def test_deletefolder_cascade_removes_everything_inside() -> None: + rest = _bwd().add_table("water.bathing.bwd.draft.raw.samples") + _catalog(rest).deletefolder(AREA, cascade=True, idempotency_key=K) + + assert not any(key[:3] == ("water", "bathing", "bwd") for key in rest.namespaces) + assert not rest.tables and not rest.views and not rest.generic + assert rest.namespace_exists(["water", "bathing"]) + + +# -- wiki ------------------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + "path", + [AREA, f"{AREA}.draft.stations", f"{AREA}.draft.latest", f"{AREA}.reference.countries"], +) +def test_wiki_round_trip(path: str) -> None: + catalog = _catalog(_bwd()) + + with pytest.raises(CatalogOperationError, match="has no wiki"): + catalog.getwikifrom(path, idempotency_key=K) + catalog.setwikito(path, "# Bathing water\n", idempotency_key=K) + assert catalog.getwikifrom(path, idempotency_key=K) == "# Bathing water\n" + catalog.deletewiki(path, idempotency_key=K) + with pytest.raises(CatalogOperationError, match="has no wiki"): + catalog.getwikifrom(path, idempotency_key=K) + + +def test_wiki_of_a_parquet_table_keeps_its_registration() -> None: + rest = _bwd() + _catalog(rest).setwikito(f"{AREA}.reference.countries", "text", idempotency_key=K) + + entry = rest.generic[(("water", "bathing", "bwd", "reference"), "countries")] + assert entry["base-location"] == "s3://lake/water/bwd/countries/" + assert entry["format"] == "parquet" + assert entry["properties"] == {"wiki": "text"} + + +def test_folder_wiki_carries_meta_data_tags_like_dremio() -> None: + rest = _bwd() + meta = [{"tag_name": "owner", "tag_value": "EEA", "tag_title": "Owner"}] + _catalog(rest).setwikito(AREA, "About", tags=meta, idempotency_key=K) + + assert rest.namespaces[("water", "bathing", "bwd")]["wiki"] == ( + 'About\n\n# Meta Data\n\tOwner : EEA\n\n\n' + ) + + +def test_meta_data_tags_are_ignored_on_a_table() -> None: + rest = _bwd() + meta = [{"tag_name": "owner", "tag_value": "EEA", "tag_title": "Owner"}] + _catalog(rest).setwikito(f"{AREA}.draft.stations", "About", tags=meta, idempotency_key=K) + + assert rest.tables[(("water", "bathing", "bwd", "draft"), "stations")].properties == { + "wiki": "About" + } + + +def test_wiki_of_missing_paths() -> None: + catalog = _catalog(_bwd()) + with pytest.raises(CatalogOperationError, match="does not exist"): + catalog.getwikifrom(f"{AREA}.nope", idempotency_key=K) + with pytest.raises(CatalogOperationError, match="does not exist"): + catalog.setwikito(f"{AREA}.nope", "x", idempotency_key=K) + catalog.deletewiki(f"{AREA}.nope", idempotency_key=K) # no-op, like Dremio + + +# -- tags ------------------------------------------------------------------------------------ + + +def test_table_tags_live_on_the_parent_namespace() -> None: + rest = _bwd() + catalog = _catalog(rest) + path = f"{AREA}.draft.stations" + + assert catalog.gettagsfrom(path, idempotency_key=K) == [] + catalog.settagsto(path, ["#Public", "reviewed"], idempotency_key=K) + + assert rest.namespaces[("water", "bathing", "bwd", "draft")]["tags:stations"] == ( + "public,reviewed" + ) + assert catalog.gettagsfrom(path, idempotency_key=K) == ["public", "reviewed"] + catalog.deletetags(path, ["#public"], idempotency_key=K) + assert catalog.gettagsfrom(path, idempotency_key=K) == ["reviewed"] + catalog.settagsto(path, [], idempotency_key=K) + assert "tags:stations" not in rest.namespaces[("water", "bathing", "bwd", "draft")] + + +def test_folder_tags_are_the_namespace_property() -> None: + rest = _bwd() + _catalog(rest).settagsto(AREA, ["water"], idempotency_key=K) + assert rest.namespaces[("water", "bathing", "bwd")]["tags"] == "water" + + +def test_view_and_parquet_tags() -> None: + rest = _bwd() + catalog = _catalog(rest) + catalog.settagsto(f"{AREA}.draft.latest", ["public"], idempotency_key=K) + catalog.settagsto(f"{AREA}.reference.countries", ["ref"], idempotency_key=K) + + assert rest.namespaces[("water", "bathing", "bwd", "draft")]["tags:latest"] == "public" + assert rest.namespaces[("water", "bathing", "bwd", "reference")]["tags:countries"] == "ref" + + +def test_tags_of_missing_paths_and_the_root() -> None: + catalog = _catalog(_bwd()) + with pytest.raises(CatalogOperationError, match="does not exist"): + catalog.gettagsfrom(f"{AREA}.nope", idempotency_key=K) + with pytest.raises(CatalogOperationError, match="catalog itself has no tags"): + catalog.settagsto("eea_lakehouse", ["x"], idempotency_key=K) + + +# -- through the session: queue, commit, roll back ------------------------------------ + + +def test_session_metadata_verbs_commit() -> None: + rest = _bwd() + session = CatalogSession(_catalog(rest)) + session.use(AREA) + + session.create_folder("archive").set_wiki("archive", "Old data").set_tags( + "draft.stations", ["#reviewed"] + ).commit() + + assert rest.namespaces[("water", "bathing", "bwd", "archive")] == {"wiki": "Old data"} + assert session.get_tags("draft.stations") == ["reviewed"] + assert session.get_wiki("archive") == "Old data" + + +def test_session_rolls_back_metadata_verbs_on_failure() -> None: + rest = _bwd() + rest.namespaces[("water", "bathing", "bwd", "draft")]["tags:stations"] = "old" + session = CatalogSession(_catalog(rest)) + session.use(AREA) + + session.create_folder("archive") + session.set_tags("draft.stations", ["new"]) + session.set_wiki("draft.stations", "text") + session.delete_folder("draft") # not empty, no cascade: fails + with pytest.raises(CatalogCommitError) as caught: + session.commit() + + assert caught.value.rolled_back + assert not rest.namespace_exists(["water", "bathing", "bwd", "archive"]) + assert rest.namespaces[("water", "bathing", "bwd", "draft")]["tags:stations"] == "old" + assert "wiki" not in rest.tables[(("water", "bathing", "bwd", "draft"), "stations")].properties + + +def test_session_delete_folder_cascade() -> None: + rest = _bwd() + session = CatalogSession(_catalog(rest)) + session.use(AREA) + + report = session.delete_folder("draft", cascade=True).commit() + + assert report.succeeded == [f"delete folder '{AREA}.draft'"] + assert not rest.namespace_exists(["water", "bathing", "bwd", "draft"]) + + +def test_session_use_of_a_table_path_is_allowed_like_dremio() -> None: + session = CatalogSession(_catalog(_bwd())) + session.use(f"{AREA}.draft.stations") + assert session.get_context() == f"{AREA}.draft.stations" + with pytest.raises(CatalogSessionError): + session.use(f"{AREA}.draft.nope") From 35cdd50c4b59601c29245b5bf02851413df8d3a4 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:40:15 +0100 Subject: [PATCH 06/25] Polaris backend: copy, move, views, deletes and versions Fourth step of the Polaris migration (publish follows separately). - data_copy: CREATE TABLE ... AS SELECT in DuckDB into an Iceberg table, with every column cast to a type Iceberg holds (nanosecond timestamps to microseconds, unsigned/small integers widened, geometry to WKB, enums and intervals to text). Reads a view through its own SQL and a read-only Parquet table through read_parquet. Same rules as on Dremio: an existing folder target gets the source's name, overwrite drops whatever is there (by its kind), create_target_folder makes the namespaces. - data_move: the copy, a check that it is there, then the source dropped. - create_view: an Iceberg view registered over REST with its DuckDB SQL and schema - plus the same SQL for Trino when the source is a table - and the source path in the view's "eea.source" property. - delete_table / delete_view check the kind; a missing one is a no-op. - create_version / draft_to_version: Dremio's planning rules (reference and vocabulary folders and views skipped, overwrite, cleanup of what a failed run created) on top of the Polaris copy. - update_latest_release works on Polaris: the session matches #public with or without "#" and in any case (Dremio keeps "#public", Polaris "public"). - PolarisRestClient.create_view takes SQL for more engines. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/polaris.py | 388 +++++++++++++++-- src/eea_datalakehouse/catalog/polaris_rest.py | 11 +- src/eea_datalakehouse/catalog/session.py | 13 +- tests/catalog/polaris_fakes.py | 10 +- tests/catalog/test_polaris_catalog.py | 13 +- tests/catalog/test_polaris_data.py | 394 ++++++++++++++++++ 6 files changed, 791 insertions(+), 38 deletions(-) create mode 100644 tests/catalog/test_polaris_data.py diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index 8b047cf..b497914 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -19,7 +19,7 @@ from . import operations from .backend import Partitions, PublishOutcome -from .duckdb_engine import DuckDbEngine, quote_literal +from .duckdb_engine import DuckDbEngine, quote_identifier, quote_literal from .errors import CatalogAuthError, CatalogOperationError from .operations import TableInfo, VersionResult from .polaris_rest import PARQUET_FORMAT, PolarisHttpError, PolarisRestClient @@ -113,6 +113,85 @@ def _snapshot_rows(metadata: dict[str, Any]) -> int | None: return int(summary["total-records"]) +# The property a view registered here keeps its source path in. +VIEW_SOURCE_PROPERTY = "eea.source" + +# DuckDB types an Iceberg table can't hold, and what to cast them to. +_ICEBERG_CASTS = { + "TINYINT": "INTEGER", + "SMALLINT": "INTEGER", + "UTINYINT": "INTEGER", + "USMALLINT": "INTEGER", + "UINTEGER": "BIGINT", + "UBIGINT": "DECIMAL(38, 0)", + "HUGEINT": "DECIMAL(38, 0)", + "UHUGEINT": "DECIMAL(38, 0)", + "TIMESTAMP_NS": "TIMESTAMP", + "TIMESTAMP_MS": "TIMESTAMP", + "TIMESTAMP_S": "TIMESTAMP", + "TIME WITH TIME ZONE": "VARCHAR", + "INTERVAL": "VARCHAR", + "BIT": "VARCHAR", + "JSON": "VARCHAR", +} + + +def _iceberg_column(name: str, duck_type: str) -> str: + """The select expression for column `name` of DuckDB type `duck_type` in a + table written to Iceberg: the column itself, or a cast to a type Iceberg has.""" + column = quote_identifier(name) + kind = duck_type.upper() + if kind == "GEOMETRY" or kind.startswith("GEOMETRY("): + return f"ST_AsWKB({column}) AS {column}" + if kind.startswith("ENUM("): + return f"CAST({column} AS VARCHAR) AS {column}" + if kind in _ICEBERG_CASTS: + return f"CAST({column} AS {_ICEBERG_CASTS[kind]}) AS {column}" + return column + + +_ICEBERG_TYPES = { + "BOOLEAN": "boolean", + "TINYINT": "int", + "SMALLINT": "int", + "INTEGER": "int", + "UTINYINT": "int", + "USMALLINT": "int", + "BIGINT": "long", + "UINTEGER": "long", + "FLOAT": "float", + "DOUBLE": "double", + "VARCHAR": "string", + "BLOB": "binary", + "DATE": "date", + "TIME": "time", + "TIMESTAMP": "timestamp", + "TIMESTAMP_NS": "timestamp", + "TIMESTAMP_MS": "timestamp", + "TIMESTAMP_S": "timestamp", + "TIMESTAMP WITH TIME ZONE": "timestamptz", + "UUID": "uuid", +} +_DECIMAL_RE = re.compile(r"^DECIMAL\((\d+),\s*(\d+)\)$") + + +def _iceberg_type(duck_type: str) -> str: + """A DuckDB column type as an Iceberg primitive type name, for a view's schema; + anything without one (nested, geometry, …) is described as a string.""" + kind = duck_type.upper() + decimal = _DECIMAL_RE.match(kind) + if decimal: + return f"decimal({decimal.group(1)}, {decimal.group(2)})" + return _ICEBERG_TYPES.get(kind, "string") + + +def _iceberg_fields(columns: list[tuple[str, str]]) -> list[dict[str, Any]]: + return [ + {"id": number, "name": name, "type": _iceberg_type(kind), "required": False} + for number, (name, kind) in enumerate(columns, start=1) + ] + + class PolarisCatalog: """`CatalogBackend` on Polaris — see the module docstring. @@ -534,13 +613,70 @@ def deletetags(self, path: str, tags: list[str], *, idempotency_key: str) -> Non if remaining != current: self.settagsto(path, remaining, idempotency_key=idempotency_key) - # -- not on Polaris yet (next steps of the migration) ---------------------------- + # -- data: copy, move, views, deletes ------------------------------------------------ + + def _columns(self, path: str) -> list[tuple[str, str]]: + """``(name, DuckDB type)`` of every column the table or view at `path` returns.""" + rows = self.engine.fetch_all(f"DESCRIBE SELECT * FROM {self.source_sql(path)}") + return [(str(r["column_name"]), str(r["column_type"])) for r in rows] + + def iceberg_select(self, path: str) -> str: + """``SELECT …`` reading `path` with every column in a type an Iceberg table + can hold — nanosecond timestamps as microseconds, unsigned and small integers + widened, geometry as WKB, and so on (see `_iceberg_column`).""" + columns = self._columns(path) + source = self.source_sql(path) + select = [_iceberg_column(name, kind) for name, kind in columns] + if all( + expr == quote_identifier(name) for expr, (name, _) in zip(select, columns, strict=True) + ): + return f"SELECT * FROM {source}" + return f"SELECT {', '.join(select)} FROM {source}" + + def _drop(self, namespace: list[str], name: str, kind: EntryType) -> None: + """Drop `name` in `namespace`, which is a `kind`: a table with its data + files, a view, or a read-only Parquet table's registration (its files stay).""" + if kind == "table": + self.rest.drop_table(namespace, name) + elif kind == "view": + self.rest.drop_view(namespace, name) + else: + self.rest.drop_generic(namespace, name) - def _not_yet(self, verb: str) -> NoReturn: - raise CatalogOperationError( - f"{verb} is not available on the Polaris backend yet — set " - "EEA_CATALOG_BACKEND=dremio to run it on Dremio" - ) + def _prepare_target( + self, + source_path: str, + target_path: str, + *, + overwrite: bool, + create_target_folder: bool, + ) -> tuple[list[str], str]: + """Checks shared by copy, move and view creation: the source exists; a + target that is an existing folder gets the source's name inside it; the + target's folder exists (or is created); an existing target is dropped with + `overwrite`, an error without it. ``(namespace, name)`` of the target.""" + if self._kind_of(source_path) is None: + raise CatalogOperationError(f"source {source_path!r} does not exist") + if self.is_folder(target_path): + target_path = f"{target_path}.{source_path.rsplit('.', 1)[-1]}" + if target_path == source_path: + raise CatalogOperationError(f"source and target are the same: {source_path!r}") + namespace, name = self._split(target_path) + if create_target_folder: + self.ensure_folder_path(self.path_of(namespace)) + elif not self.rest.namespace_exists(namespace): + raise CatalogOperationError( + f"folder {self.path_of(namespace)!r} does not exist — pass " + "create_target_folder=True, or end the target with / to create it" + ) + existing = self._entry_type(namespace, name) + if existing is not None: + if not overwrite: + raise CatalogOperationError( + f"target {target_path!r} already exists — pass overwrite=True to replace it" + ) + self._drop(namespace, name, existing) + return namespace, name def datacopy( self, @@ -550,8 +686,20 @@ def datacopy( overwrite: bool = False, create_target_folder: bool = False, idempotency_key: str, - ) -> Any: - self._not_yet("data_copy") + ) -> str: + """Copy the table or view at `source_path` into a new Iceberg table + (``CREATE TABLE … AS SELECT`` in DuckDB): a snapshot of what it returns. + A target that is an existing folder gets the source's name inside it. + Returns the target path.""" + namespace, name = self._prepare_target( + source_path, + target_path, + overwrite=overwrite, + create_target_folder=create_target_folder, + ) + target = self.engine.table_ref(namespace, name) + self.engine.execute(f"CREATE TABLE {target} AS {self.iceberg_select(source_path)}") + return self.path_of([*namespace, name]) def datamove( self, @@ -562,8 +710,93 @@ def datamove( overwrite: bool = False, create_target_folder: bool = False, idempotency_key: str, - ) -> Any: - self._not_yet("data_move") + ) -> str: + """`datacopy`, then drop the source (whatever it is) once the copy is + there. The target is always an Iceberg table. Returns the target path.""" + source_kind = self._source_entry(source_path) + target = self.datacopy( + source_path, + target_path, + overwrite=overwrite, + create_target_folder=create_target_folder, + idempotency_key=idempotency_key, + ) + if self._kind_of(target) is None: + raise CatalogOperationError( + f"target {target!r} does not exist after the copy — the move did not complete" + ) + namespace, name = self._split(source_path) + self._drop(namespace, name, source_kind) + return target + + def _source_entry(self, path: str) -> EntryType: + namespace, name = self._split(path) + kind = self._entry_type(namespace, name) + if kind is None: + raise CatalogOperationError(f"source {path!r} does not exist") + return kind + + def createview( + self, + source_path: str, + target_path: str, + *, + overwrite: bool = False, + create_target_folder: bool = False, + idempotency_key: str, + ) -> str: + """Register an Iceberg view at `target_path` over `source_path` + (``SELECT * FROM`` it). A view over an Iceberg table also gets the same + SQL for Trino, which names it the same way. Returns the view's path.""" + source_kind = self._source_entry(source_path) + columns = self._columns(source_path) + sql = f"SELECT * FROM {self.source_sql(source_path)}" + namespace, name = self._prepare_target( + source_path, + target_path, + overwrite=overwrite, + create_target_folder=create_target_folder, + ) + self.rest.create_view( + namespace, + name, + sql=sql, + fields=_iceberg_fields(columns), + default_namespace=namespace, + other_dialects={"trino": sql} if source_kind == "table" else None, + properties={VIEW_SOURCE_PROPERTY: source_path}, + ) + return self.path_of([*namespace, name]) + + def deleteview(self, view_path: str, *, idempotency_key: str) -> None: + """Drop the view; a missing one is a no-op, a table an error.""" + namespace, name = self._split(view_path) + kind = self._entry_type(namespace, name) + if kind is None: + return + if kind != "view": + raise CatalogOperationError(f"{view_path!r} is a {_KIND_NAMES[kind]}, not a view") + self.rest.drop_view(namespace, name) + + def deletetable(self, table_path: str, *, idempotency_key: str) -> None: + """Drop the table (with its data files; a read-only Parquet table's + registration only); a missing one is a no-op, a view an error.""" + namespace, name = self._split(table_path) + kind = self._entry_type(namespace, name) + if kind is None: + return + if kind == "view": + raise CatalogOperationError(f"{table_path!r} is a view, not a table") + self._drop(namespace, name, kind) + + def drop_entry(self, path: str, *, idempotency_key: str) -> None: + """Drop whatever table or view is at `path`; nothing there is a no-op.""" + namespace, name = self._split(path) + kind = self._entry_type(namespace, name) + if kind is not None: + self._drop(namespace, name, kind) + + # -- versions ------------------------------------------------------------------------ def createversion( self, @@ -577,27 +810,132 @@ def createversion( include_views: bool = False, idempotency_key: str, ) -> VersionResult: - self._not_yet("create_version") + """Copy the listed tables of the folder `source_path` into the version + folder ``{target_path}.{version_name}`` — the same rules as Dremio's + `operations.createversion` (what is skipped, what `overwrite` replaces, + what is cleaned up when a copy fails); each copy is a `datacopy`.""" + source_path, version_name, entries = operations._check_version_args( # noqa: SLF001 + source_path, version_name, tables + ) + version_path = f"{target_path}.{version_name}" + created_targets: list[str] = [] + created_folder = False + new_tables: list[str] = [] + try: + copies, from_views, skipped, target_exists, folder_exists = self._plan_version( + source_path, + entries, + version_path, + target_path, + overwrite=overwrite, + create_target_folder=create_target_folder, + include_views=include_views, + ) + if not target_exists: + created_targets = self.ensure_folder_path(target_path) + if not folder_exists: + self.createfolder(version_path, idempotency_key=idempotency_key) + created_folder = True + copied: list[tuple[str, str]] = [] + replaced: list[str] = [] + for source_table, target_table in copies: + existed = folder_exists and self._kind_of(target_table) is not None + self.datacopy( + source_table, + target_table, + overwrite=overwrite, + create_target_folder=True, + idempotency_key=idempotency_key, + ) + copied.append((source_table, target_table)) + (replaced if existed else new_tables).append(target_table) + except Exception as exc: + created_top = ( + created_targets[0] + if created_targets + else (version_path if created_folder else None) + ) + try: + if created_top is not None: + self.deletefolder(created_top, cascade=True, idempotency_key=idempotency_key) + else: + for table in new_tables: + self.drop_entry(table, idempotency_key=idempotency_key) + except Exception as cleanup_error: # noqa: BLE001 — the original failure is raised + leftover = created_top or ", ".join(new_tables) + exc.add_note(f"cleanup failed, check {leftover} by hand: {cleanup_error}") + raise + return VersionResult( + version_path=version_path, + copied=copied, + skipped=skipped, + replaced=replaced, + created_folder=created_folder, + created_target_folders=created_targets, + from_views=from_views, + ) - def createview( + def _plan_version( self, source_path: str, + entries: list[str], + version_path: str, target_path: str, *, - overwrite: bool = False, - create_target_folder: bool = False, - idempotency_key: str, - ) -> Any: - self._not_yet("create_view") - - def deleteview(self, view_path: str, *, idempotency_key: str) -> Any: - self._not_yet("delete_view") + overwrite: bool, + create_target_folder: bool, + include_views: bool, + ) -> tuple[list[tuple[str, str]], list[str], list[tuple[str, str]], bool, bool]: + """Everything `createversion` checks before it writes anything: + ``(copies, from_views, skipped, target_exists, folder_exists)``.""" + if not self.exists(source_path): + raise CatalogOperationError(f"source {source_path!r} does not exist") + if not self.is_folder(source_path): + raise CatalogOperationError(f"source {source_path!r} is not a folder") + target_exists = self.exists(target_path) + if not target_exists and not create_target_folder: + raise CatalogOperationError( + f"target {target_path!r} does not exist — pass create_target_folder=True to " + "create it" + ) + folder_exists = target_exists and self.exists(version_path) + if folder_exists and not overwrite: + raise CatalogOperationError( + f"version {version_path!r} already exists — pass overwrite=True to replace " + "the listed tables in it" + ) + if folder_exists and not self.is_folder(version_path): + raise CatalogOperationError(f"{version_path!r} exists but is not a folder") + available = dict(self.list_dataset_kinds(source_path)) + copies: list[tuple[str, str]] = [] + skipped: list[tuple[str, str]] = [] + from_views: list[str] = [] + for source_table in operations._expand_entries(source_path, entries, available): # noqa: SLF001 + folders = {segment.lower() for segment in source_table.split(".")[:-1]} + shared = sorted(folders & operations._SHARED_TABLE_FOLDERS) # noqa: SLF001 + if shared: + skipped.append((source_table, f"{shared[0]} table — not versioned")) + elif available[source_table] == "VIEW" and not include_views: + skipped.append((source_table, "view — only tables are versioned")) + else: + relative = source_table[len(source_path) + 1 :] + copies.append((source_table, f"{version_path}.{relative}")) + if available[source_table] == "VIEW": + from_views.append(source_table) + if not copies: + reasons = "; ".join(f"{table}: {reason}" for table, reason in skipped) + raise CatalogOperationError( + f"nothing to copy — every listed table was skipped ({reasons})" + ) + return copies, from_views, skipped, target_exists, folder_exists - def deletetable(self, table_path: str, *, idempotency_key: str) -> Any: - self._not_yet("delete_table") + # -- not on Polaris yet (next steps of the migration) ---------------------------- - def drop_entry(self, path: str, *, idempotency_key: str) -> None: - self._not_yet("dropping a table or view") + def _not_yet(self, verb: str) -> NoReturn: + raise CatalogOperationError( + f"{verb} is not available on the Polaris backend yet — set " + "EEA_CATALOG_BACKEND=dremio to run it on Dremio" + ) def publish_target(self, area: str) -> str: return f"the public data store ({area})" diff --git a/src/eea_datalakehouse/catalog/polaris_rest.py b/src/eea_datalakehouse/catalog/polaris_rest.py index e434a91..c2ac66b 100644 --- a/src/eea_datalakehouse/catalog/polaris_rest.py +++ b/src/eea_datalakehouse/catalog/polaris_rest.py @@ -388,10 +388,17 @@ def create_view( fields: Sequence[Mapping[str, Any]], default_namespace: Namespace = (), dialect: str = "duckdb", + other_dialects: Mapping[str, str] | None = None, properties: Mapping[str, str] | None = None, ) -> None: """Register a view: its SQL, and the Iceberg schema `fields` of what it - returns (``{"id", "name", "type", "required"}`` each).""" + returns (``{"id", "name", "type", "required"}`` each). `other_dialects` + adds the same view's SQL for other engines (dialect → SQL).""" + representations = [{"type": "sql", "sql": sql, "dialect": dialect}] + representations += [ + {"type": "sql", "sql": text, "dialect": name} + for name, text in (other_dialects or {}).items() + ] self._call( "POST", f"{self._ns_path(namespace)}/views", @@ -404,7 +411,7 @@ def create_view( "timestamp-ms": int(time.time() * 1000), "summary": {"engine-name": dialect, "engine-version": "eea_datalakehouse"}, "default-namespace": list(default_namespace), - "representations": [{"type": "sql", "sql": sql, "dialect": dialect}], + "representations": representations, }, "properties": dict(properties or {}), }, diff --git a/src/eea_datalakehouse/catalog/session.py b/src/eea_datalakehouse/catalog/session.py index 8071b85..af8ace3 100644 --- a/src/eea_datalakehouse/catalog/session.py +++ b/src/eea_datalakehouse/catalog/session.py @@ -231,10 +231,15 @@ def _plan_version_views( return plan +def _same_tag(a: str, b: str) -> bool: + """Whether two tags are the same: Dremio keeps "#public", Polaris "public".""" + return a.strip().lstrip("#").lower() == b.strip().lstrip("#").lower() + + def _add_tag(catalog: CatalogBackend, path: str, tag: str, *, idempotency_key: str) -> None: """Add `tag` to `path`'s tags, keeping the others.""" tags = catalog.gettagsfrom(path, idempotency_key=f"{idempotency_key}-read") - if tag not in tags: + if not any(_same_tag(existing, tag) for existing in tags): catalog.settagsto(path, [*tags, tag], idempotency_key=idempotency_key) @@ -250,9 +255,11 @@ def _remove_tag_under( ``(path, tags before)`` to `removed` as it goes, so an undo can restore them.""" for number, path in enumerate(catalog.list_datasets(folder), start=1): tags = catalog.gettagsfrom(path, idempotency_key=f"{key}-{number}-read") - if tag in tags: + if any(_same_tag(existing, tag) for existing in tags): catalog.settagsto( - path, [t for t in tags if t != tag], idempotency_key=f"{key}-{number}" + path, + [t for t in tags if not _same_tag(t, tag)], + idempotency_key=f"{key}-{number}", ) removed.append((path, tags)) diff --git a/tests/catalog/polaris_fakes.py b/tests/catalog/polaris_fakes.py index 046137e..d01da84 100644 --- a/tests/catalog/polaris_fakes.py +++ b/tests/catalog/polaris_fakes.py @@ -200,15 +200,19 @@ def create_view( fields: Sequence[Mapping[str, Any]], default_namespace: Sequence[str] = (), dialect: str = "duckdb", + other_dialects: Mapping[str, str] | None = None, properties: Mapping[str, str] | None = None, ) -> None: self.calls.append(("create_view", tuple(namespace), name)) key = self._need(namespace) if (key, name) in self.views or (key, name) in self.tables: raise PolarisHttpError(f"{name} already exists", status=409) - self.views[(key, name)] = FakeEntry( - dict(properties or {}), view_metadata(sql, fields, dialect) - ) + metadata = view_metadata(sql, fields, dialect) + metadata["versions"][0]["representations"] += [ + {"type": "sql", "sql": text, "dialect": other} + for other, text in (other_dialects or {}).items() + ] + self.views[(key, name)] = FakeEntry(dict(properties or {}), metadata) def update_table_properties( self, diff --git a/tests/catalog/test_polaris_catalog.py b/tests/catalog/test_polaris_catalog.py index ce58dc7..debd897 100644 --- a/tests/catalog/test_polaris_catalog.py +++ b/tests/catalog/test_polaris_catalog.py @@ -9,7 +9,6 @@ from eea_datalakehouse.catalog.polaris import PolarisCatalog from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient from eea_datalakehouse.catalog.session import ( - CatalogCommitError, CatalogSession, CatalogSessionError, ) @@ -159,10 +158,14 @@ def test_session_use_of_a_missing_path() -> None: def test_verbs_not_ported_yet_say_so() -> None: catalog, _ = _catalog(_bwd()) - session = CatalogSession(catalog) - session.data_copy(f"{AREA}.draft.stations", f"{AREA}.draft.copy") - with pytest.raises(CatalogCommitError, match="not available on the Polaris backend yet"): - session.commit() + with pytest.raises(CatalogOperationError, match="not available on the Polaris backend yet"): + catalog.publish_dataflow( + "eea_lakehouse.water.bathing.bwd", + overwrite=True, + partitions=(), + idempotency_key="k", + notes=[], + ) def test_magic_builds_a_polaris_session(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/catalog/test_polaris_data.py b/tests/catalog/test_polaris_data.py new file mode 100644 index 0000000..4355a3b --- /dev/null +++ b/tests/catalog/test_polaris_data.py @@ -0,0 +1,394 @@ +"""Step 4 of the Polaris backend: copies, moves, views, deletes, versions and +`update_latest_release`.""" + +from __future__ import annotations + +import re +from typing import Any, cast + +import duckdb +import pytest + +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogOperationError +from eea_datalakehouse.catalog.polaris import ( + VIEW_SOURCE_PROPERTY, + PolarisCatalog, + _iceberg_column, + _iceberg_type, +) +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.session import ( + PUBLIC_TAG, + CatalogCommitError, + CatalogSession, +) +from eea_datalakehouse.catalog.settings import PolarisSettings + +from .polaris_fakes import FakePolarisRest + +SETTINGS = PolarisSettings(uri="http://polaris.test/api/catalog") +AREA = "eea_lakehouse.water.bathing.bwd" +K = "key" +_CTAS = re.compile(r'^CREATE TABLE "eea_lakehouse"\."([^"]+)"\."([^"]+)" AS ') + + +class CatalogEngine(DuckDbEngine): + """Records SQL. A ``CREATE TABLE … AS`` registers the table in the fake + Polaris (as DuckDB writing to the catalog would); a DESCRIBE answers `columns`; + `fail_on` makes the first statement containing it fail.""" + + def __init__( + self, + rest: FakePolarisRest, + columns: list[tuple[str, str]] | None = None, + fail_on: str | None = None, + ) -> None: + super().__init__(SETTINGS, connect=lambda: None, token_provider=lambda: "t") + self.rest = rest + self.sql: list[str] = [] + self.columns = columns or [("id", "BIGINT"), ("site", "VARCHAR")] + self.fail_on = fail_on + + def _check(self, sql: str) -> None: + if self.fail_on and self.fail_on in sql: + self.fail_on = None + raise CatalogOperationError(f"DuckDB: boom\n in: {sql}") + + def fetch_all(self, sql: str) -> list[dict[str, Any]]: + self.sql.append(sql) + self._check(sql) + if sql.startswith("DESCRIBE"): + return [{"column_name": n, "column_type": t} for n, t in self.columns] + return [{"row_count": 1}] + + def execute(self, sql: str) -> None: + self.sql.append(sql) + self._check(sql) + created = _CTAS.match(sql) + if created: + namespace, name = created.groups() + self.rest.add_table(f"{namespace}.{name}") + + def created(self) -> list[str]: + return [s for s in self.sql if s.startswith("CREATE TABLE")] + + +def _setup( + rest: FakePolarisRest | None = None, **engine_args: Any +) -> tuple[PolarisCatalog, FakePolarisRest, CatalogEngine]: + rest = rest or _bwd() + engine = CatalogEngine(rest, **engine_args) + catalog = PolarisCatalog(SETTINGS, rest=cast(PolarisRestClient, rest), engine=engine) + return catalog, rest, engine + + +def _bwd() -> FakePolarisRest: + return ( + FakePolarisRest() + .add_table("water.bathing.bwd.draft.stations") + .add_table("water.bathing.bwd.draft.assessment.results") + .add_table("water.bathing.bwd.draft.reference.countries") + .add_view( + "water.bathing.bwd.draft.latest", + sql='SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations"', + ) + .add_namespace("water", "bathing", "bwd", "versions") + ) + + +# -- type helpers on a real DuckDB -------------------------------------------------------- + + +def test_iceberg_columns_on_real_duckdb() -> None: + con = duckdb.connect() + con.execute( + "CREATE TABLE t AS SELECT 1::TINYINT AS a, 2::UBIGINT AS b, " + "TIMESTAMP_NS '2024-01-01 00:00:00.123456789' AS c, 'x'::VARCHAR AS d, " + "3.5::DECIMAL(10, 2) AS e" + ) + columns = [(r[0], r[1]) for r in con.execute("DESCRIBE t").fetchall()] + select = ", ".join(_iceberg_column(n, k) for n, k in columns) + con.execute(f"CREATE TABLE u AS SELECT {select} FROM t") + + assert {r[0]: r[1] for r in con.execute("DESCRIBE u").fetchall()} == { + "a": "INTEGER", + "b": "DECIMAL(38,0)", + "c": "TIMESTAMP", + "d": "VARCHAR", + "e": "DECIMAL(10,2)", + } + + +@pytest.mark.parametrize( + ("duck", "iceberg"), + [ + ("BIGINT", "long"), + ("INTEGER", "int"), + ("VARCHAR", "string"), + ("DECIMAL(10,2)", "decimal(10, 2)"), + ("TIMESTAMP WITH TIME ZONE", "timestamptz"), + ("STRUCT(a INTEGER)", "string"), + ], +) +def test_iceberg_type(duck: str, iceberg: str) -> None: + assert _iceberg_type(duck) == iceberg + + +def test_geometry_becomes_wkb() -> None: + assert _iceberg_column("geom", "GEOMETRY") == 'ST_AsWKB("geom") AS "geom"' + + +# -- data_copy -------------------------------------------------------------------------------- + + +def test_datacopy_creates_an_iceberg_table() -> None: + catalog, rest, engine = _setup() + + target = catalog.datacopy(f"{AREA}.draft.stations", f"{AREA}.draft.copy", idempotency_key=K) + + assert target == f"{AREA}.draft.copy" + assert engine.created() == [ + 'CREATE TABLE "eea_lakehouse"."water.bathing.bwd.draft"."copy" AS ' + 'SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations"' + ] + assert rest.table_exists(["water", "bathing", "bwd", "draft"], "copy") + + +def test_datacopy_casts_what_iceberg_cannot_hold() -> None: + catalog, _, engine = _setup(columns=[("id", "BIGINT"), ("at", "TIMESTAMP_NS")]) + catalog.datacopy(f"{AREA}.draft.stations", f"{AREA}.draft.copy", idempotency_key=K) + assert engine.created()[0].endswith( + 'AS SELECT "id", CAST("at" AS TIMESTAMP) AS "at" ' + 'FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations"' + ) + + +def test_datacopy_of_a_view_reads_its_sql() -> None: + catalog, _, engine = _setup() + catalog.datacopy(f"{AREA}.draft.latest", f"{AREA}.draft.snapshot", idempotency_key=K) + assert engine.created()[0].endswith( + 'AS SELECT * FROM (SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations")' + ) + + +def test_datacopy_into_an_existing_folder_keeps_the_name() -> None: + catalog, _, _ = _setup() + target = catalog.datacopy(f"{AREA}.draft.stations", f"{AREA}.versions", idempotency_key=K) + assert target == f"{AREA}.versions.stations" + + +def test_datacopy_refuses_an_existing_target_without_overwrite() -> None: + catalog, rest, engine = _setup() + with pytest.raises(CatalogOperationError, match="already exists — pass overwrite=True"): + catalog.datacopy(f"{AREA}.draft.stations", f"{AREA}.draft.latest", idempotency_key=K) + assert engine.created() == [] + + catalog.datacopy( + f"{AREA}.draft.stations", f"{AREA}.draft.latest", overwrite=True, idempotency_key=K + ) + assert ("drop_view", ("water", "bathing", "bwd", "draft"), "latest") in rest.calls + assert rest.table_exists(["water", "bathing", "bwd", "draft"], "latest") + + +def test_datacopy_needs_the_target_folder() -> None: + catalog, rest, _ = _setup() + with pytest.raises(CatalogOperationError, match="create_target_folder=True"): + catalog.datacopy(f"{AREA}.draft.stations", f"{AREA}.archive.s", idempotency_key=K) + catalog.datacopy( + f"{AREA}.draft.stations", f"{AREA}.archive.s", create_target_folder=True, idempotency_key=K + ) + assert rest.table_exists(["water", "bathing", "bwd", "archive"], "s") + + +@pytest.mark.parametrize( + ("source", "target", "message"), + [ + (f"{AREA}.draft.nope", f"{AREA}.draft.x", "does not exist"), + (f"{AREA}.draft.stations", f"{AREA}.draft.stations", "are the same"), + ], +) +def test_datacopy_errors(source: str, target: str, message: str) -> None: + catalog, _, _ = _setup() + with pytest.raises(CatalogOperationError, match=message): + catalog.datacopy(source, target, idempotency_key=K) + + +# -- data_move, views, deletes -------------------------------------------------------------- + + +def test_datamove_copies_then_drops_the_source() -> None: + catalog, rest, _ = _setup() + target = catalog.datamove( + f"{AREA}.draft.stations", f"{AREA}.versions.stations", idempotency_key=K + ) + assert target == f"{AREA}.versions.stations" + assert rest.table_exists(["water", "bathing", "bwd", "versions"], "stations") + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + + +def test_datamove_keeps_the_source_when_the_copy_fails() -> None: + catalog, rest, _ = _setup(fail_on="CREATE TABLE") + with pytest.raises(CatalogOperationError, match="boom"): + catalog.datamove(f"{AREA}.draft.stations", f"{AREA}.draft.moved", idempotency_key=K) + assert rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + + +def test_createview_registers_duckdb_and_trino_sql() -> None: + catalog, rest, _ = _setup() + + catalog.createview(f"{AREA}.draft.stations", f"{AREA}.stations", idempotency_key=K) + + entry = rest.views[(("water", "bathing", "bwd"), "stations")] + sql = 'SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations"' + assert entry.metadata["versions"][0]["representations"] == [ + {"type": "sql", "sql": sql, "dialect": "duckdb"}, + {"type": "sql", "sql": sql, "dialect": "trino"}, + ] + assert entry.metadata["schemas"][0]["fields"] == [ + {"id": 1, "name": "id", "type": "long", "required": False}, + {"id": 2, "name": "site", "type": "string", "required": False}, + ] + assert entry.properties == {VIEW_SOURCE_PROPERTY: f"{AREA}.draft.stations"} + assert catalog.view_sql(f"{AREA}.stations") == sql + + +def test_createview_over_a_view_inlines_its_sql_for_duckdb_only() -> None: + catalog, rest, _ = _setup() + catalog.createview(f"{AREA}.draft.latest", f"{AREA}.latest", idempotency_key=K) + representations = rest.views[(("water", "bathing", "bwd"), "latest")].metadata["versions"][0][ + "representations" + ] + assert [r["dialect"] for r in representations] == ["duckdb"] + assert representations[0]["sql"] == ( + 'SELECT * FROM (SELECT * FROM "eea_lakehouse"."water.bathing.bwd.draft"."stations")' + ) + + +def test_deletes_check_the_kind() -> None: + catalog, rest, _ = _setup() + + with pytest.raises(CatalogOperationError, match="is a view, not a table"): + catalog.deletetable(f"{AREA}.draft.latest", idempotency_key=K) + with pytest.raises(CatalogOperationError, match="is a table, not a view"): + catalog.deleteview(f"{AREA}.draft.stations", idempotency_key=K) + catalog.deleteview(f"{AREA}.draft.latest", idempotency_key=K) + catalog.deletetable(f"{AREA}.draft.stations", idempotency_key=K) + catalog.deletetable(f"{AREA}.draft.stations", idempotency_key=K) # gone: no-op + catalog.drop_entry(f"{AREA}.draft.nope", idempotency_key=K) # nothing: no-op + + assert not rest.view_exists(["water", "bathing", "bwd", "draft"], "latest") + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + + +# -- versions -------------------------------------------------------------------------------- + + +def test_createversion_copies_tables_and_skips_reference_and_views() -> None: + catalog, rest, _ = _setup() + + result = catalog.createversion( + f"{AREA}.draft", "v2026_1", target_path=f"{AREA}.versions", idempotency_key=K + ) + + assert result.version_path == f"{AREA}.versions.v2026_1" + assert result.copied == [ + (f"{AREA}.draft.assessment.results", f"{AREA}.versions.v2026_1.assessment.results"), + (f"{AREA}.draft.stations", f"{AREA}.versions.v2026_1.stations"), + ] + assert sorted(t for t, _ in result.skipped) == [ + f"{AREA}.draft.latest", + f"{AREA}.draft.reference.countries", + ] + assert result.created_folder + assert rest.table_exists(["water", "bathing", "bwd", "versions", "v2026_1"], "stations") + + +def test_createversion_with_views_and_a_table_list() -> None: + catalog, _, _ = _setup() + result = catalog.createversion( + f"{AREA}.draft", + "v2026_2", + ["latest", "stations"], + target_path=f"{AREA}.versions", + include_views=True, + idempotency_key=K, + ) + assert result.from_views == [f"{AREA}.draft.latest"] + assert [t for _, t in result.copied] == [ + f"{AREA}.versions.v2026_2.latest", + f"{AREA}.versions.v2026_2.stations", + ] + + +def test_createversion_refuses_an_existing_version() -> None: + catalog, rest, _ = _setup() + rest.add_namespace("water", "bathing", "bwd", "versions", "v1") + with pytest.raises(CatalogOperationError, match="already exists — pass overwrite=True"): + catalog.createversion( + f"{AREA}.draft", "v1", target_path=f"{AREA}.versions", idempotency_key=K + ) + + +def test_createversion_removes_what_it_created_when_a_copy_fails() -> None: + catalog, rest, _ = _setup(fail_on='"stations"') + with pytest.raises(CatalogOperationError, match="boom"): + catalog.createversion( + f"{AREA}.draft", "v9", target_path=f"{AREA}.versions", idempotency_key=K + ) + assert not rest.namespace_exists(["water", "bathing", "bwd", "versions", "v9"]) + + +# -- through the session ------------------------------------------------------------------------- + + +def test_session_draft_to_version_and_update_latest_release() -> None: + catalog, rest, _ = _setup() + rest.add_table("water.bathing.bwd.versions.v2025_1.stations") + rest.namespaces[("water", "bathing", "bwd", "versions", "v2025_1")]["tags:stations"] = "public" + session = CatalogSession(catalog) + session.use(AREA) + + session.draft_to_version("v2026_1").commit() + report = session.update_latest_release("v2026_1").commit() + + views = sorted(name for ns, name in rest.views if ns == ("water", "bathing", "bwd")) + assert views == ["latest", "stations"] + assert rest.views[(("water", "bathing", "bwd"), "stations")].properties == { + VIEW_SOURCE_PROPERTY: f"{AREA}.versions.v2026_1.stations" + } + assert rest.namespaces[("water", "bathing", "bwd")]["tags:stations"] == "public" + # the earlier release's #public tag is removed, whatever its spelling + assert ( + "tags:stations" not in rest.namespaces[("water", "bathing", "bwd", "versions", "v2025_1")] + ) + assert any("removed '#public'" in note for note in report.notes) + assert session.get_tags("stations") == [PUBLIC_TAG.lstrip("#")] + + +def test_session_data_copy_rolls_back_on_a_later_failure() -> None: + catalog, rest, _ = _setup() + session = CatalogSession(catalog) + session.use(AREA) + + session.data_copy("draft.stations", "archive/") + session.delete_view("draft.nope") # fails: does not exist + with pytest.raises(CatalogCommitError) as caught: + session.commit() + + assert caught.value.rolled_back + assert not rest.namespace_exists(["water", "bathing", "bwd", "archive"]) + + +def test_session_data_move_and_create_view() -> None: + catalog, rest, _ = _setup() + session = CatalogSession(catalog) + session.use(AREA) + + session.data_move("draft.stations", "draft.stations_old").create_view( + "draft.stations_old", "stations_view" + ).commit() + + assert rest.table_exists(["water", "bathing", "bwd", "draft"], "stations_old") + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + assert rest.view_exists(["water", "bathing", "bwd"], "stations_view") From efc272be0642cccb8a37ba396d106f644cbf8d51 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:43:25 +0100 Subject: [PATCH 07/25] Polaris backend: publish through the Document Service Completes step 4 of the Polaris migration: every %catalog verb now runs on Polaris. - publish on Polaris: each #public view of the dataflow (outside draft, versions and reference) is written by DuckDB to one Parquet file and pushed with DDS POST /api/v1/public/files// (X-Keycloak-Token; DDS lets in its publishers' group only). That is the folder DDS gives a table of the same name, so the public path stays stable across releases, as on Dremio; the earlier data.parquet is replaced. - Unlike Dremio it is not all-or-nothing: a failure stops the run and names the views already published, and a publish can't be undone. partition_by and overwrite=False are refused with the reason. - catalog/dds_public.py: PublicDataClient (config, push_files). - PolarisSettings.dds_base_url reads DDS_BASE_URL. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/dds_public.py | 117 +++++++++++ src/eea_datalakehouse/catalog/polaris.py | 102 ++++++++- src/eea_datalakehouse/catalog/settings.py | 4 + tests/catalog/test_polaris_catalog.py | 12 -- tests/catalog/test_polaris_publish.py | 218 ++++++++++++++++++++ 5 files changed, 431 insertions(+), 22 deletions(-) create mode 100644 src/eea_datalakehouse/catalog/dds_public.py create mode 100644 tests/catalog/test_polaris_publish.py diff --git a/src/eea_datalakehouse/catalog/dds_public.py b/src/eea_datalakehouse/catalog/dds_public.py new file mode 100644 index 0000000..e12891c --- /dev/null +++ b/src/eea_datalakehouse/catalog/dds_public.py @@ -0,0 +1,117 @@ +"""`PublicDataClient` — the Document Service's public data store, for `publish` on Polaris. + +DDS (``/api/v1/public``, EEA Lakehouse ``Components/DremioDocumentService``) holds +the only write access to the public bucket. It takes the signed-in user's +Keycloak token (``X-Keycloak-Token``) and lets in members of its publishers' +group only (``data_publishers``):: + + GET /api/v1/public — is a store configured, may I publish? + POST /api/v1/public/files/{folder…} — Parquet files (multipart "files") into + //; files of the same + name are replaced, others kept + +A folder is lower-case names joined by "/" (``water/bathing/bwd/stations``) — +the same folder DDS gives a catalog table of that name. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +import httpx + +from .errors import CatalogAuthError, CatalogOperationError +from .settings import user_token + +DEFAULT_TIMEOUT = 3600.0 # a large table's upload can take a while + + +def _message(response: httpx.Response) -> str: + """DDS' own error message (``{"message": …}``), else the status.""" + try: + body = response.json() + except ValueError: + body = None + if isinstance(body, dict): + for key in ("message", "detail"): + if body.get(key): + return str(body[key]) + return f"HTTP {response.status_code}" + + +class PublicDataClient: + """`config` and `push_files` against DDS at `base_url`, as the signed-in user.""" + + def __init__( + self, + base_url: str, + *, + token_provider: Callable[[], str | None] = user_token, + http: httpx.Client | None = None, + timeout: float = DEFAULT_TIMEOUT, + ) -> None: + if not base_url: + raise CatalogOperationError( + "publishing needs the Document Service: set DDS_BASE_URL in the kernel environment" + ) + self._base_url = base_url.rstrip("/") + self._token_provider = token_provider + self._owns_http = http is None + self._http = http or httpx.Client(timeout=timeout) + + def __repr__(self) -> str: + return f"PublicDataClient(base_url={self._base_url!r})" + + def close(self) -> None: + if self._owns_http: + self._http.close() + + def _call(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]: + token = self._token_provider() + if not token: + raise CatalogAuthError( + "publishing needs your own sign-in (KEYCLOAK_ACCESS_TOKEN is not set)" + ) + url = f"{self._base_url}/api/v1/public{path}" + try: + response = self._http.request( + method, url, headers={"X-Keycloak-Token": token}, **kwargs + ) + except httpx.HTTPError as exc: + raise CatalogOperationError( + f"the Document Service can't be reached ({self._base_url}): {exc}" + ) from exc + if response.status_code in (401, 403): + raise CatalogAuthError(f"the Document Service refused to publish: {_message(response)}") + if response.status_code >= 400: + raise CatalogOperationError( + f"the Document Service could not publish (HTTP {response.status_code}): " + f"{_message(response)}" + ) + return response.json() if response.content else {} + + def config(self) -> dict[str, Any]: + """``{"configured", "bucket", "prefix", "base_url", "publishers_group", "can_publish"}``.""" + return self._call("GET", "") + + def push_files( + self, folder: str, files: Sequence[Path], *, description: str = "" + ) -> dict[str, Any]: + """Publish local Parquet `files` into the public `folder`, keeping their names. + ``{"folder", "url", "public_url", "files", "rows", "bytes", "datasets"}``.""" + handles = [path.open("rb") for path in files] + try: + return self._call( + "POST", + f"/files/{folder.strip('/')}", + data={"description": description}, + files=[ + ("files", (path.name, handle, "application/octet-stream")) + for path, handle in zip(files, handles, strict=True) + ], + ) + finally: + for handle in handles: + handle.close() diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index b497914..82143a6 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -14,13 +14,17 @@ from __future__ import annotations import re +import tempfile from collections.abc import Iterable, Sequence -from typing import Any, Literal, NoReturn +from pathlib import Path +from typing import Any, Literal from . import operations from .backend import Partitions, PublishOutcome +from .dds_public import PublicDataClient from .duckdb_engine import DuckDbEngine, quote_identifier, quote_literal from .errors import CatalogAuthError, CatalogOperationError +from .layout import NOT_PUBLISHED, PUBLIC_TAG from .operations import TableInfo, VersionResult from .polaris_rest import PARQUET_FORMAT, PolarisHttpError, PolarisRestClient from .settings import PolarisSettings @@ -116,6 +120,9 @@ def _snapshot_rows(metadata: dict[str, Any]) -> int | None: # The property a view registered here keeps its source path in. VIEW_SOURCE_PROPERTY = "eea.source" +# The one file publish writes into a view's public folder. +PUBLISHED_FILE = "data.parquet" + # DuckDB types an Iceberg table can't hold, and what to cast them to. _ICEBERG_CASTS = { "TINYINT": "INTEGER", @@ -203,10 +210,12 @@ def __init__( *, rest: PolarisRestClient | None = None, engine: DuckDbEngine | None = None, + public: PublicDataClient | None = None, ) -> None: self._settings = settings self.rest = rest or PolarisRestClient(settings) self.engine = engine or DuckDbEngine(settings) + self._public = public def __repr__(self) -> str: return f"PolarisCatalog(uri={self._settings.uri!r}, catalog={self.root!r})" @@ -218,6 +227,8 @@ def root(self) -> str: def close(self) -> None: self.engine.close() self.rest.close() + if self._public is not None: + self._public.close() # -- paths ---------------------------------------------------------------- @@ -929,19 +940,51 @@ def _plan_version( ) return copies, from_views, skipped, target_exists, folder_exists - # -- not on Polaris yet (next steps of the migration) ---------------------------- + # -- publish --------------------------------------------------------------------------- + # Through the Document Service's public data store: each #public view's rows are + # written to one Parquet file here and pushed into the view's own public folder + # (// — the folder DDS would give a table of that name), + # replacing the file an earlier publish put there. - def _not_yet(self, verb: str) -> NoReturn: - raise CatalogOperationError( - f"{verb} is not available on the Polaris backend yet — set " - "EEA_CATALOG_BACKEND=dremio to run it on Dremio" - ) + @property + def public(self) -> PublicDataClient: + """The Document Service's public-data client (built on first use).""" + if self._public is None: + self._public = PublicDataClient(self._settings.dds_base_url) + return self._public + + def public_folder(self, path: str) -> str: + """The public folder of `path`: its parts below the root joined by "/".""" + return "/".join(self.parts(path)) def publish_target(self, area: str) -> str: - return f"the public data store ({area})" + return f"the public data store ({self.public_folder(area)}/…)" def check_publish(self, area: str, partitions: Partitions, *, idempotency_key: str) -> None: - self._not_yet("publish") + if partitions: + raise CatalogOperationError( + "partition_by is not available on Polaris: each view is published as one " + "Parquet file through the Document Service" + ) + + def _public_views(self, area: str, notes: list[str]) -> list[str]: + """The views `publish_dataflow` publishes: tagged #public, under `area` but + outside its draft, versions and reference folders.""" + internal = tuple(f"{area}.{folder}." for folder in NOT_PUBLISHED) + views: list[str] = [] + for path, kind in self.list_dataset_kinds(area): + if kind != "VIEW" or path.startswith(internal): + continue + tags = self.gettagsfrom(path, idempotency_key="publish") + if PUBLIC_TAG.lstrip("#") not in tags: + notes.append(f"skipped {path!r}: no {PUBLIC_TAG} tag") + continue + views.append(path) + if not views: + raise CatalogOperationError( + f"{area!r} has no views tagged {PUBLIC_TAG!r} — run update_latest_release first" + ) + return views def publish_dataflow( self, @@ -952,4 +995,43 @@ def publish_dataflow( idempotency_key: str, notes: list[str], ) -> PublishOutcome: - self._not_yet("publish") + """Publish every #public view of the dataflow `area` — see the section + comment above. Not all-or-nothing: a failure stops the run, and the error + names the views already published (those stay published). A publish can't + be undone, so every published view counts as replaced.""" + self.check_publish(area, partitions, idempotency_key=idempotency_key) + if not overwrite: + raise CatalogOperationError( + "overwrite=False is not available on Polaris: what is already public can't be " + "checked from here, and publishing replaces each view's file" + ) + views = self._public_views(area, notes) + client = self.public + published: list[str] = [] + with tempfile.TemporaryDirectory(prefix="eea-publish-") as tmp: + for number, view in enumerate(views, start=1): + folder = self.public_folder(view) + local = Path(tmp) / str(number) / PUBLISHED_FILE + local.parent.mkdir() + try: + self.engine.execute( + f"COPY (SELECT * FROM {self.source_sql(view)}) TO " + f"{quote_literal(str(local))} (FORMAT parquet, COMPRESSION zstd)" + ) + result = client.push_files(folder, [local]) + except Exception as exc: + done = ", ".join(repr(v) for v in published) or "none" + raise CatalogOperationError( + f"publishing {view!r} failed: {exc}; already published (not undone): {done}" + ) from exc + finally: + local.unlink(missing_ok=True) + published.append(view) + rows = result.get("rows") + where = result.get("url") or f"{folder}/" + notes.append( + f"published {view!r} to {where}" + + (f" ({rows} rows)" if rows is not None else "") + ) + return len(published), lambda: None + diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py index 8365481..f561349 100644 --- a/src/eea_datalakehouse/catalog/settings.py +++ b/src/eea_datalakehouse/catalog/settings.py @@ -119,6 +119,8 @@ class PolarisSettings: - ``role_arn``: ``RUSTFS_ROLE_ARN``; ``arn:aws:iam:::role/eea-datalakehouse``. - ``flight_host``/``flight_port``: ``FLIGHT_HOST``/``FLIGHT_HOST_PORT``; ``localhost``/``8815``. + - ``dds_base_url``: ``DDS_BASE_URL`` — the Document Service, which `publish` + sends public files through. The user's own identity, ``KEYCLOAK_ACCESS_TOKEN``, is not stored here — see `user_token`, read on every request. @@ -138,6 +140,7 @@ class PolarisSettings: role_arn: str = DEFAULT_ROLE_ARN flight_host: str = "localhost" flight_port: int = DEFAULT_FLIGHT_PORT + dds_base_url: str = "" @property def root(self) -> str: @@ -188,4 +191,5 @@ def from_env(cls, environ: Mapping[str, str] | None = None) -> PolarisSettings: role_arn=_get(env, "RUSTFS_ROLE_ARN") or DEFAULT_ROLE_ARN, flight_host=_get(env, "FLIGHT_HOST") or "localhost", flight_port=port, + dds_base_url=_get(env, "DDS_BASE_URL").rstrip("/"), ) diff --git a/tests/catalog/test_polaris_catalog.py b/tests/catalog/test_polaris_catalog.py index debd897..58470b5 100644 --- a/tests/catalog/test_polaris_catalog.py +++ b/tests/catalog/test_polaris_catalog.py @@ -156,18 +156,6 @@ def test_session_use_of_a_missing_path() -> None: CatalogSession(catalog).use(f"{AREA}.nope") -def test_verbs_not_ported_yet_say_so() -> None: - catalog, _ = _catalog(_bwd()) - with pytest.raises(CatalogOperationError, match="not available on the Polaris backend yet"): - catalog.publish_dataflow( - "eea_lakehouse.water.bathing.bwd", - overwrite=True, - partitions=(), - idempotency_key="k", - notes=[], - ) - - def test_magic_builds_a_polaris_session(monkeypatch: pytest.MonkeyPatch) -> None: from eea_datalakehouse.notebook import magics diff --git a/tests/catalog/test_polaris_publish.py b/tests/catalog/test_polaris_publish.py new file mode 100644 index 0000000..dbb26c0 --- /dev/null +++ b/tests/catalog/test_polaris_publish.py @@ -0,0 +1,218 @@ +"""`publish` on Polaris: each #public view pushed to DDS' public store as one Parquet file.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any, cast + +import httpx +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +import respx + +from eea_datalakehouse.catalog.dds_public import PublicDataClient +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogAuthError, CatalogOperationError +from eea_datalakehouse.catalog.polaris import PolarisCatalog +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.session import ( + CatalogCommitError, + CatalogSession, + CatalogSessionError, +) +from eea_datalakehouse.catalog.settings import PolarisSettings + +from .polaris_fakes import FakePolarisRest + +DDS = "http://dds.test" +SETTINGS = PolarisSettings(uri="http://polaris.test/api/catalog", dds_base_url=DDS) +AREA = "eea_lakehouse.water.bathing.bwd" +_COPY = re.compile(r"^COPY \(SELECT \* FROM (.+)\) TO '([^']+)' \(FORMAT parquet") + + +class CopyEngine(DuckDbEngine): + """A COPY … TO '' writes a small real Parquet file there.""" + + def __init__(self, fail_on: str | None = None) -> None: + super().__init__(SETTINGS, connect=lambda: None, token_provider=lambda: "t") + self.copies: list[tuple[str, str]] = [] + self.fail_on = fail_on + + def execute(self, sql: str) -> None: + match = _COPY.match(sql) + assert match, sql + source, target = match.groups() + if self.fail_on and self.fail_on in source: + raise CatalogOperationError("DuckDB: boom") + self.copies.append((source, target)) + pq.write_table(pa.table({"id": [1, 2, 3]}), target) + + +def _area() -> FakePolarisRest: + rest = ( + FakePolarisRest() + .add_table("water.bathing.bwd.versions.v1.stations") + .add_table("water.bathing.bwd.versions.v1.eu.sites") + .add_namespace("water", "bathing", "bwd", "draft") + .add_namespace("water", "bathing", "bwd", "reference") + .add_view("water.bathing.bwd.stations", 'SELECT * FROM "s"') + .add_view("water.bathing.bwd.eu.sites", 'SELECT * FROM "e"') + .add_view("water.bathing.bwd.unreleased", 'SELECT * FROM "u"') + .add_view("water.bathing.bwd.draft.wip", 'SELECT * FROM "w"') + ) + rest.namespaces[("water", "bathing", "bwd")]["tags:stations"] = "public" + rest.namespaces[("water", "bathing", "bwd", "eu")]["tags:sites"] = "public,reviewed" + rest.namespaces[("water", "bathing", "bwd", "draft")]["tags:wip"] = "public" + return rest + + +def _catalog( + rest: FakePolarisRest, engine: CopyEngine, token: str | None = "user-jwt" +) -> PolarisCatalog: + public = PublicDataClient(DDS, token_provider=lambda: token) + return PolarisCatalog( + SETTINGS, rest=cast(PolarisRestClient, rest), engine=engine, public=public + ) + + +def _push_route(status: int = 200) -> respx.Route: + def answer(request: httpx.Request) -> httpx.Response: + if status != 200: + return httpx.Response(status, json={"message": "not a publisher"}) + folder = request.url.path.removeprefix("/api/v1/public/files/") + return httpx.Response( + 200, + json={"folder": f"{folder}/", "url": f"s3://public/{folder}/", "files": 1, "rows": 3}, + ) + + return respx.post(url__regex=rf"{DDS}/api/v1/public/files/.*").mock(side_effect=answer) + + +@respx.mock +def test_publish_pushes_each_public_view_to_its_own_folder() -> None: + route = _push_route() + engine = CopyEngine() + notes: list[str] = [] + + replaced, undo = _catalog(_area(), engine).publish_dataflow( + AREA, overwrite=True, partitions=(), idempotency_key="k", notes=notes + ) + + assert replaced == 2 + undo() # nothing to undo: a no-op + assert [s for s, _ in engine.copies] == ['(SELECT * FROM "e")', '(SELECT * FROM "s")'] + pushed = [str(call.request.url.path) for call in route.calls] + assert pushed == [ + "/api/v1/public/files/water/bathing/bwd/eu/sites", + "/api/v1/public/files/water/bathing/bwd/stations", + ] + request = route.calls[0].request + assert request.headers["X-Keycloak-Token"] == "user-jwt" + assert b'filename="data.parquet"' in request.content + assert notes == [ + f"skipped '{AREA}.unreleased': no #public tag", + f"published '{AREA}.eu.sites' to s3://public/water/bathing/bwd/eu/sites/ (3 rows)", + f"published '{AREA}.stations' to s3://public/water/bathing/bwd/stations/ (3 rows)", + ] + assert all(not Path(target).exists() for _, target in engine.copies) # cleaned up + + +@respx.mock +def test_a_failure_names_what_is_already_published() -> None: + _push_route() + with pytest.raises(CatalogOperationError, match=r"publishing '.*stations' failed.*eu.sites"): + _catalog(_area(), CopyEngine(fail_on='"s"')).publish_dataflow( + AREA, overwrite=True, partitions=(), idempotency_key="k", notes=[] + ) + + +@respx.mock +def test_not_a_publisher_is_an_auth_error() -> None: + _push_route(status=403) + with pytest.raises(CatalogOperationError, match="not a publisher") as caught: + _catalog(_area(), CopyEngine()).publish_dataflow( + AREA, overwrite=True, partitions=(), idempotency_key="k", notes=[] + ) + assert isinstance(caught.value.__cause__, CatalogAuthError) + + +def test_publishing_needs_a_sign_in() -> None: + client = PublicDataClient(DDS, token_provider=lambda: None) + with pytest.raises(CatalogAuthError, match="KEYCLOAK_ACCESS_TOKEN"): + client.config() + + +def test_publishing_needs_dds() -> None: + catalog = PolarisCatalog( + PolarisSettings(uri="http://polaris.test/api/catalog"), + rest=cast(PolarisRestClient, _area()), + engine=CopyEngine(), + ) + with pytest.raises(CatalogOperationError, match="DDS_BASE_URL"): + catalog.publish_dataflow(AREA, overwrite=True, partitions=(), idempotency_key="k", notes=[]) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"overwrite": True, "partitions": ("year",)}, "partition_by is not available"), + ({"overwrite": False, "partitions": ()}, "overwrite=False is not available"), + ], +) +def test_options_polaris_does_not_have(kwargs: dict[str, Any], message: str) -> None: + with pytest.raises(CatalogOperationError, match=message): + _catalog(_area(), CopyEngine()).publish_dataflow( + AREA, idempotency_key="k", notes=[], **kwargs + ) + + +def test_no_public_views() -> None: + rest = ( + FakePolarisRest() + .add_view("water.bathing.bwd.stations") + .add_namespace("water", "bathing", "bwd", "draft") + ) + with pytest.raises(CatalogOperationError, match="no views tagged '#public'"): + _catalog(rest, CopyEngine()).publish_dataflow( + AREA, overwrite=True, partitions=(), idempotency_key="k", notes=[] + ) + + +# -- through the session ---------------------------------------------------------------------- + + +@respx.mock +def test_session_publish_reports_and_cannot_be_undone() -> None: + _push_route() + session = CatalogSession(_catalog(_area(), CopyEngine())) + session.use(AREA) + + report = session.publish().commit() + + assert report.succeeded == [ + f"publish the #public views of '{AREA}' to 'the public data store (water/bathing/bwd/…)'" + ] + assert sum(note.startswith("published") for note in report.notes) == 2 + + +def test_session_refuses_partition_by_when_queued() -> None: + session = CatalogSession(_catalog(_area(), CopyEngine())) + session.use(AREA) + with pytest.raises(CatalogSessionError, match="partition_by is not available"): + session.publish(partition_by=["year"]) + + +@respx.mock +def test_session_publish_failure_rolls_back_earlier_steps() -> None: + _push_route(status=403) + rest = _area() + session = CatalogSession(_catalog(rest, CopyEngine())) + session.use(AREA) + + session.create_folder("archive").publish() + with pytest.raises(CatalogCommitError): + session.commit() + + assert not rest.namespace_exists(["water", "bathing", "bwd", "archive"]) From 26dda44749a6e2b82d63a39ed2749dcbf82c3c9f Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:48:42 +0100 Subject: [PATCH 08/25] %gpkg on Polaris: read through the Arrow Flight gateway Fifth step of the Polaris migration. - geopackage/flight_source.py: FlightSource, a DatasetSource over Polaris and the EEA Lakehouse Arrow Flight gateway (plain Arrow Flight: the ticket is the SQL; "authorization: Bearer " on every call, no shared fallback identity). The listing and column types come from PolarisCatalog; the SELECT is the catalog's own source_sql, so views are read through their stored SQL and read-only Parquet tables through read_parquet. One Flight client per stream; results are fetched from the gateway address the client connected to (FLIGHT_HOST / FLIGHT_HOST_PORT), not the Docker-internal location it advertises. Refused tokens, an unreachable gateway and query errors become catalog errors with the gateway's own message. - geopackage/controller.py: open_source() picks FlightSource on Polaris and DremioSource on Dremio; a source may build its own SELECT (select_sql); Iceberg and DuckDB type names map to GeoPackage types for empty tables. - GpkgSession reads through open_source, so %gpkg follows the %catalog backend. - PolarisCatalog.settings is public. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/polaris.py | 4 + .../geopackage/controller.py | 35 +++- .../geopackage/flight_source.py | 132 ++++++++++++ src/eea_datalakehouse/geopackage/session.py | 14 +- tests/geopackage/test_flight_source.py | 195 ++++++++++++++++++ tests/geopackage/test_session.py | 2 +- 6 files changed, 372 insertions(+), 10 deletions(-) create mode 100644 src/eea_datalakehouse/geopackage/flight_source.py create mode 100644 tests/geopackage/test_flight_source.py diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index 82143a6..ba19df8 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -224,6 +224,10 @@ def __repr__(self) -> str: def root(self) -> str: return self._settings.catalog + @property + def settings(self) -> PolarisSettings: + return self._settings + def close(self) -> None: self.engine.close() self.rest.close() diff --git a/src/eea_datalakehouse/geopackage/controller.py b/src/eea_datalakehouse/geopackage/controller.py index 3d6a7da..c1d872a 100644 --- a/src/eea_datalakehouse/geopackage/controller.py +++ b/src/eea_datalakehouse/geopackage/controller.py @@ -71,7 +71,7 @@ # Batches a worker may have waiting for the writer before it pauses reading. BATCHES_AHEAD = 3 _RESERVED_PREFIXES = ("gpkg_", "rtree_", "sqlite_") -# Dremio DATA_TYPE -> GeoPackage type, for a table with no rows to learn from. +# Column type -> GeoPackage type, for a table with no rows to learn from. _SQL_TYPES = { "BOOLEAN": "BOOLEAN", "TINYINT": "TINYINT", @@ -86,6 +86,16 @@ "TIMESTAMP": "DATETIME", "BINARY VARYING": "BLOB", "VARBINARY": "BLOB", + # Iceberg type names (Polaris' schema() of an Iceberg table or view) + "INT": "MEDIUMINT", + "LONG": "INTEGER", + "STRING": "TEXT", + "TIMESTAMPTZ": "DATETIME", + "BINARY": "BLOB", + # DuckDB type names (a read-only Parquet table on Polaris) + "VARCHAR": "TEXT", + "BLOB": "BLOB", + "TIMESTAMP WITH TIME ZONE": "DATETIME", } @@ -163,6 +173,18 @@ def _channel(self) -> FlightSqlExecutor: return channel +def open_source(catalog: Any) -> Any: + """The :class:`DatasetSource` for `catalog`: a :class:`~.flight_source.FlightSource` + (the Arrow Flight gateway) on Polaris, a :class:`DremioSource` on Dremio. Use it + as a context manager: it is closed when the export ends.""" + from ..catalog.polaris import PolarisCatalog + from .flight_source import FlightSource + + if isinstance(catalog, PolarisCatalog): + return FlightSource(catalog) + return DremioSource(catalog) + + @dataclass(frozen=True) class GpkgLayer: """One table or view as it was written.""" @@ -431,7 +453,7 @@ def _drain(inbox: queue.Queue[Any]) -> None: def _produce(source: DatasetSource, job: _Job, send: Any, stop: threading.Event) -> None: """Read one table and send the writer its create, its rows, then done.""" - sql = f"SELECT * FROM {_quote_path(job.path)}" + (f" LIMIT {job.limit}" if job.limit else "") + sql = _select_sql(source, job.path, job.limit) description = f"{job.kind.lower()} {job.path}" batches = iter(source.batches(sql)) try: @@ -606,5 +628,14 @@ def _chain(first: pa.RecordBatch, rest: Iterator[pa.RecordBatch]) -> Iterator[pa yield from rest +def _select_sql(source: DatasetSource, path: str, limit: int | None) -> str: + """The SELECT reading `path`: the source's own when it has one (Polaris + names tables differently and reads views through their SQL), else Dremio's.""" + select = getattr(source, "select_sql", None) + if callable(select): + return str(select(path, limit)) + return f"SELECT * FROM {_quote_path(path)}" + (f" LIMIT {limit}" if limit else "") + + def _quote_path(path: str) -> str: return ".".join('"' + segment.replace('"', '""') + '"' for segment in path.split(".")) diff --git a/src/eea_datalakehouse/geopackage/flight_source.py b/src/eea_datalakehouse/geopackage/flight_source.py new file mode 100644 index 0000000..798350e --- /dev/null +++ b/src/eea_datalakehouse/geopackage/flight_source.py @@ -0,0 +1,132 @@ +"""`FlightSource` — `%gpkg`'s rows from Polaris, over the EEA Lakehouse Arrow Flight gateway. + +The gateway (EEA Lakehouse ``Components/ArrowFlightServer``) runs SQL with +DuckDB as the caller: it checks the caller's Keycloak token on every call and +reads Iceberg tables through Polaris, and S3 files with the caller's own +temporary keys. It is plain Arrow Flight, not Flight SQL — a ticket *is* the +SQL:: + + do_get(Ticket(sql), headers={"authorization": "Bearer "}) -> Arrow batches + +Every stream opens its own client, so tables read at once don't share one +connection. The gateway has no shared identity to fall back on: without +``KEYCLOAK_ACCESS_TOKEN`` there is nothing to read with. + +The listing and the column types come from the Polaris catalog (`PolarisCatalog`, +as `%catalog list()`/`schema()`); the SELECT is the catalog's own +(`PolarisCatalog.source_sql`), so a view is read through its stored SQL and a +read-only Parquet table through ``read_parquet`` — the gateway attaches the +catalog under the same name. +""" + +from __future__ import annotations + +import uuid +from collections.abc import Callable, Iterator +from types import TracebackType +from typing import Any + +import pyarrow as pa +import pyarrow.flight as flight + +from ..catalog.errors import CatalogAuthError, CatalogOperationError +from ..catalog.polaris import PolarisCatalog +from ..catalog.settings import user_token + + +def _gateway_message(exc: Exception) -> str: + """The gateway's own message, without the gRPC debug context pyarrow appends.""" + text = str(exc) + for marker in (". Detail:", ". gRPC client debug context:"): + text = text.split(marker, 1)[0] + return text.strip() + + +def _client(location: str) -> Any: + return flight.FlightClient(location) + + +class FlightSource: + """A :class:`~.controller.DatasetSource` over Polaris and the Flight gateway. + + `location` defaults to the catalog settings' ``FLIGHT_HOST``/``FLIGHT_HOST_PORT``; + `client` builds a Flight client for a location (a test passes a fake).""" + + def __init__( + self, + catalog: PolarisCatalog, + *, + location: str | None = None, + token_provider: Callable[[], str | None] = user_token, + client: Callable[[str], Any] = _client, + ) -> None: + self._catalog = catalog + self._location = location or catalog.settings.flight_location + self._token_provider = token_provider + self._client = client + + def __repr__(self) -> str: + return f"FlightSource(location={self._location!r})" + + def __enter__(self) -> FlightSource: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """Nothing is kept open between streams.""" + + def datasets(self, path: str) -> list[tuple[str, str]]: + return self._catalog.list_dataset_kinds(path) + + def columns(self, path: str) -> list[tuple[str, str]]: + info = self._catalog.gettableitemsfrom(path, idempotency_key=f"gpkg-{uuid.uuid4()}") + return list(info.schema.items()) + + def select_sql(self, path: str, limit: int | None) -> str: + """The SELECT that reads `path` on the gateway, with an optional row limit.""" + sql = f"SELECT * FROM {self._catalog.source_sql(path)}" + return f"{sql} LIMIT {int(limit)}" if limit else sql + + def batches(self, sql: str) -> Iterator[pa.RecordBatch]: + token = self._token_provider() + if not token: + raise CatalogAuthError( + "%gpkg on Polaris reads through the Arrow Flight gateway, which needs your own " + "sign-in (KEYCLOAK_ACCESS_TOKEN is not set)" + ) + options = flight.FlightCallOptions(headers=[(b"authorization", f"Bearer {token}".encode())]) + client = self._client(self._location) + try: + try: + reader = client.do_get(flight.Ticket(sql.encode()), options) + except flight.FlightError as exc: + raise self._error(exc, sql) from exc + while True: + try: + chunk = reader.read_chunk() + except StopIteration: + return + except flight.FlightError as exc: + raise self._error(exc, sql) from exc + if chunk.data is not None and chunk.data.num_rows: + yield chunk.data + finally: + client.close() + + def _error(self, exc: Exception, sql: str) -> CatalogOperationError: + message = _gateway_message(exc) + if isinstance(exc, flight.FlightUnauthenticatedError | flight.FlightUnauthorizedError): + return CatalogAuthError(f"the Arrow Flight gateway refused your sign-in: {message}") + if isinstance(exc, flight.FlightUnavailableError): + return CatalogOperationError( + f"the Arrow Flight gateway can't be reached at {self._location} " + f"(FLIGHT_HOST/FLIGHT_HOST_PORT): {message}" + ) + return CatalogOperationError(f"the Arrow Flight gateway failed: {message}\n in: {sql}") diff --git a/src/eea_datalakehouse/geopackage/session.py b/src/eea_datalakehouse/geopackage/session.py index 26feb7c..20c4012 100644 --- a/src/eea_datalakehouse/geopackage/session.py +++ b/src/eea_datalakehouse/geopackage/session.py @@ -26,11 +26,11 @@ import pyproj -from ..catalog.client import Catalog +from ..catalog.backend import CatalogBackend from ..catalog.errors import CatalogOperationError, EngineStartingError from ..dds_documents.paths import path_segments from ..session_utils import check_arg_types, friendly_errors -from .controller import DEFAULT_WORKERS, DremioSource, GpkgController, GpkgReport +from .controller import DEFAULT_WORKERS, GpkgController, GpkgReport, open_source GPKG_SUFFIX = ".gpkg" @@ -58,7 +58,7 @@ class GpkgSession: ``resolve_path(path)`` turns the ``path`` argument into a catalog path: ``None`` means the current `%catalog` context. ``catalog()`` returns the - :class:`~eea_datalakehouse.catalog.Catalog` to read with; ``controller`` + catalog (Dremio or Polaris — see `open_source`) to read with; ``controller`` replaces the one built over it for each export (tests). """ @@ -66,7 +66,7 @@ def __init__( self, *, resolve_path: Callable[[str | None], str | None] | None = None, - catalog: Callable[[], Catalog] | None = None, + catalog: Callable[[], CatalogBackend] | None = None, controller: GpkgController | None = None, ) -> None: self._resolve_path_fn = resolve_path or (lambda path: path) @@ -116,9 +116,9 @@ def export( if self._controller is not None: return self._controller.export(catalog_path, output, **options) # type: ignore[arg-type] if self._catalog is None: - raise RuntimeError("no Dremio catalog to read from") - # One pool of Flight channels per export, closed when it ends. - with DremioSource(self._catalog()) as source: + raise RuntimeError("no catalog to read from") + # One source per export (on Dremio a pool of Flight channels), closed when it ends. + with open_source(self._catalog()) as source: return GpkgController(source).export(catalog_path, output, **options) # type: ignore[arg-type] # -- internals -------------------------------------------------------- diff --git a/tests/geopackage/test_flight_source.py b/tests/geopackage/test_flight_source.py new file mode 100644 index 0000000..6c8b4d2 --- /dev/null +++ b/tests/geopackage/test_flight_source.py @@ -0,0 +1,195 @@ +"""`%gpkg` on Polaris: rows over the Arrow Flight gateway (`FlightSource`).""" + +from __future__ import annotations + +import sqlite3 +import threading +from collections.abc import Iterator +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pyarrow.flight as flight +import pytest +import shapely + +from catalog.polaris_fakes import FakePolarisRest # tests/catalog, on sys.path via pytest +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogAuthError, CatalogOperationError +from eea_datalakehouse.catalog.polaris import PolarisCatalog +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.settings import PolarisSettings +from eea_datalakehouse.geopackage.controller import DremioSource, GpkgController, open_source +from eea_datalakehouse.geopackage.flight_source import FlightSource + +AREA = "eea_lakehouse.water.bwd" +TOKEN = "user-jwt" + + +# -- a real Arrow Flight server, shaped like the gateway ------------------------------------ + + +class _Auth(flight.ServerMiddlewareFactory): + def start_call(self, info: Any, headers: dict[str, list[str]]) -> None: + values = headers.get("authorization") or [] + if values != [f"Bearer {TOKEN}"]: + raise flight.FlightUnauthenticatedError("Invalid token") + return None + + +class Gateway(flight.FlightServerBase): # type: ignore[misc] + """Answers a ticket (the SQL) with `tables[sql]`; records every ticket.""" + + def __init__(self, tables: dict[str, pa.Table]) -> None: + super().__init__("grpc://127.0.0.1:0", middleware={"auth": _Auth()}) + self.tables = tables + self.tickets: list[str] = [] + + def do_get(self, context: Any, ticket: flight.Ticket) -> flight.RecordBatchStream: + sql = ticket.ticket.decode() + self.tickets.append(sql) + if sql not in self.tables: + raise flight.FlightServerError(f"Catalog Error: unknown {sql}") + return flight.RecordBatchStream(self.tables[sql]) + + +@pytest.fixture +def gateway() -> Iterator[Gateway]: + stations = pa.table( + { + "id": pa.array([1, 2], pa.int64()), + "name": ["Lido", "Playa"], + "geom": [ + shapely.to_wkb(shapely.Point(10.0, 45.0)), + shapely.to_wkb(shapely.Point(-3.7, 40.4)), + ], + "srid": [4326, 4326], + } + ) + server = Gateway( + { + 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations"': stations, + 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations" LIMIT 1': stations.slice(0, 1), + 'SELECT * FROM (SELECT 1 AS "n") LIMIT 1': pa.table({"n": [1]}), + 'SELECT * FROM (SELECT 1 AS "n")': pa.table({"n": [1]}), + 'SELECT * FROM "eea_lakehouse"."water.bwd"."empty"': pa.table( + {"id": pa.array([], pa.int64())} + ), + } + ) + thread = threading.Thread(target=server.serve, daemon=True) + thread.start() + yield server + server.shutdown() + + +def _catalog(port: int = 1) -> PolarisCatalog: + rest = ( + FakePolarisRest() + .add_table( + "water.bwd.stations", + { + "current-schema-id": 0, + "schemas": [{"schema-id": 0, "fields": [{"id": 1, "name": "id", "type": "long"}]}], + }, + ) + .add_table( + "water.bwd.empty", + { + "current-schema-id": 0, + "schemas": [{"schema-id": 0, "fields": [{"id": 1, "name": "id", "type": "long"}]}], + "current-snapshot-id": -1, + }, + ) + .add_view("water.bwd.latest", 'SELECT 1 AS "n"') + ) + settings = PolarisSettings(uri="http://polaris.test/api/catalog", flight_port=port) + engine = DuckDbEngine(settings, connect=lambda: None, token_provider=lambda: TOKEN) + return PolarisCatalog(settings, rest=cast(PolarisRestClient, rest), engine=engine) + + +def _source(gateway: Gateway, token: str | None = TOKEN) -> FlightSource: + return FlightSource(_catalog(gateway.port), token_provider=lambda: token) + + +# -- the source ----------------------------------------------------------------------------------- + + +def test_location_comes_from_the_settings() -> None: + assert repr(FlightSource(_catalog(9815))) == "FlightSource(location='grpc://localhost:9815')" + + +def test_select_sql_is_the_catalogs_own() -> None: + source = FlightSource(_catalog()) + assert source.select_sql(f"{AREA}.stations", None) == ( + 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations"' + ) + assert source.select_sql(f"{AREA}.latest", 1) == 'SELECT * FROM (SELECT 1 AS "n") LIMIT 1' + + +def test_datasets_and_columns_come_from_polaris() -> None: + source = FlightSource(_catalog()) + assert source.datasets(AREA) == [ + (f"{AREA}.empty", "TABLE"), + (f"{AREA}.latest", "VIEW"), + (f"{AREA}.stations", "TABLE"), + ] + assert source.columns(f"{AREA}.stations") == [("id", "long")] + + +def test_batches_send_the_token_and_the_sql_as_ticket(gateway: Gateway) -> None: + sql = 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations"' + rows = pa.Table.from_batches(list(_source(gateway).batches(sql))) + assert rows.column("name").to_pylist() == ["Lido", "Playa"] + assert gateway.tickets == [sql] + + +def test_a_refused_token_is_an_auth_error(gateway: Gateway) -> None: + with pytest.raises(CatalogAuthError, match="refused your sign-in"): + list(_source(gateway, token="expired").batches("SELECT 1")) + + +def test_no_token_at_all(gateway: Gateway) -> None: + with pytest.raises(CatalogAuthError, match="KEYCLOAK_ACCESS_TOKEN"): + list(_source(gateway, token=None).batches("SELECT 1")) + + +def test_a_query_error_names_the_sql(gateway: Gateway) -> None: + with pytest.raises( + CatalogOperationError, match=r"failed: Catalog Error: unknown SELECT 2\n in: SELECT 2$" + ): + list(_source(gateway).batches("SELECT 2")) + + +def test_an_unreachable_gateway() -> None: + source = FlightSource(_catalog(), location="grpc://127.0.0.1:1", token_provider=lambda: TOKEN) + with pytest.raises(CatalogOperationError, match="can't be reached at grpc://127.0.0.1:1"): + list(source.batches("SELECT 1")) + + +def test_open_source_picks_flight_on_polaris() -> None: + assert isinstance(open_source(_catalog()), FlightSource) + assert isinstance(open_source(object()), DremioSource) + + +# -- a whole export ------------------------------------------------------------------------------- + + +def test_export_over_flight_writes_a_geopackage(gateway: Gateway, tmp_path: Path) -> None: + output = tmp_path / "bwd.gpkg" + with _source(gateway) as source: + report = GpkgController(source).export( + AREA, output, tables=["stations", "latest", "empty"], limit=None + ) + + layers = {layer.layer: layer for layer in report.layers} + assert layers["stations"].kind == "features" + assert layers["stations"].rows == 2 + assert layers["empty"].rows == 0 + with sqlite3.connect(output) as db: + names = {row[0] for row in db.execute("SELECT table_name FROM gpkg_contents")} + assert {"stations", "empty"} <= names + assert db.execute('SELECT name FROM "stations" ORDER BY id').fetchall() == [ + ("Lido",), + ("Playa",), + ] diff --git a/tests/geopackage/test_session.py b/tests/geopackage/test_session.py index 1ae25a2..538ae3b 100644 --- a/tests/geopackage/test_session.py +++ b/tests/geopackage/test_session.py @@ -96,7 +96,7 @@ def test_call_that_does_not_fit_the_signature_shows_the_usage() -> None: def test_no_catalog_is_a_session_error(tmp_path: Path) -> None: session = GpkgSession(resolve_path=lambda path: DATASET) - with pytest.raises(GpkgSessionError, match="no Dremio catalog"): + with pytest.raises(GpkgSessionError, match="no catalog to read from"): session.export(output_dir=str(tmp_path)) From e60b294db57dfbf565c3d4ca1daaf32c83bc0328 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:59:00 +0100 Subject: [PATCH 09/25] %dds on Polaris: sign in with Keycloak, namespace paths Sixth step of the Polaris migration, first half. - DocumentsClient signs in with either the Dremio PAT (Authorization: Bearer, as before) or, on the Polaris stack, the user's Keycloak token (X-Keycloak-Token and no Authorization header: DDS then checks the Access service's grants for that user). - DdsSession uses the Keycloak token when the catalog backend is polaris (KEYCLOAK_ACCESS_TOKEN required) and stores under the namespace's own path, without the catalog name: eea_lakehouse.water.bwd -> water/bwd, as DDS maps a Keycloak caller's path onto Polaris namespaces. - settings.polaris_catalog_name(). Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/settings.py | 9 +++- src/eea_datalakehouse/dds_documents/client.py | 15 +++++- .../dds_documents/session.py | 34 +++++++++++-- tests/dds_documents/test_session.py | 51 +++++++++++++++++++ 4 files changed, 102 insertions(+), 7 deletions(-) diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py index f561349..3b41145 100644 --- a/src/eea_datalakehouse/catalog/settings.py +++ b/src/eea_datalakehouse/catalog/settings.py @@ -58,6 +58,13 @@ def backend_name(environ: Mapping[str, str] | None = None) -> Backend: return chosen +def polaris_catalog_name(environ: Mapping[str, str] | None = None) -> str: + """The Polaris catalog's name (``POLARIS_CATALOG``/``POLARIS_CATALOG_NAME``, + default ``eea_lakehouse``) — the root of every `%catalog` path on Polaris.""" + env = os.environ if environ is None else environ + return _get(env, "POLARIS_CATALOG", "POLARIS_CATALOG_NAME") or DEFAULT_POLARIS_CATALOG + + def user_token(environ: Mapping[str, str] | None = None) -> str | None: """The signed-in user's Keycloak access token (``KEYCLOAK_ACCESS_TOKEN``), or None. @@ -178,7 +185,7 @@ def from_env(cls, environ: Mapping[str, str] | None = None) -> PolarisSettings: raise SettingsError(f"FLIGHT_HOST_PORT={flight_port!r} is not a port number") from None return cls( uri=uri.rstrip("/"), - catalog=_get(env, "POLARIS_CATALOG", "POLARIS_CATALOG_NAME") or DEFAULT_POLARIS_CATALOG, + catalog=polaris_catalog_name(env), client_id=_get(env, "POLARIS_CLIENT_ID", "POLARIS_ROOT_CLIENT_ID"), client_secret=_get(env, "POLARIS_CLIENT_SECRET", "POLARIS_ROOT_CLIENT_SECRET"), vended_credentials=_get(env, "POLARIS_VENDED_CREDENTIALS").lower() in _TRUE, diff --git a/src/eea_datalakehouse/dds_documents/client.py b/src/eea_datalakehouse/dds_documents/client.py index d310646..6568e15 100644 --- a/src/eea_datalakehouse/dds_documents/client.py +++ b/src/eea_datalakehouse/dds_documents/client.py @@ -80,15 +80,26 @@ class DocumentsClient: def __init__( self, base_url: str, - creds: DremioCreds, + creds: DremioCreds | None = None, *, + keycloak_token: str | None = None, timeout: float = DEFAULT_TIMEOUT, http_client: httpx.Client | None = None, ) -> None: + """Signs in with the Dremio PAT in `creds` (``Authorization: Bearer``), or — + on the Polaris stack — with the user's Keycloak token (``X-Keycloak-Token``, + no ``Authorization`` header: DDS then checks the grants the Access service + holds for that user). Exactly one of the two.""" + if (creds is None) == (keycloak_token is None): + raise ValueError("DocumentsClient needs either creds or keycloak_token, not both") self._base_url = base_url.rstrip("/") self._owns_client = http_client is None self._http = http_client or httpx.Client(timeout=timeout) - self._auth_headers = {"Authorization": f"Bearer {creds.password}"} + self._auth_headers = ( + {"X-Keycloak-Token": keycloak_token} + if keycloak_token is not None + else {"Authorization": f"Bearer {creds.password}"} # type: ignore[union-attr] + ) @classmethod def from_env( diff --git a/src/eea_datalakehouse/dds_documents/session.py b/src/eea_datalakehouse/dds_documents/session.py index 288ace4..ede2789 100644 --- a/src/eea_datalakehouse/dds_documents/session.py +++ b/src/eea_datalakehouse/dds_documents/session.py @@ -41,6 +41,7 @@ import httpx +from ..catalog.settings import backend_name, polaris_catalog_name, user_token from ..dds_ingestion.credentials import ( ENV_BASE_URL, ENV_PWD, @@ -297,14 +298,39 @@ def _dds_path(self, path: str | None) -> str: raise ValueError( "no DDS target path: pick a dataset folder with %catalog use(...) or pass path=" ) + if self._on_polaris(): + # DDS keeps a Polaris namespace's documents under the namespace's own path, + # without the catalog's name: eea_lakehouse.water.bwd -> water/bwd. + root = polaris_catalog_name(self._environ()) + if resolved == root: + raise ValueError( + f"{root!r} is the catalog itself; pick a dataset folder with " + "%catalog use(...) or pass path=" + ) + resolved = resolved.removeprefix(f"{root}.").removeprefix(f"{root}/") return resolved + def _environ(self) -> Mapping[str, str]: + return os.environ if self._env is None else self._env + + def _on_polaris(self) -> bool: + return backend_name(self._environ()) == "polaris" + def _dds(self) -> DdsController: if self._controller is None: - env = os.environ if self._env is None else self._env - self._controller = DdsController( - DocumentsClient(self._resolve_url()[0], load_dds_creds(env)) - ) + env = self._environ() + url = self._resolve_url()[0] + if self._on_polaris(): + token = user_token(env) + if not token: + raise MissingCredentialsError( + "%dds on Polaris signs in with your Keycloak token: " + "KEYCLOAK_ACCESS_TOKEN is not set in the kernel environment" + ) + client = DocumentsClient(url, keycloak_token=token) + else: + client = DocumentsClient(url, load_dds_creds(env)) + self._controller = DdsController(client) return self._controller def _resolve_url(self) -> tuple[str, str]: diff --git a/tests/dds_documents/test_session.py b/tests/dds_documents/test_session.py index e18daa3..711f7c9 100644 --- a/tests/dds_documents/test_session.py +++ b/tests/dds_documents/test_session.py @@ -478,3 +478,54 @@ def test_get_into_a_folder_of_that_name_is_refused(tmp_path: Path) -> None: (tmp_path / "report.pdf").mkdir() with pytest.raises(DdsSessionError, match="is a folder"): _session(env={}).get(DdsFolder.DELIVERABLES, "report.pdf", output_dir=str(tmp_path)) + + +# -- on the Polaris stack: Keycloak sign-in, namespace paths -------------------------------- + +POLARIS_ENV = { + "DDS_BASE_URL": DDS_URL, + "EEA_CATALOG_BACKEND": "polaris", + "KEYCLOAK_ACCESS_TOKEN": "user-jwt", +} +POLARIS_DATASET = "eea_lakehouse.water.bwd" + + +@respx.mock +def test_push_on_polaris_signs_in_with_keycloak_under_the_namespace_path() -> None: + put = respx.put(file_url("water/bwd/deliverables/report.pdf")).mock( + return_value=httpx.Response(201) + ) + + report = _session(POLARIS_DATASET, env=POLARIS_ENV).push(DdsFolder.DELIVERABLES, REPORT) + + assert report.paths == ("water/bwd/deliverables/report.pdf",) + headers = put.calls.last.request.headers + assert headers["X-Keycloak-Token"] == "user-jwt" + assert "Authorization" not in headers + + +def test_target_on_polaris_drops_the_catalog_name() -> None: + session = _session(POLARIS_DATASET, env=POLARIS_ENV) + assert session.target(DdsFolder.METADATA) == "water/bwd/metadata" + assert session.target(DdsFolder.METADATA, path="water/air") == "water/air/metadata" + + +def test_target_on_polaris_with_another_catalog_name() -> None: + session = _session("lake.water.bwd", env={**POLARIS_ENV, "POLARIS_CATALOG": "lake"}) + assert session.target(DdsFolder.METADATA) == "water/bwd/metadata" + + +def test_the_catalog_itself_is_no_dds_folder() -> None: + with pytest.raises(DdsSessionError, match="the catalog itself"): + _session("eea_lakehouse", env=POLARIS_ENV).target(DdsFolder.METADATA) + + +def test_polaris_without_a_keycloak_token() -> None: + env = {k: v for k, v in POLARIS_ENV.items() if k != "KEYCLOAK_ACCESS_TOKEN"} + with pytest.raises(DdsSessionError, match="KEYCLOAK_ACCESS_TOKEN"): + _session(POLARIS_DATASET, env=env).push(DdsFolder.DELIVERABLES, REPORT) + + +def test_documents_client_takes_one_identity() -> None: + with pytest.raises(ValueError, match="either creds or keycloak_token"): + DocumentsClient(DDS_URL) From 92b5b73346a077bbf6836977888adda6f7f89796 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 12:59:00 +0100 Subject: [PATCH 10/25] %ingest on Polaris: upload to the object store, then Iceberg or Parquet Sixth step of the Polaris migration, second half. - dds_ingestion/polaris_ingest.py: PolarisIngest, one folder -> one table, as the signed-in user, without the Document Service. table_format picks the table, as the Polaris Navigator does: * "iceberg" (default): files are uploaded to the staging prefix (s3://////
/), then DuckDB loads them (Parquet, CSV or JSON, csv_options/json_options passed to read_csv/read_json) into an Iceberg table with every column in a type Iceberg holds; the staged files are deleted (kept on failure unless cleanup_on_failure). * "parquet": Parquet files are uploaded as they are into the table's own folder (/
/[/]) and registered as a read-only Parquet table - registered first, so Polaris refuses before anything is uploaded. conflict_mode fail/append/replace as on Dremio (replace with sub_path re-does that sub-folder only); table names follow DDS' rule. diagnose() checks sign-in, files, target and storage without uploading. - promote(path): a read-only Parquet table -> an Iceberg table of the same name, in place; its wiki is kept and its original files removed; the registration is restored if the load fails. - catalog/object_store.py: RustFS from the kernel - the user's own STS keys (AssumeRoleWithWebIdentity with the Keycloak token), else the static key with a note saying why; upload/list/delete with pyarrow.fs. - DuckDbEngine.add_s3_secret() (scoped to a prefix); PolarisCatalog.iceberg_select_from() over any source. - IngestSession runs PolarisIngest on Polaris: ingest(table_format=...), commit, diagnose, promote; Document Service-only options are reported as ignored. %ingest shares %catalog's Polaris catalog; help lists promote. Co-Authored-By: Claude Opus 5.5 --- .../catalog/duckdb_engine.py | 23 + src/eea_datalakehouse/catalog/object_store.py | 205 ++++++ src/eea_datalakehouse/catalog/polaris.py | 22 +- .../dds_ingestion/polaris_ingest.py | 594 ++++++++++++++++++ .../dds_ingestion/session.py | 134 +++- src/eea_datalakehouse/notebook/magics.py | 18 +- tests/dds_ingestion/conftest.py | 8 + tests/dds_ingestion/test_polaris_ingest.py | 488 ++++++++++++++ 8 files changed, 1477 insertions(+), 15 deletions(-) create mode 100644 src/eea_datalakehouse/catalog/object_store.py create mode 100644 src/eea_datalakehouse/dds_ingestion/polaris_ingest.py create mode 100644 tests/dds_ingestion/test_polaris_ingest.py diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py index 7e858e9..c47a286 100644 --- a/src/eea_datalakehouse/catalog/duckdb_engine.py +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -192,6 +192,29 @@ def setup_statements(self) -> list[str]: ) return statements + def add_s3_secret( + self, + name: str, + scope: str, + *, + key_id: str, + secret: str, + session_token: str | None = None, + ) -> None: + """An S3 secret for URLs under `scope` only (``s3://bucket/prefix/``) — e.g. + a user's own temporary keys for files staged there. DuckDB uses the secret + whose scope matches a URL most specifically.""" + settings = self._settings + scheme, _, host = settings.s3_endpoint.partition("://") + token = f"SESSION_TOKEN {quote_literal(session_token)}, " if session_token else "" + self.execute( + f"CREATE OR REPLACE SECRET {quote_identifier(name)} (TYPE s3, " + f"KEY_ID {quote_literal(key_id)}, SECRET {quote_literal(secret)}, {token}" + f"ENDPOINT {quote_literal(host or scheme)}, URL_STYLE 'path', " + f"USE_SSL {'true' if scheme == 'https' else 'false'}, " + f"REGION {quote_literal(settings.s3_region)}, SCOPE {quote_literal(scope)})" + ) + # -- queries -------------------------------------------------------------- def _run(self, sql: str, query: Callable[[Any], Any] | None = None) -> Any: diff --git a/src/eea_datalakehouse/catalog/object_store.py b/src/eea_datalakehouse/catalog/object_store.py new file mode 100644 index 0000000..8cd587d --- /dev/null +++ b/src/eea_datalakehouse/catalog/object_store.py @@ -0,0 +1,205 @@ +"""`ObjectStore` — the Polaris catalog's own object store (RustFS), from this kernel. + +Used by `%ingest` on Polaris to upload files before they are promoted to Iceberg +(or registered as a read-only Parquet table), and to delete them afterwards. + +**Credentials** (`s3_credentials`), first that works: + +1. the signed-in user's own temporary keys: STS ``AssumeRoleWithWebIdentity`` + with ``KEYCLOAK_ACCESS_TOKEN`` against the store's endpoint (role + ``RUSTFS_ROLE_ARN``) — what the Flight gateway and the Document Service do, + so RustFS' own policy for that user applies; +2. the static key (``RUSTFS_ACCESS_KEY``/``RUSTFS_SECRET_KEY``), when STS is + not available — the local stack's RustFS has no OIDC provider configured yet. + +Files are addressed by ``s3://bucket/key`` URLs. pyarrow's S3 filesystem does +the work (path-style addressing, as RustFS needs). +""" + +from __future__ import annotations + +import base64 +import json +import urllib.parse +import xml.etree.ElementTree as ET +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import httpx +from pyarrow import fs as pafs + +from .errors import CatalogAuthError, CatalogOperationError +from .settings import PolarisSettings, user_token + +_STS_NS = {"sts": "https://sts.amazonaws.com/doc/2011-06-15/"} +_STS_SECONDS = 3600 + + +@dataclass(frozen=True) +class S3Credentials: + access_key: str + secret_key: str + session_token: str | None = None + source: str = "static" # "sts" (the user's own) or "static" (the shared key) + note: str = "" # why STS was not used, when it wasn't + + def __repr__(self) -> str: # never the secrets + return f"S3Credentials(source={self.source!r})" + + +def token_username(token: str | None) -> str | None: + """``preferred_username`` from a Keycloak JWT (not verified: only a name for paths).""" + if not token: + return None + try: + payload = token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + except (IndexError, ValueError): + return None + name = claims.get("preferred_username") or claims.get("sub") + return str(name) if name else None + + +def _assume_role(settings: PolarisSettings, token: str, http: httpx.Client) -> S3Credentials: + name = token_username(token) or "user" + response = http.post( + settings.s3_endpoint, + data={ + "Action": "AssumeRoleWithWebIdentity", + "Version": "2011-06-15", + "RoleArn": settings.role_arn, + "RoleSessionName": f"eea-datalakehouse-{name}"[:64], + "WebIdentityToken": token, + "DurationSeconds": str(_STS_SECONDS), + }, + ) + if response.status_code >= 400: + raise CatalogAuthError(f"STS refused ({response.status_code}): {response.text[:300]}") + root = ET.fromstring(response.text) + creds = root.find(".//sts:Credentials", _STS_NS) + if creds is None: + raise CatalogAuthError("STS answered without credentials") + + def value(tag: str) -> str: + found = creds.find(f"sts:{tag}", _STS_NS) + if found is None or not found.text: + raise CatalogAuthError(f"STS answered without {tag}") + return found.text + + return S3Credentials( + value("AccessKeyId"), value("SecretAccessKey"), value("SessionToken"), source="sts" + ) + + +def s3_credentials( + settings: PolarisSettings, + *, + token_provider: Callable[[], str | None] = user_token, + http: httpx.Client | None = None, +) -> S3Credentials: + """Credentials for the object store — see the module docstring.""" + token = token_provider() + problem = "no Keycloak token (KEYCLOAK_ACCESS_TOKEN)" + if token: + client = http or httpx.Client(timeout=30) + try: + return _assume_role(settings, token, client) + except (CatalogAuthError, httpx.HTTPError, ET.ParseError) as exc: + problem = f"your own keys could not be had from STS: {exc}" + finally: + if http is None: + client.close() + if settings.s3_access_key and settings.s3_secret_key: + return S3Credentials(settings.s3_access_key, settings.s3_secret_key, note=problem) + raise CatalogAuthError( + f"no credentials for the object store at {settings.s3_endpoint}: {problem}, and " + "RUSTFS_ACCESS_KEY/RUSTFS_SECRET_KEY are not set" + ) + + +def split_url(url: str) -> tuple[str, str]: + """``s3://bucket/a/b`` → ``("bucket", "a/b")``.""" + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in ("s3", "s3a") or not parsed.netloc: + raise CatalogOperationError(f"not an S3 location: {url!r}") + return parsed.netloc, parsed.path.lstrip("/") + + +@dataclass(frozen=True) +class StoredFile: + url: str + size: int + + +class ObjectStore: + """Upload, list and delete files in the catalog's object store. + + `filesystem` lets a test pass its own (any pyarrow filesystem whose paths are + ``bucket/key``).""" + + def __init__( + self, + settings: PolarisSettings, + credentials: S3Credentials, + *, + filesystem: Any = None, + ) -> None: + self.credentials = credentials + if filesystem is None: + scheme, _, host = settings.s3_endpoint.partition("://") + filesystem = pafs.S3FileSystem( + access_key=credentials.access_key, + secret_key=credentials.secret_key, + session_token=credentials.session_token, + endpoint_override=host or scheme, + scheme=scheme if host else "http", + region=settings.s3_region, + force_virtual_addressing=False, + ) + self._fs = filesystem + + def upload(self, local: Path, url: str) -> None: + bucket, key = split_url(url) + if not isinstance(self._fs, pafs.S3FileSystem): + # A plain filesystem (tests) needs the folder; S3 has none to make. + self._fs.create_dir(f"{bucket}/{key}".rsplit("/", 1)[0], recursive=True) + try: + pafs.copy_files( + str(local), + f"{bucket}/{key}", + source_filesystem=pafs.LocalFileSystem(), + destination_filesystem=self._fs, + ) + except OSError as exc: + raise CatalogOperationError(f"could not upload {local.name} to {url}: {exc}") from exc + + def list(self, prefix_url: str) -> list[StoredFile]: + """Every file under the folder `prefix_url`, at any depth.""" + bucket, key = split_url(prefix_url) + selector = pafs.FileSelector( + f"{bucket}/{key.rstrip('/')}", recursive=True, allow_not_found=True + ) + try: + infos = self._fs.get_file_info(selector) + except OSError as exc: + raise CatalogOperationError(f"could not list {prefix_url}: {exc}") from exc + return sorted( + ( + StoredFile(f"s3://{info.path}", int(info.size or 0)) + for info in infos + if info.type == pafs.FileType.File + ), + key=lambda f: f.url, + ) + + def delete(self, urls: Sequence[str]) -> None: + for url in urls: + bucket, key = split_url(url) + try: + self._fs.delete_file(f"{bucket}/{key}") + except FileNotFoundError: + continue + except OSError as exc: + raise CatalogOperationError(f"could not delete {url}: {exc}") from exc diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index ba19df8..f458988 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -632,15 +632,24 @@ def deletetags(self, path: str, tags: list[str], *, idempotency_key: str) -> Non def _columns(self, path: str) -> list[tuple[str, str]]: """``(name, DuckDB type)`` of every column the table or view at `path` returns.""" - rows = self.engine.fetch_all(f"DESCRIBE SELECT * FROM {self.source_sql(path)}") + return self.columns_of(self.source_sql(path)) + + def columns_of(self, source: str) -> list[tuple[str, str]]: + """``(name, DuckDB type)`` of every column of ``SELECT * FROM ``.""" + rows = self.engine.fetch_all(f"DESCRIBE SELECT * FROM {source}") return [(str(r["column_name"]), str(r["column_type"])) for r in rows] def iceberg_select(self, path: str) -> str: - """``SELECT …`` reading `path` with every column in a type an Iceberg table - can hold — nanosecond timestamps as microseconds, unsigned and small integers - widened, geometry as WKB, and so on (see `_iceberg_column`).""" - columns = self._columns(path) - source = self.source_sql(path) + """``SELECT …`` reading the table or view at `path` with every column in a + type an Iceberg table can hold (see `iceberg_select_from`).""" + return self.iceberg_select_from(self.source_sql(path)) + + def iceberg_select_from(self, source: str) -> str: + """``SELECT …`` reading `source` (anything that goes after ``FROM``) with + every column in a type an Iceberg table can hold — nanosecond timestamps as + microseconds, unsigned and small integers widened, geometry as WKB, and so + on (see `_iceberg_column`).""" + columns = self.columns_of(source) select = [_iceberg_column(name, kind) for name, kind in columns] if all( expr == quote_identifier(name) for expr, (name, _) in zip(select, columns, strict=True) @@ -1038,4 +1047,3 @@ def publish_dataflow( + (f" ({rows} rows)" if rows is not None else "") ) return len(published), lambda: None - diff --git a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py new file mode 100644 index 0000000..dc2c34d --- /dev/null +++ b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py @@ -0,0 +1,594 @@ +"""`%ingest` on Polaris: upload a folder's files to the catalog's object store, then +make a table of them. + +``table_format`` picks what the table is — the two choices the EEA Lakehouse's +Polaris Navigator offers when files are dropped on it: + +* ``"iceberg"`` (the default) — *Updatable*. The files are uploaded to a staging + area (``s3://////
/``), then + promoted: DuckDB reads them (Parquet, CSV or JSON) and writes one Iceberg table + — every column in a type Iceberg holds — and the staged files are deleted. +* ``"parquet"`` — *Read only*. The Parquet files are uploaded as they are into + the table's own folder (``/
/[/]``) and + registered as a read-only Parquet table (a Polaris generic table). `promote` + turns one into an Iceberg table later, in place, and removes the original files. + +``conflict_mode`` decides what happens when the table is already there, as on +Dremio: ``"fail"`` (the default) refuses, ``"append"`` adds rows (Iceberg) or +files (Parquet), ``"replace"`` replaces the table — or, for a Parquet table with +``sub_path``, only that sub-folder's files. + +Everything runs as the signed-in user: Polaris with their Keycloak token, the +object store with their own temporary keys where RustFS allows it (see +`catalog.object_store`). No Document Service is involved. +""" + +from __future__ import annotations + +import datetime as dt +import re +import secrets +import unicodedata +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +import pyarrow.parquet as pq + +from ..catalog.duckdb_engine import quote_literal +from ..catalog.errors import CatalogAuthError, CatalogOperationError +from ..catalog.object_store import ( + ObjectStore, + S3Credentials, + s3_credentials, + split_url, + token_username, +) +from ..catalog.polaris import WIKI_PROPERTY, PolarisCatalog +from ..catalog.polaris_rest import PARQUET_FORMAT +from ..catalog.settings import user_token +from .folder import scan_folder +from .models import DataFormat, FileSpec + +TableFormat = Literal["iceberg", "parquet"] +TABLE_FORMATS: tuple[TableFormat, ...] = ("iceberg", "parquet") +CONFLICT_MODES = ("fail", "append", "replace") +_STAGING_SECRET = "eea_ingest_staging" + +# DDS' own csv_options names, as DuckDB's read_csv calls them. +_CSV_OPTION_NAMES = {"delimiter": "delim", "separator": "delim", "sep": "delim"} + +_SEPARATORS = re.compile(r"[\s.\-/\\]+") +_DISALLOWED = re.compile(r"[^a-z0-9_]") + + +def to_eea_identifier(name: str) -> str: + """`name` as an EEA identifier — ASCII, lower case, separators as ``_``, nothing + else — the same rule the Document Service applies to table names.""" + ascii_name = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode("ascii") + return _DISALLOWED.sub("", _SEPARATORS.sub("_", ascii_name.lower())) + + +def default_table_name(table_name: str | None, specs: Sequence[FileSpec]) -> str: + """`table_name`, or — as the Document Service does — the name of the first + file's top-level folder or file, without its extension; normalised.""" + if table_name: + name = to_eea_identifier(table_name) + else: + top = specs[0].rel_path.split("/", 1)[0] + dot = top.rfind(".") + name = to_eea_identifier(top[:dot] if dot > 0 else top) + if not name: + raise CatalogOperationError( + f"table name {table_name or specs[0].rel_path!r} has no letters or digits — " + "pass table_name=" + ) + return name + + +def _plain_segment(segment: str) -> str: + """A file or folder name with only the characters object keys keep simple.""" + text = unicodedata.normalize("NFKD", segment).encode("ascii", "ignore").decode("ascii") + text = re.sub(r"[^A-Za-z0-9._()+-]+", "_", text).strip("_ ") + return text or "file" + + +def plain_key(rel_path: str) -> str: + """`rel_path` with every segment made plain (``Zürich [2026].parquet`` → + ``Zurich_2026_.parquet``): readers treat ``[ ] * ?`` in a path as patterns.""" + return "/".join(_plain_segment(part) for part in rel_path.split("/") if part) + + +def _sql_value(value: Any) -> str: + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int | float): + return str(value) + if isinstance(value, list | tuple): + return "[" + ", ".join(_sql_value(v) for v in value) + "]" + if isinstance(value, Mapping): + return ( + "{" + + ", ".join(f"{quote_literal(str(k))}: {_sql_value(v)}" for k, v in value.items()) + + "}" + ) + return quote_literal(str(value)) + + +def reader_sql( + data_format: DataFormat, urls: Sequence[str], options: Mapping[str, Any] | None = None +) -> str: + """The DuckDB table function reading the files `urls` of `data_format`.""" + files = "[" + ", ".join(quote_literal(url) for url in urls) + "]" + if data_format == "parquet": + return f"read_parquet({files}, union_by_name = true)" + arguments = [files, "union_by_name = true"] + for key, value in (options or {}).items(): + name = _CSV_OPTION_NAMES.get(key, key) if data_format == "csv" else key + if not re.fullmatch(r"[a-z_]+", name): + raise CatalogOperationError(f"{data_format}_options: {key!r} is not an option name") + arguments.append(f"{name} = {_sql_value(value)}") + function = "read_csv" if data_format == "csv" else "read_json" + return f"{function}({', '.join(arguments)})" + + +@dataclass +class PolarisIngestOutcome: + """What one ingest on Polaris did.""" + + table: str # the table's %catalog path + table_format: str # "iceberg" or "parquet" + action: str # "created", "appended" or "replaced" + rows: int | None + files: int + location: str | None = None # where a Parquet table's files are + notes: list[str] = field(default_factory=list) + + def __str__(self) -> str: + rows = f"{self.rows} rows, " if self.rows is not None else "" + where = f" at {self.location}" if self.location else "" + files = f"{rows}{self.files} files" + return f"{self.action} {self.table_format} table {self.table} ({files}){where}" + + +@dataclass(frozen=True) +class _Plan: + namespace: list[str] + table: str + existing: str | None # "table", "view", "parquet" or None + specs: list[FileSpec] + + +class PolarisIngest: + """One folder → one table on Polaris — see the module docstring. `diagnose` + checks everything without uploading; `run` does it. + + `store` builds the object store client from credentials (a test passes a fake).""" + + def __init__( + self, + folder: str | Path, + target_catalog_path: str, + *, + data_format: DataFormat, + catalog: PolarisCatalog, + table_format: TableFormat = "iceberg", + conflict_mode: str = "fail", + table_name: str | None = None, + sub_path: str | None = None, + csv_options: Mapping[str, Any] | None = None, + json_options: Mapping[str, Any] | None = None, + cleanup_on_failure: bool = False, + show_progress: bool = True, + store: Callable[[S3Credentials], ObjectStore] | None = None, + token_provider: Callable[[], str | None] = user_token, + notes: Sequence[str] = (), + ) -> None: + if table_format not in TABLE_FORMATS: + raise ValueError( + f"table_format must be one of {', '.join(TABLE_FORMATS)}, not {table_format!r}" + ) + if conflict_mode not in CONFLICT_MODES: + raise ValueError( + f"conflict_mode must be one of {', '.join(CONFLICT_MODES)}, not {conflict_mode!r}" + ) + if data_format not in ("parquet", "csv", "json"): + raise ValueError(f"data_format must be parquet, csv or json, not {data_format!r}") + if table_format == "parquet" and data_format != "parquet": + raise ValueError( + "table_format='parquet' keeps the files as they are, so they must be Parquet — " + "use table_format='iceberg' (the default) to load CSV or JSON" + ) + if sub_path is not None and table_format != "parquet": + raise ValueError( + "sub_path files an upload under a sub-folder of a read-only Parquet " + "table — it needs table_format='parquet'" + ) + self.folder = Path(folder).expanduser() + self.target_catalog_path = target_catalog_path + self.data_format: DataFormat = data_format + self.table_format: TableFormat = table_format + self.conflict_mode = conflict_mode + self.table_name = table_name + self.sub_path = sub_path.strip("/") if sub_path else None + self.options = ( + csv_options if data_format == "csv" else json_options if data_format == "json" else None + ) + self.cleanup_on_failure = cleanup_on_failure + self.show_progress = show_progress + self._catalog = catalog + self._store = store or (lambda creds: ObjectStore(catalog.settings, creds)) + self._token_provider = token_provider + self._notes = list(notes) + + def describe(self) -> str: + return f"{self.table_format} ingest {str(self.folder)!r} -> {self.target_catalog_path!r}" + + # -- planning ------------------------------------------------------------------------- + + def _namespace(self) -> list[str]: + root = self._catalog.root + path = self.target_catalog_path.strip().strip("/.") + parts = [p for p in re.split(r"[./]", path) if p] + if parts and parts[0] == root: + parts = parts[1:] + if not parts: + raise CatalogOperationError( + f"target_catalog_path {self.target_catalog_path!r} names no namespace — " + f"give the folder below {root!r}, e.g. 'water.bwd.draft'" + ) + return parts + + def plan(self) -> _Plan: + """What `run` would do, checked — raises before anything is uploaded.""" + if not self.folder.is_dir(): + raise CatalogOperationError(f"{self.folder} is not a folder") + specs = scan_folder(self.folder, self.data_format) + if not specs: + raise CatalogOperationError(f"{self.folder} has no {self.data_format} files") + namespace = self._namespace() + if not self._catalog.rest.namespace_exists(namespace): + path = self._catalog.path_of(namespace) + raise CatalogOperationError( + f"{path!r} does not exist — create it first: " + f"%catalog create_folder({path!r}, create_parents=True)" + ) + table = default_table_name(self.table_name, specs) + existing = self._catalog._entry_type(namespace, table) # noqa: SLF001 — same package + target = self._catalog.path_of([*namespace, table]) + if existing == "view": + raise CatalogOperationError(f"{target!r} is a view; a table can't replace it") + # A Parquet table that grows by sub-folder may take a new one; run() refuses + # a sub-folder that already holds files. + new_sub_folder = existing == "parquet" and self.table_format == "parquet" and self.sub_path + if existing is not None and self.conflict_mode == "fail" and not new_sub_folder: + raise CatalogOperationError( + f"{target!r} already exists — pass conflict_mode='append' or 'replace'" + ) + wanted = "table" if self.table_format == "iceberg" else "parquet" + if self.conflict_mode == "append" and existing is not None and existing != wanted: + if existing == "parquet": + raise CatalogOperationError( + f"{target!r} is a read-only Parquet table: append with " + "table_format='parquet', or promote it first" + ) + raise CatalogOperationError( + f"{target!r} is an Iceberg table: append with table_format='iceberg'" + ) + return _Plan(namespace, table, existing, specs) + + def namespace_location(self, namespace: Sequence[str]) -> str: + """The S3 folder of `namespace`: its ``location`` property, or its nearest + ancestor's with the remaining levels appended (no trailing "/").""" + for depth in range(len(namespace), 0, -1): + location = self._catalog.rest.namespace_properties(namespace[:depth]).get("location") + if location: + return "/".join([location.rstrip("/"), *namespace[depth:]]) + raise CatalogOperationError( + f"can't tell where {self._catalog.path_of(namespace)!r} is stored: neither it nor a " + "namespace above it has a 'location' property" + ) + + def _credentials(self) -> S3Credentials: + creds = s3_credentials(self._catalog.settings, token_provider=self._token_provider) + if creds.note: + self._notes.append(f"uploaded with the shared storage key — {creds.note}") + return creds + + def _progress(self, line: str) -> None: + if self.show_progress: + print(line, flush=True) + + def _upload(self, store: ObjectStore, folder_url: str, specs: Sequence[FileSpec]) -> list[str]: + urls: list[str] = [] + total = len(specs) + for number, spec in enumerate(specs, start=1): + url = f"{folder_url.rstrip('/')}/{plain_key(spec.rel_path)}" + store.upload(self.folder / spec.rel_path, url) + urls.append(url) + self._progress(f" uploaded {number}/{total}: {spec.rel_path}") + return urls + + # -- running ------------------------------------------------------------------------ + + def run(self) -> PolarisIngestOutcome: + plan = self.plan() + if self.table_format == "iceberg": + return self._run_iceberg(plan) + return self._run_parquet(plan) + + def _staging_url(self, namespace: Sequence[str], table: str) -> str: + settings = self._catalog.settings + bucket = settings.ingest_bucket or split_url(self.namespace_location(namespace))[0] + user = to_eea_identifier(token_username(self._token_provider()) or "service") or "service" + run = dt.datetime.now(dt.UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + secrets.token_hex(3) + return f"s3://{bucket}/{settings.ingest_prefix}/{user}/{run}/{table}/" + + def _run_iceberg(self, plan: _Plan) -> PolarisIngestOutcome: + catalog, engine = self._catalog, self._catalog.engine + target = catalog.path_of([*plan.namespace, plan.table]) + creds = self._credentials() + store = self._store(creds) + staging = self._staging_url(plan.namespace, plan.table) + self._progress(f"uploading {len(plan.specs)} file(s) to {staging}") + urls: list[str] = [] + try: + urls = self._upload(store, staging, plan.specs) + engine.add_s3_secret( + _STAGING_SECRET, + staging, + key_id=creds.access_key, + secret=creds.secret_key, + session_token=creds.session_token, + ) + source = reader_sql(self.data_format, urls, self.options) + select = catalog.iceberg_select_from(source) + counted = engine.fetch_all(f'SELECT COUNT(*) AS "row_count" FROM {source}') + rows = int(counted[0]["row_count"]) if counted else None + table_sql = engine.table_ref(plan.namespace, plan.table) + self._progress(f"loading into {target}") + if plan.existing == "table" and self.conflict_mode == "append": + engine.execute(f"INSERT INTO {table_sql} BY NAME {select}") + action = "appended" + else: + if plan.existing is not None: # replace + catalog._drop(plan.namespace, plan.table, plan.existing) # type: ignore[arg-type] # noqa: SLF001 + if plan.existing == "parquet": + self._notes.append( + "the read-only Parquet table it replaced was unregistered; its files " + "stay in the bucket" + ) + engine.execute(f"CREATE TABLE {table_sql} AS {select}") + action = "replaced" if plan.existing is not None else "created" + except Exception as exc: + if self.cleanup_on_failure: + try: + store.delete(urls) + except CatalogOperationError as cleanup_error: + exc.add_note(f"the staged files could not be removed: {cleanup_error}") + elif urls: + exc.add_note(f"the uploaded files are kept at {staging} (cleanup_on_failure=False)") + raise + try: + store.delete(urls) + except CatalogOperationError as exc: + self._notes.append(f"the staged files at {staging} could not be removed: {exc}") + return PolarisIngestOutcome( + table=target, + table_format="iceberg", + action=action, + rows=rows, + files=len(urls), + notes=self._notes, + ) + + def _run_parquet(self, plan: _Plan) -> PolarisIngestOutcome: + catalog, rest = self._catalog, self._catalog.rest + target = catalog.path_of([*plan.namespace, plan.table]) + location = f"{self.namespace_location(plan.namespace)}/{plan.table}/" + folder_url = f"{location}{self.sub_path}/" if self.sub_path else location + creds = self._credentials() + store = self._store(creds) + present = store.list(folder_url) + if present and self.conflict_mode == "fail": + raise CatalogOperationError( + f"{folder_url} already holds {len(present)} file(s) — pass conflict_mode=" + "'append' or 'replace'" + ) + names = {plain_key(spec.rel_path) for spec in plan.specs} + clashes = [f.url for f in present if f.url[len(folder_url) :] in names] + if clashes and self.conflict_mode == "append": + raise CatalogOperationError( + f"{len(clashes)} file(s) of the same name are already there (e.g. {clashes[0]}) — " + "pass conflict_mode='replace' to replace them" + ) + if self.conflict_mode == "replace" and (plan.existing is not None or present): + action = "replaced" + elif plan.existing == "parquet": + action = "appended" # more files, or a new sub-folder, in the same table + else: + action = "created" + registered = plan.existing == "parquet" + if plan.existing == "table" and self.conflict_mode == "replace": + catalog._drop(plan.namespace, plan.table, "table") # noqa: SLF001 — same package + if self.conflict_mode == "replace" and present: + store.delete([f.url for f in present]) + created_registration = False + if not registered: + # Registered first: Polaris checks the caller may write here before + # anything is uploaded. + rest.create_generic( + plan.namespace, + plan.table, + fmt=PARQUET_FORMAT, + base_location=location, + properties={"created_with": "eea_datalakehouse", "read_only": "true"}, + ) + created_registration = True + self._progress(f"uploading {len(plan.specs)} file(s) to {folder_url}") + try: + urls = self._upload(store, folder_url, plan.specs) + except Exception: + if created_registration: + rest.drop_generic(plan.namespace, plan.table) + raise + rows = sum( + pq.ParquetFile(self.folder / spec.rel_path).metadata.num_rows for spec in plan.specs + ) + return PolarisIngestOutcome( + table=target, + table_format="parquet", + action=action, + rows=rows, + files=len(urls), + location=location, + notes=self._notes, + ) + + # -- diagnose ------------------------------------------------------------------------ + + def diagnose(self) -> bool: + """Check this ingest without uploading anything; one printed line per check. + True when every check that ran passed.""" + ok = True + + def report(passed: bool | None, name: str, detail: str) -> None: + nonlocal ok + mark = {True: "✓", False: "✗", None: "–"}[passed] + ok = ok and passed is not False + print(f"{mark} {name}: {detail}", flush=True) + + token = self._token_provider() + report( + True if token else None, + "sign-in", + f"Keycloak user {token_username(token)!r}" + if token + else "no KEYCLOAK_ACCESS_TOKEN — Polaris client credentials will be used", + ) + try: + plan = self.plan() + except CatalogOperationError as exc: + report(False, "plan", str(exc)) + return ok + size = sum(spec.size for spec in plan.specs) + report(True, "files", f"{len(plan.specs)} {self.data_format} file(s), {size} bytes") + report( + True, + "target", + f"{self._catalog.path_of([*plan.namespace, plan.table])} " + + (f"(exists as {plan.existing}; {self.conflict_mode})" if plan.existing else "(new)"), + ) + try: + where = ( + self._staging_url(plan.namespace, plan.table) + if self.table_format == "iceberg" + else f"{self.namespace_location(plan.namespace)}/{plan.table}/" + ) + creds = self._credentials() + self._store(creds).list(where) + report(True, "storage", f"{where} reachable ({creds.source} keys)") + except (CatalogOperationError, CatalogAuthError) as exc: + report(False, "storage", str(exc)) + return ok + + +# -- promote ------------------------------------------------------------------------------ + + +def promote( + catalog: PolarisCatalog, + path: str, + *, + store: Callable[[S3Credentials], ObjectStore] | None = None, + token_provider: Callable[[], str | None] = user_token, +) -> PolarisIngestOutcome: + """Turn the read-only Parquet table at `path` into an Iceberg table of the same + name, in place: its rows are loaded into Iceberg, then its original files are + removed. Its wiki is kept (its tags live on the namespace and stay).""" + namespace, name = catalog._split(path) # noqa: SLF001 — same package + kind = catalog._entry_type(namespace, name) # noqa: SLF001 + if kind is None: + raise CatalogOperationError(f"{path!r} does not exist") + if kind != "parquet": + what = "an Iceberg table already" if kind == "table" else "a view" + raise CatalogOperationError( + f"{path!r} is {what} — only a read-only Parquet table is promoted" + ) + entry = catalog.rest.load_generic(namespace, name) + location = str(entry.get("base-location") or "") + if not location: + raise CatalogOperationError(f"{path!r} has no storage location") + location = location.rstrip("/") + "/" + creds = s3_credentials(catalog.settings, token_provider=token_provider) + objects = (store or (lambda c: ObjectStore(catalog.settings, c)))(creds) + files = objects.list(location) + parquet = [f.url for f in files if f.url.lower().endswith(".parquet")] + others = [f.url for f in files if not f.url.lower().endswith(".parquet")] + if not parquet: + raise CatalogOperationError(f"{location} holds no Parquet files") + if others: + raise CatalogOperationError( + f"{location} also holds {len(others)} other file(s) (e.g. {others[0]}) — " + "move them first" + ) + engine = catalog.engine + engine.add_s3_secret( + _STAGING_SECRET, + location, + key_id=creds.access_key, + secret=creds.secret_key, + session_token=creds.session_token, + ) + source = reader_sql("parquet", parquet) + select = catalog.iceberg_select_from(source) + counted = engine.fetch_all(f'SELECT COUNT(*) AS "row_count" FROM {source}') + rows = int(counted[0]["row_count"]) if counted else None + properties = dict(entry.get("properties") or {}) + catalog.rest.drop_generic(namespace, name) + try: + engine.execute(f"CREATE TABLE {engine.table_ref(namespace, name)} AS {select}") + except Exception: + catalog.rest.create_generic( + namespace, + name, + fmt=PARQUET_FORMAT, + base_location=entry.get("base-location"), + doc=entry.get("doc"), + properties=properties, + ) + raise + notes: list[str] = [] + if properties.get(WIKI_PROPERTY): + catalog.rest.update_table_properties( + namespace, name, {WIKI_PROPERTY: properties[WIKI_PROPERTY]} + ) + try: + objects.delete(parquet) + except CatalogOperationError as exc: + notes.append(f"the original files at {location} could not all be removed: {exc}") + if creds.note: + notes.append(f"read with the shared storage key — {creds.note}") + return PolarisIngestOutcome( + table=path, + table_format="iceberg", + action="promoted", + rows=rows, + files=len(parquet), + notes=notes, + ) + + +__all__ = [ + "CONFLICT_MODES", + "TABLE_FORMATS", + "PolarisIngest", + "PolarisIngestOutcome", + "TableFormat", + "default_table_name", + "plain_key", + "promote", + "reader_sql", + "to_eea_identifier", +] diff --git a/src/eea_datalakehouse/dds_ingestion/session.py b/src/eea_datalakehouse/dds_ingestion/session.py index 32a09b7..fca5013 100644 --- a/src/eea_datalakehouse/dds_ingestion/session.py +++ b/src/eea_datalakehouse/dds_ingestion/session.py @@ -30,15 +30,20 @@ from __future__ import annotations -from collections.abc import Mapping +import os +from collections.abc import Callable, Mapping from dataclasses import dataclass, field from pathlib import Path from typing import Any +from ..catalog.polaris import PolarisCatalog +from ..catalog.settings import PolarisSettings, backend_name from .client import IngestClient from .credentials import DremioCreds from .folder import DEFAULT_PARALLELISM, FolderIngest, IngestOutcome, IngestStateError from .models import DataFormat, Intent, TableDefinition, UploadMode +from .polaris_ingest import PolarisIngest, PolarisIngestOutcome, TableFormat +from .polaris_ingest import promote as polaris_promote class IngestSessionError(RuntimeError): @@ -59,7 +64,7 @@ def __init__( *, failed_index: int, original_error: Exception, - succeeded: list[IngestOutcome], + succeeded: list[IngestOutcome | PolarisIngestOutcome], ) -> None: super().__init__(message) self.failed_index = failed_index @@ -71,7 +76,24 @@ def __init__( class IngestCommitReport: """What a successful `commit()` actually did, in order.""" - outcomes: list[IngestOutcome] = field(default_factory=list) + # `IngestOutcome` on Dremio, `PolarisIngestOutcome` on Polaris. + outcomes: list[IngestOutcome | PolarisIngestOutcome] = field(default_factory=list) + + +# The Document Service pipeline's own options, with their defaults: on Polaris a +# queued ingest that changed one is told it was ignored. +_DDS_ONLY_DEFAULTS: dict[str, Any] = { + "intent": "read_only", + "parallelism": DEFAULT_PARALLELISM, + "multipart": None, + "upload_mode": "auto", + "table_definition": None, +} + + +def _dremio_kwargs(kwargs: Mapping[str, Any]) -> dict[str, Any]: + """A queued ingest's options for `FolderIngest` — without the Polaris-only ones.""" + return {key: value for key, value in kwargs.items() if key != "table_format"} @dataclass @@ -103,12 +125,79 @@ def __init__( client: IngestClient | None = None, base_url: str | None = None, creds: DremioCreds | None = None, + catalog: Callable[[], PolarisCatalog] | None = None, + env: Mapping[str, str] | None = None, ) -> None: + """On Polaris (``EEA_CATALOG_BACKEND``, see `catalog.settings`) the ingests + run with `PolarisIngest` against `catalog()` — by default one built from the + kernel environment — instead of through the Document Service.""" self._client = client self._base_url = base_url self._creds = creds + self._catalog_factory = catalog + self._polaris_catalog: PolarisCatalog | None = None + self._env = env self._pending: list[_QueuedIngest] = [] + def _on_polaris(self) -> bool: + return backend_name(os.environ if self._env is None else self._env) == "polaris" + + def _catalog(self) -> PolarisCatalog: + if self._polaris_catalog is None: + if self._catalog_factory is not None: + self._polaris_catalog = self._catalog_factory() + else: + env = os.environ if self._env is None else self._env + self._polaris_catalog = PolarisCatalog(PolarisSettings.from_env(env)) + return self._polaris_catalog + + def _polaris_job( + self, item: _QueuedIngest, *, show_progress: bool | None = None + ) -> PolarisIngest: + """The queued ingest as a `PolarisIngest`; options only the Document + Service pipeline has are noted as ignored.""" + kwargs = dict(item.kwargs) + ignored = [ + f"{name}={kwargs[name]!r}" + for name, default in _DDS_ONLY_DEFAULTS.items() + if kwargs.get(name, default) != default + ] + notes = ( + [f"ignored on Polaris (Document Service options): {', '.join(ignored)}"] + if ignored + else [] + ) + return PolarisIngest( + item.folder, + item.target_catalog_path, + data_format=item.data_format, + catalog=self._catalog(), + table_format=kwargs.get("table_format", "iceberg"), + conflict_mode=kwargs.get("conflict_mode", "fail"), + table_name=kwargs.get("table_name"), + sub_path=kwargs.get("sub_path"), + csv_options=kwargs.get("csv_options"), + json_options=kwargs.get("json_options"), + cleanup_on_failure=kwargs.get("cleanup_on_failure", False), + show_progress=kwargs.get("show_progress", True) + if show_progress is None + else show_progress, + notes=notes, + ) + + def promote(self, path: str) -> PolarisIngestOutcome: + """Polaris only: turn the read-only Parquet table at `path` (an ingest with + ``table_format="parquet"``) into an Iceberg table of the same name, in place — + its rows are loaded into Iceberg and its original files removed. Runs now, + not at `commit()`. `path` is a full ``%catalog`` path + (``eea_lakehouse..….
``).""" + if not self._on_polaris(): + raise IngestSessionError( + "promote is for the Polaris catalog (EEA_CATALOG_BACKEND=polaris); on Dremio, " + "ingest with intent='editable' instead" + ) + return polaris_promote(self._catalog(), path) + def __repr__(self) -> str: return f"IngestSession(pending={len(self._pending)})" @@ -130,6 +219,7 @@ def ingest( csv_options: Mapping[str, Any] | None = None, json_options: Mapping[str, Any] | None = None, upload_mode: UploadMode = "auto", + table_format: TableFormat = "iceberg", ) -> IngestSession: """Queue one folder ingest — see `FolderIngest` for what each argument means. No `idempotency_key` here: unlike the catalog side, a queued @@ -148,6 +238,16 @@ def ingest( With `cleanup_on_failure=True`, `commit(retry=True)` uploads a cleaned-up ingest again under a new session (see `FolderIngest.retry`). + + On Polaris the files go to the catalog's object store and `table_format` + decides the table (see `polaris_ingest`): ``"iceberg"`` (the default) loads + them into an Iceberg table — Parquet, CSV or JSON — and ``"parquet"`` keeps + Parquet files as a read-only table (`promote` converts it later). + `conflict_mode` is ``"fail"``, ``"append"`` or ``"replace"``; `sub_path` + is for ``"parquet"``. `intent`, `parallelism`, `multipart`, `upload_mode` + and `table_definition` belong to the Document Service pipeline and are + ignored there (the commit report's notes say so). On Dremio, + `table_format` is ignored and `intent` decides. `FolderIngest`'s `infer_schema` is left out on purpose: turning inference off only makes DDS ask for the columns, which `table_definition` gives anyway.""" @@ -169,6 +269,7 @@ def ingest( "csv_options": csv_options, "json_options": json_options, "upload_mode": upload_mode, + "table_format": table_format, }, ) ) @@ -183,6 +284,14 @@ def diagnose(self) -> None: if not self._pending: print("nothing queued — queue an ingest(...) first, then diagnose") return + if self._on_polaris(): + for item in self._pending: + print(f"{item.describe()} (Polaris):") + try: + self._polaris_job(item, show_progress=True).diagnose() + except (OSError, ValueError, RuntimeError) as exc: + print(f"✗ cannot check it: {exc}") + return for item in self._pending: print(f"{item.describe()}:") try: @@ -193,7 +302,7 @@ def diagnose(self) -> None: client=self._client, base_url=self._base_url, creds=self._creds, - **{**item.kwargs, "show_progress": True}, # the lines are the point + **{**_dremio_kwargs(item.kwargs), "show_progress": True}, # the lines matter ) except (OSError, ValueError, RuntimeError) as exc: # A missing folder or credential is itself the finding. @@ -217,8 +326,21 @@ def commit(self, *, retry: bool = False, max_retries: int = 3) -> IngestCommitRe The queue is cleared either way. """ - succeeded: list[IngestOutcome] = [] + succeeded: list[IngestOutcome | PolarisIngestOutcome] = [] pending, self._pending = self._pending, [] + if self._on_polaris(): + for index, item in enumerate(pending): + try: + succeeded.append(self._polaris_job(item).run()) + except Exception as exc: + raise IngestCommitError( + f"{item.describe()} failed ({exc}); {len(succeeded)} earlier ingest(s) " + "in this batch already committed and CANNOT be undone", + failed_index=index, + original_error=exc, + succeeded=succeeded, + ) from exc + return IngestCommitReport(outcomes=succeeded) for index, item in enumerate(pending): job = FolderIngest( item.folder, @@ -227,7 +349,7 @@ def commit(self, *, retry: bool = False, max_retries: int = 3) -> IngestCommitRe client=self._client, base_url=self._base_url, creds=self._creds, - **item.kwargs, + **_dremio_kwargs(item.kwargs), ) try: outcome = self._run_with_retry(job, retry=retry, max_retries=max_retries) diff --git a/src/eea_datalakehouse/notebook/magics.py b/src/eea_datalakehouse/notebook/magics.py index 8eed059..59df34d 100644 --- a/src/eea_datalakehouse/notebook/magics.py +++ b/src/eea_datalakehouse/notebook/magics.py @@ -345,7 +345,9 @@ "Queue one folder ingest (see FolderIngest for what each argument means). " "upload_mode='proxy' when S3 is unreachable; csv_options={'delimiter': ';'}; " "table_definition={'columns': [{'name': 'value', 'type': 'DOUBLE'}]} for the column " - "types of a CSV/JSON table.", + "types of a CSV/JSON table. On Polaris: table_format='iceberg' (default; Parquet, CSV " + "or JSON loaded into an Iceberg table) or 'parquet' (the files kept as a read-only " + "table); conflict_mode 'fail', 'append' or 'replace'.", ), ( "diagnose", @@ -353,6 +355,11 @@ "sizes, DDS's storage, and a dry run. Nothing is uploaded; the queue is kept.", ), ("commit", "Run every queued ingest in order; stops at the first failure."), + ( + "promote", + "Polaris only, runs immediately: turn the read-only Parquet table at path into an " + "Iceberg table of the same name; its original files are removed.", + ), ] _SDI_HELP = [ ( @@ -1074,7 +1081,7 @@ def ingest(self, line: str) -> Any: _print_help_table(IngestSession, _INGEST_HELP, "ingest") return None if self._ingest_session is None: - self._ingest_session = IngestSession() + self._ingest_session = IngestSession(catalog=self._polaris_catalog) result = _dispatch( self._ingest_session, line, self.shell.user_ns, "ingest", IngestSessionError ) @@ -1151,6 +1158,13 @@ def dds(self, line: str) -> Any: _notify_dds_pushed(self.shell, dds_path) return None if result is _DISPATCH_FAILED else result + def _polaris_catalog(self) -> PolarisCatalog: + """`%catalog`'s Polaris catalog, for `%ingest` on Polaris — one connection for both.""" + catalog = self._catalog_for_gpkg() + if not isinstance(catalog, PolarisCatalog): + raise RuntimeError("%catalog is not on Polaris (EEA_CATALOG_BACKEND)") + return catalog + def _catalog_for_gpkg(self) -> CatalogBackend: """`%catalog`'s own Catalog, building its session if need be.""" if self._catalog_session is None: diff --git a/tests/dds_ingestion/conftest.py b/tests/dds_ingestion/conftest.py index be2a09f..653e342 100644 --- a/tests/dds_ingestion/conftest.py +++ b/tests/dds_ingestion/conftest.py @@ -25,3 +25,11 @@ def data_folder(tmp_path: Path) -> Path: (tmp_path / "meta.json").write_text("{}") (tmp_path / "readme.txt").write_text("ignore me") return tmp_path + + +@pytest.fixture(autouse=True) +def _dremio_backend(monkeypatch: pytest.MonkeyPatch) -> None: + """These tests exercise ingest through the Document Service (Dremio): keep a + developer's own Polaris variables (which would switch the backend) out of them.""" + monkeypatch.delenv("EEA_CATALOG_BACKEND", raising=False) + monkeypatch.delenv("POLARIS_URI", raising=False) diff --git a/tests/dds_ingestion/test_polaris_ingest.py b/tests/dds_ingestion/test_polaris_ingest.py new file mode 100644 index 0000000..f62341e --- /dev/null +++ b/tests/dds_ingestion/test_polaris_ingest.py @@ -0,0 +1,488 @@ +"""`%ingest` on Polaris: upload to the object store, then an Iceberg or a read-only +Parquet table; `promote`.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any, cast + +import duckdb +import httpx +import pyarrow as pa +import pyarrow.parquet as pq +import pytest +import respx +from pyarrow import fs as pafs + +from catalog.polaris_fakes import FakePolarisRest # tests/catalog, on sys.path via pytest +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogAuthError, CatalogOperationError +from eea_datalakehouse.catalog.object_store import ObjectStore, S3Credentials, s3_credentials +from eea_datalakehouse.catalog.polaris import PolarisCatalog +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.settings import PolarisSettings +from eea_datalakehouse.dds_ingestion.models import FileSpec +from eea_datalakehouse.dds_ingestion.polaris_ingest import ( + PolarisIngest, + default_table_name, + plain_key, + promote, + reader_sql, + to_eea_identifier, +) +from eea_datalakehouse.dds_ingestion.session import ( + IngestCommitError, + IngestSession, + IngestSessionError, +) + +SETTINGS = PolarisSettings( + uri="http://polaris.test/api/catalog", + s3_endpoint="http://rustfs.test:9000", + s3_access_key="ak", + s3_secret_key="sk", +) +NS_LOCATION = "s3://lake/catalog/water/bwd" +_CTAS = re.compile(r'^CREATE TABLE "eea_lakehouse"\."([^"]+)"\."([^"]+)" AS ') +# A JWT whose payload is {"preferred_username": "ana"} +TOKEN = "x.eyJwcmVmZXJyZWRfdXNlcm5hbWUiOiAiYW5hIn0.y" + + +class Engine(DuckDbEngine): + """Records SQL; a CREATE TABLE … AS registers the table in the fake Polaris.""" + + def __init__(self, rest: FakePolarisRest, fail_on: str | None = None, rows: int = 5) -> None: + super().__init__(SETTINGS, connect=lambda: None, token_provider=lambda: TOKEN) + self.rest = rest + self.sql: list[str] = [] + self.fail_on = fail_on + self.rows = rows + + def fetch_all(self, sql: str) -> list[dict[str, Any]]: + self.sql.append(sql) + if sql.startswith("DESCRIBE"): + return [{"column_name": "id", "column_type": "BIGINT"}] + return [{"row_count": self.rows}] + + def execute(self, sql: str) -> None: + self.sql.append(sql) + if self.fail_on and self.fail_on in sql: + raise CatalogOperationError("DuckDB: boom") + created = _CTAS.match(sql) + if created: + self.rest.add_table(".".join(created.groups())) + + +@pytest.fixture +def bucket(tmp_path: Path) -> Path: + root = tmp_path / "s3" + root.mkdir() + return root + + +def _store(bucket: Path) -> Any: + def make(creds: S3Credentials) -> ObjectStore: + return ObjectStore( + SETTINGS, creds, filesystem=pafs.SubTreeFileSystem(str(bucket), pafs.LocalFileSystem()) + ) + + return make + + +def _rest() -> FakePolarisRest: + rest = FakePolarisRest().add_namespace("water", "bwd") + rest.namespaces[("water",)]["location"] = "s3://lake/catalog/water" + return rest + + +def _setup( + rest: FakePolarisRest | None = None, **engine_args: Any +) -> tuple[PolarisCatalog, FakePolarisRest, Engine]: + rest = rest or _rest() + engine = Engine(rest, **engine_args) + catalog = PolarisCatalog(SETTINGS, rest=cast(PolarisRestClient, rest), engine=engine) + return catalog, rest, engine + + +def _folder(tmp_path: Path, kind: str = "parquet", names: tuple[str, ...] = ("a",)) -> Path: + folder = tmp_path / "bw_2026" + folder.mkdir(exist_ok=True) + for name in names: + if kind == "parquet": + pq.write_table(pa.table({"id": [1, 2]}), folder / f"{name}.parquet") + else: + (folder / f"{name}.csv").write_text("id;name\n1;x\n2;y\n") + return folder + + +def _ingest(catalog: PolarisCatalog, folder: Path, bucket: Path, **kwargs: Any) -> PolarisIngest: + kwargs.setdefault("data_format", "parquet") + return PolarisIngest( + folder, + kwargs.pop("target", "eea_lakehouse.water.bwd"), + catalog=catalog, + store=_store(bucket), + token_provider=lambda: None, + show_progress=False, + **kwargs, + ) + + +def _files(root: Path) -> list[str]: + return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()) + + +# -- names and SQL --------------------------------------------------------------------- + + +def test_to_eea_identifier() -> None: + assert to_eea_identifier("Water Temperature-2026.v1") == "water_temperature_2026_v1" + assert to_eea_identifier("Île de Köln") == "ile_de_koln" + + +def test_default_table_name_follows_dds() -> None: + assert default_table_name(None, [FileSpec("Stations 2026.parquet", 1)]) == "stations_2026" + assert default_table_name(None, [FileSpec("country=at/part-1.parquet", 1)]) == "countryat" + assert default_table_name("Water Temp", [FileSpec("a.parquet", 1)]) == "water_temp" + with pytest.raises(CatalogOperationError, match="pass table_name"): + default_table_name("***", [FileSpec("a.parquet", 1)]) + + +def test_plain_key() -> None: + assert plain_key("2026/Zürich [v1].parquet") == "2026/Zurich_v1_.parquet" + + +def test_reader_sql_on_real_duckdb(tmp_path: Path) -> None: + csv = tmp_path / "a.csv" + csv.write_text("id;name\n1;x\n2;y\n") + sql = reader_sql("csv", [str(csv)], {"delimiter": ";", "header": True}) + assert "delim = ';'" in sql and "header = true" in sql + assert duckdb.connect().execute(f"SELECT COUNT(*), MAX(name) FROM {sql}").fetchone() == (2, "y") + + jsn = tmp_path / "a.json" + jsn.write_text('[{"id": 1}, {"id": 2}]') + sql = reader_sql("json", [str(jsn)], {"format": "array"}) + assert duckdb.connect().execute(f"SELECT SUM(id) FROM {sql}").fetchone() == (3,) + + with pytest.raises(CatalogOperationError, match="is not an option name"): + reader_sql("csv", ["x"], {"bad name; DROP": 1}) + + +def test_argument_checks(tmp_path: Path) -> None: + catalog, _, _ = _setup() + with pytest.raises(ValueError, match="must be Parquet"): + PolarisIngest(tmp_path, "w", data_format="csv", catalog=catalog, table_format="parquet") + with pytest.raises(ValueError, match="needs table_format='parquet'"): + PolarisIngest(tmp_path, "w", data_format="parquet", catalog=catalog, sub_path="2026") + with pytest.raises(ValueError, match="conflict_mode"): + PolarisIngest(tmp_path, "w", data_format="parquet", catalog=catalog, conflict_mode="x") + + +# -- Iceberg (the default) ------------------------------------------------------------- + + +def test_iceberg_ingest_stages_loads_and_cleans_up(tmp_path: Path, bucket: Path) -> None: + catalog, rest, engine = _setup() + folder = _folder(tmp_path, names=("a", "b")) + + outcome = _ingest(catalog, folder, bucket).run() + + assert outcome.table == "eea_lakehouse.water.bwd.a" + assert (outcome.action, outcome.rows, outcome.files) == ("created", 5, 2) + assert rest.table_exists(["water", "bwd"], "a") + secret = next(s for s in engine.sql if "SECRET" in s) + assert re.search(r"SCOPE 's3://lake/_ingestion/service/\d{8}T\d{6}Z-\w+/a/'\)$", secret) + ctas = next(s for s in engine.sql if s.startswith("CREATE TABLE")) + assert ctas.startswith( + 'CREATE TABLE "eea_lakehouse"."water.bwd"."a" AS SELECT * FROM read_parquet([' + ) + assert "/a/a.parquet', 's3://lake/_ingestion/" in ctas + assert _files(bucket) == [] # staged files removed + + +def test_iceberg_ingest_of_csv(tmp_path: Path, bucket: Path) -> None: + catalog, _, engine = _setup() + folder = _folder(tmp_path, kind="csv") + _ingest(catalog, folder, bucket, data_format="csv", csv_options={"delimiter": ";"}).run() + ctas = next(s for s in engine.sql if s.startswith("CREATE TABLE")) + assert "read_csv([" in ctas and "delim = ';'" in ctas + + +def test_iceberg_append_and_replace(tmp_path: Path, bucket: Path) -> None: + catalog, rest, engine = _setup(_rest().add_table("water.bwd.a")) + folder = _folder(tmp_path) + + assert _ingest(catalog, folder, bucket, conflict_mode="append").run().action == "appended" + assert any( + s.startswith('INSERT INTO "eea_lakehouse"."water.bwd"."a" BY NAME SELECT') + for s in engine.sql + ) + + assert _ingest(catalog, folder, bucket, conflict_mode="replace").run().action == "replaced" + assert ("drop_table", ("water", "bwd"), "a") in rest.calls + + +def test_existing_table_fails_before_any_upload(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup(_rest().add_table("water.bwd.a")) + with pytest.raises(CatalogOperationError, match="already exists — pass conflict_mode"): + _ingest(catalog, _folder(tmp_path), bucket).run() + assert _files(bucket) == [] + + +def test_a_failed_load_keeps_the_staged_files_unless_asked(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup(fail_on="CREATE TABLE") + with pytest.raises(CatalogOperationError, match="boom") as caught: + _ingest(catalog, _folder(tmp_path), bucket).run() + assert any("files are kept at s3://lake/_ingestion/" in note for note in caught.value.__notes__) + assert len(_files(bucket)) == 1 + + catalog, _, _ = _setup(fail_on="CREATE TABLE") + for path in bucket.rglob("*.parquet"): + path.unlink() + with pytest.raises(CatalogOperationError, match="boom"): + _ingest(catalog, _folder(tmp_path), bucket, cleanup_on_failure=True).run() + assert _files(bucket) == [] + + +def test_ingest_bucket_setting_wins(tmp_path: Path, bucket: Path) -> None: + catalog, _, engine = _setup() + catalog._settings = PolarisSettings( # noqa: SLF001 + uri=SETTINGS.uri, + s3_access_key="ak", + s3_secret_key="sk", + ingest_bucket="staging", + ingest_prefix="in", + ) + _ingest(catalog, _folder(tmp_path), bucket).run() + assert any("SCOPE 's3://staging/in/service/" in s for s in engine.sql) + + +def test_missing_namespace_says_how_to_create_it(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup() + with pytest.raises(CatalogOperationError, match=r"create_folder\('eea_lakehouse.water.nope'"): + _ingest(catalog, _folder(tmp_path), bucket, target="water/nope").run() + + +# -- read-only Parquet ----------------------------------------------------------------- + + +def test_parquet_ingest_uploads_in_place_and_registers(tmp_path: Path, bucket: Path) -> None: + catalog, rest, _ = _setup() + folder = _folder(tmp_path, names=("a", "b")) + + outcome = _ingest(catalog, folder, bucket, table_format="parquet", table_name="temps").run() + + assert (outcome.action, outcome.rows, outcome.files) == ("created", 4, 2) + assert outcome.location == f"{NS_LOCATION}/temps/" + assert _files(bucket) == [ + "lake/catalog/water/bwd/temps/a.parquet", + "lake/catalog/water/bwd/temps/b.parquet", + ] + entry = rest.generic[(("water", "bwd"), "temps")] + assert (entry["format"], entry["base-location"]) == ("parquet", f"{NS_LOCATION}/temps/") + assert catalog.entry_kind("eea_lakehouse.water.bwd.temps", idempotency_key="k") == "TABLE" + + +def test_parquet_table_grows_by_sub_path(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup() + folder = _folder(tmp_path) + args = {"table_format": "parquet", "table_name": "temps"} + + _ingest(catalog, folder, bucket, sub_path="2025", **args).run() + outcome = _ingest(catalog, folder, bucket, sub_path="2026", **args).run() + + assert outcome.action == "appended" + assert _files(bucket) == [ + "lake/catalog/water/bwd/temps/2025/a.parquet", + "lake/catalog/water/bwd/temps/2026/a.parquet", + ] + with pytest.raises(CatalogOperationError, match="already holds 1 file"): + _ingest(catalog, folder, bucket, sub_path="2026", **args).run() + replaced = _ingest(catalog, folder, bucket, sub_path="2026", conflict_mode="replace", **args) + assert replaced.run().action == "replaced" + assert len(_files(bucket)) == 2 # 2025 untouched + + +def test_parquet_append_refuses_same_named_files(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup() + folder = _folder(tmp_path) + args = {"table_format": "parquet", "table_name": "temps"} + _ingest(catalog, folder, bucket, **args).run() + with pytest.raises(CatalogOperationError, match="same name"): + _ingest(catalog, folder, bucket, conflict_mode="append", **args).run() + + +def test_parquet_registration_is_undone_when_the_upload_fails(tmp_path: Path, bucket: Path) -> None: + catalog, rest, _ = _setup() + + def broken(creds: S3Credentials) -> ObjectStore: + store = _store(bucket)(creds) + store.upload = lambda local, url: (_ for _ in ()).throw(CatalogOperationError("down")) # type: ignore[method-assign] + return store + + job = _ingest(catalog, _folder(tmp_path), bucket, table_format="parquet") + job._store = broken # noqa: SLF001 + with pytest.raises(CatalogOperationError, match="down"): + job.run() + assert (("water", "bwd"), "a") not in rest.generic + + +def test_append_to_the_other_format_is_refused(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup(_rest().add_parquet("water.bwd.a")) + with pytest.raises(CatalogOperationError, match="promote it first"): + _ingest(catalog, _folder(tmp_path), bucket, conflict_mode="append").run() + + +# -- promote --------------------------------------------------------------------------- + + +def test_promote_turns_a_parquet_table_into_iceberg(tmp_path: Path, bucket: Path) -> None: + catalog, rest, engine = _setup() + _ingest( + catalog, _folder(tmp_path, names=("a", "b")), bucket, table_format="parquet", table_name="t" + ).run() + rest.generic[(("water", "bwd"), "t")]["properties"]["wiki"] = "About t" + + outcome = promote( + catalog, "eea_lakehouse.water.bwd.t", store=_store(bucket), token_provider=lambda: None + ) + + assert (outcome.action, outcome.files, outcome.rows) == ("promoted", 2, 5) + assert (("water", "bwd"), "t") not in rest.generic + assert rest.tables[(("water", "bwd"), "t")].properties == {"wiki": "About t"} + assert _files(bucket) == [] + assert any(s.startswith('CREATE TABLE "eea_lakehouse"."water.bwd"."t" AS') for s in engine.sql) + + +def test_promote_restores_the_registration_when_the_load_fails( + tmp_path: Path, bucket: Path +) -> None: + catalog, rest, _ = _setup(fail_on="CREATE TABLE") + _ingest(catalog, _folder(tmp_path), bucket, table_format="parquet", table_name="t").run() + with pytest.raises(CatalogOperationError, match="boom"): + promote( + catalog, "eea_lakehouse.water.bwd.t", store=_store(bucket), token_provider=lambda: None + ) + assert (("water", "bwd"), "t") in rest.generic + assert len(_files(bucket)) == 1 + + +def test_promote_only_a_parquet_table() -> None: + catalog, _, _ = _setup(_rest().add_table("water.bwd.t")) + with pytest.raises(CatalogOperationError, match="an Iceberg table already"): + promote(catalog, "eea_lakehouse.water.bwd.t") + + +# -- credentials ----------------------------------------------------------------------- + +_STS_OK = """ +UAK +USKUST +""" + + +@respx.mock +def test_sts_gives_the_users_own_keys() -> None: + route = respx.post("http://rustfs.test:9000").mock( + return_value=httpx.Response(200, text=_STS_OK) + ) + creds = s3_credentials(SETTINGS, token_provider=lambda: TOKEN) + assert (creds.access_key, creds.session_token, creds.source) == ("UAK", "UST", "sts") + form = route.calls[0].request.content.decode() + assert ( + "Action=AssumeRoleWithWebIdentity" in form + and "RoleSessionName=eea-datalakehouse-ana" in form + ) + + +@respx.mock +def test_without_sts_the_static_key_is_used_and_said_why() -> None: + respx.post("http://rustfs.test:9000").mock( + return_value=httpx.Response(400, text="no OIDC provider") + ) + creds = s3_credentials(SETTINGS, token_provider=lambda: TOKEN) + assert (creds.access_key, creds.source) == ("ak", "static") + assert "no OIDC provider" in creds.note + + +def test_no_storage_credentials_at_all() -> None: + with pytest.raises(CatalogAuthError, match="RUSTFS_ACCESS_KEY"): + s3_credentials(PolarisSettings(uri="http://p"), token_provider=lambda: None) + + +# -- through IngestSession (%ingest) --------------------------------------------------- + +POLARIS_ENV = {"EEA_CATALOG_BACKEND": "polaris", "POLARIS_URI": "http://polaris.test/api/catalog"} + + +def _session( + catalog: PolarisCatalog, bucket: Path, monkeypatch: pytest.MonkeyPatch +) -> IngestSession: + import eea_datalakehouse.dds_ingestion.polaris_ingest as module + + original = module.PolarisIngest.__init__ + + def init(self: PolarisIngest, *args: Any, **kwargs: Any) -> None: + original(self, *args, **{**kwargs, "store": _store(bucket), "token_provider": lambda: None}) + + monkeypatch.setattr(module.PolarisIngest, "__init__", init) + return IngestSession(catalog=lambda: catalog, env=POLARIS_ENV) + + +def test_session_commit_on_polaris( + tmp_path: Path, bucket: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + catalog, rest, _ = _setup() + session = _session(catalog, bucket, monkeypatch) + + session.ingest( + _folder(tmp_path), + "water.bwd", + data_format="parquet", + intent="editable", + upload_mode="proxy", + show_progress=False, + ) + report = session.commit() + + (outcome,) = report.outcomes + assert str(outcome) == "created iceberg table eea_lakehouse.water.bwd.a (5 rows, 1 files)" + notes = outcome.notes # type: ignore[union-attr] + assert notes[0] == ( + "ignored on Polaris (Document Service options): intent='editable', upload_mode='proxy'" + ) + assert notes[1].startswith("uploaded with the shared storage key — no Keycloak token") + assert rest.table_exists(["water", "bwd"], "a") + + +def test_session_commit_failure_on_polaris( + tmp_path: Path, bucket: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + catalog, _, _ = _setup(_rest().add_table("water.bwd.a")) + session = _session(catalog, bucket, monkeypatch) + session.ingest(_folder(tmp_path), "water.bwd", data_format="parquet", show_progress=False) + with pytest.raises(IngestCommitError, match="already exists"): + session.commit() + + +def test_session_diagnose_on_polaris( + tmp_path: Path, + bucket: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + catalog, _, _ = _setup() + session = _session(catalog, bucket, monkeypatch) + session.ingest(_folder(tmp_path), "water.bwd", data_format="parquet") + session.diagnose() + out = capsys.readouterr().out + assert "✓ files: 1 parquet file(s)" in out + assert "✓ target: eea_lakehouse.water.bwd.a (new)" in out + assert "✓ storage: s3://lake/_ingestion/service/" in out + assert _files(bucket) == [] # nothing uploaded + + +def test_session_promote_is_polaris_only() -> None: + with pytest.raises(IngestSessionError, match="promote is for the Polaris catalog"): + IngestSession(env={}).promote("catalog.a.b") From 66c4eccd38357ce0f92a3848f672d8895b7de40e Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 13:14:11 +0100 Subject: [PATCH 11/25] Document the Polaris backend: README, help texts, .env example Seventh step of the Polaris migration. - README: a "Polaris backend" section - how EEA_CATALOG_BACKEND picks the backend, the settings (kernel names with their local-stack/.env fallbacks), and what changes on Polaris for paths, SQL, wiki and tags, publish, %gpkg, %dds and %ingest (table_format, promote); the new modules in the Layout table. - %catalog / %dds / %gpkg help: the backend and the root on Polaris, tags on folders and their spelling, publish through the Document Service and its limits, %dds' Keycloak sign-in and namespace paths, %gpkg's Flight gateway; %catalog list no longer names Dremio's API. - debugger/.env.example: EEA_CATALOG_BACKEND and the Polaris, storage, ingest and Flight variables. Co-Authored-By: Claude Opus 5.5 --- README.md | 76 ++++++++++++++++++++++++ debugger/.env.example | 37 ++++++++++++ src/eea_datalakehouse/notebook/magics.py | 42 +++++++++---- 3 files changed, 143 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 671208f..1287255 100644 --- a/README.md +++ b/README.md @@ -451,6 +451,71 @@ limit=..., srid=..., workers=..., progress=print)` returns a `GpkgReport` listin source, type, SRS and row count. `Catalog.stream_rows(sql, idempotency_key=...)` streams any SELECT as Arrow batches the same way. +## Polaris backend (the EEA Lakehouse stack) + +Dremio is being replaced by [Apache Polaris](https://polaris.apache.org/) — the +Iceberg REST catalog of the EEA Lakehouse stack (`eeadata/EEALakeHouse`, +`local-stack/`). `%catalog`, `%gpkg`, `%dds` and `%ingest` run on either one; +`EEA_CATALOG_BACKEND` picks it (`polaris` or `dremio`; unset: `polaris` when +`POLARIS_URI` is set, else `dremio`, so a Dremio kernel keeps working +unchanged). The commands, their arguments and `%%catalog` stay the same. + +**Settings.** The names the JupyterLab kernel receives; in brackets the +`local-stack/.env` name read when the first is not set (see +`debugger/.env.example` for all of them): + +| Variable | Default | What | +|---|---|---| +| `POLARIS_URI` | `http://localhost:/api/catalog` | Iceberg REST base | +| `POLARIS_CATALOG` [`POLARIS_CATALOG_NAME`] | `eea_lakehouse` | the catalog, and the root of every path | +| `KEYCLOAK_ACCESS_TOKEN` | — | you: Polaris, the Flight gateway and DDS apply your grants | +| `POLARIS_CLIENT_ID` / `_SECRET` [`POLARIS_ROOT_CLIENT_ID` / `_SECRET`] | — | `%catalog` only, when there is no user token | +| `POLARIS_VENDED_CREDENTIALS` | off | per-table storage keys from Polaris | +| `S3_ENDPOINT` [`POLARIS_CATALOG_S3_ENDPOINT_URL` + `_PORT`], `AWS_REGION` | `localhost:9100`, `us-east-1` | the catalog's object store (RustFS) | +| `RUSTFS_ACCESS_KEY` / `_SECRET_KEY` [`POLARIS_CATALOG_S3_ACCESS_KEY_ID` / `_SECRET_ACCESS_KEY`] | — | static storage key (vended credentials off, or no STS) | +| `RUSTFS_ROLE_ARN`, `POLARIS_CATALOG_S3_BUCKET`, `POLARIS_INGEST_S3_PREFIX` | `…/eea-datalakehouse`, namespace's bucket, `_ingestion` | `%ingest`'s own keys and staging area | +| `FLIGHT_HOST` / `FLIGHT_HOST_PORT` | `localhost` / `8815` | Arrow Flight gateway (`%gpkg`) | +| `DDS_BASE_URL` | — | Document Service (`%dds`, `publish`) | + +**What is different on Polaris** + +- **Paths** start with the catalog's name instead of `catalog`: + `eea_lakehouse....draft.stations`. A folder is a + namespace; a table an Iceberg table or a read-only Parquet table; a view an + Iceberg view (its SQL is kept for DuckDB, and for Trino when it reads a table). +- **SQL** runs in the kernel with DuckDB (`iceberg` extension, the catalog + attached as `eea_lakehouse`), as you. Copies cast what Iceberg can't hold + (nanosecond timestamps, unsigned integers, geometry as WKB, …). +- **Wiki and tags** are properties, as the Polaris Navigator keeps them: tags + lower case without `#` (`#public` and `public` are the same tag), and folders + can be tagged too. +- **`publish`** pushes each `#public` view through the Document Service to + `//` in the public store (you must be a publisher). It + is not all or nothing — an error names the views already published — and + `partition_by` / `overwrite=False` are not available. +- **`%gpkg`** reads the rows through the Arrow Flight gateway. +- **`%dds`** signs in with your Keycloak token and stores under the namespace's + path without the catalog name (`eea_lakehouse.water.bwd` → `water/bwd/`). +- **`%ingest`** uploads the files to the catalog's object store — with your + own temporary keys from RustFS STS when available, else the static key (the + commit report says so) — then `table_format` decides the table: + + ```python + # "iceberg" (default): staged, loaded into an Iceberg table (Parquet, CSV or JSON), staging removed + %ingest ingest(folder="./bw_2026", target_catalog_path="water.bwd.draft", data_format="csv", + csv_options={"delimiter": ";"}) + # "parquet": kept as they are, registered as a read-only table; sub_path adds a sub-folder + %ingest ingest(folder="./bw_2026", target_catalog_path="water.bwd.reference", data_format="parquet", + table_format="parquet", table_name="water_temperature", sub_path="2026") + %ingest commit + %ingest promote("eea_lakehouse.water.bwd.reference.water_temperature") # Parquet -> Iceberg, in place + ``` + + `conflict_mode` is `fail`, `append` or `replace`; the target namespace must + exist. `intent`, `upload_mode`, `parallelism`, `multipart` and + `table_definition` belong to the Document Service pipeline and are ignored + (the commit report's notes say so). + ## Notebook facade (`%catalog` / `%ingest`) For interactive use in JupyterLab, `eea_datalakehouse.notebook` registers two line magics @@ -597,6 +662,17 @@ context itself — raises `CatalogSessionError` if none is set yet: | `catalog/rest.py` | `CatalogRestClient` — Dremio's native `/api/v3/catalog` for folders, wiki, and tags (none of which have a SQL/Flight equivalent) | | `catalog/retry_state.py` | persisted memory of stalled attempts, for `retry_pending()` | | `catalog/errors.py` | `CatalogOperationError`, `EngineStartingError` | +| `catalog/backend.py` | `CatalogBackend` — the operations `CatalogSession` needs, implemented by `Catalog` (Dremio) and `PolarisCatalog` | +| `catalog/settings.py` | `EEA_CATALOG_BACKEND` and each backend's settings from the environment (kernel names, `local-stack/.env` fallbacks) | +| `catalog/layout.py` | the dataflow folder layout both backends share (`draft`, `versions`, `reference`, `#public`) | +| `catalog/dremio_publish.py` | Dremio's `publish`: `#public` views to the public S3 source, with backups and rollback | +| `catalog/polaris.py` | `PolarisCatalog` — every `%catalog` verb on Polaris | +| `catalog/polaris_rest.py` | `PolarisRestClient` — Iceberg REST (namespaces, tables, views, properties) and Polaris generic tables | +| `catalog/duckdb_engine.py` | `DuckDbEngine` — the kernel's DuckDB with the Polaris catalog attached | +| `catalog/object_store.py` | `ObjectStore` / `s3_credentials` — the catalog's RustFS from the kernel (the user's STS keys, else the static key) | +| `catalog/dds_public.py` | `PublicDataClient` — the Document Service's public data store, for `publish` on Polaris | +| `geopackage/flight_source.py` | `FlightSource` — `%gpkg` rows from Polaris over the Arrow Flight gateway | +| `dds_ingestion/polaris_ingest.py` | `PolarisIngest` / `promote` — `%ingest` on Polaris: upload, then an Iceberg or a read-only Parquet table | ## Development diff --git a/debugger/.env.example b/debugger/.env.example index c5d034c..aefbbe5 100644 --- a/debugger/.env.example +++ b/debugger/.env.example @@ -11,6 +11,43 @@ SDI_METADATA_DIR= DDS_BASE_URL= DREMIO_BASE_URL= +# --- which catalog %catalog / %gpkg / %dds / %ingest use ---------------------- +# polaris or dremio. Empty: polaris when POLARIS_URI is set, else dremio. +EEA_CATALOG_BACKEND= + +# --- Polaris (the EEA Lakehouse stack's Iceberg catalog) ---------------------- +# Names as the JupyterLab kernel receives them. Each falls back to the name in +# EEALakeHouse's local-stack/.env (in brackets), so that file can be loaded as is. +# Iceberg REST base; without it, http://localhost:/api/catalog. +POLARIS_URI=http://localhost:8181/api/catalog +# The catalog — also the root of every %catalog path [POLARIS_CATALOG_NAME]. +POLARIS_CATALOG=eea_lakehouse +# Who you are: your own Keycloak access token (JupyterHub puts it in the kernel). +# Without it, Polaris client credentials [POLARIS_ROOT_CLIENT_ID / _SECRET] — +# enough for %catalog, not for %gpkg, %dds or publishing, which need a real user. +KEYCLOAK_ACCESS_TOKEN= +POLARIS_CLIENT_ID= +POLARIS_CLIENT_SECRET= +# true: Polaris hands out per-table storage keys and the static key below is unused. +POLARIS_VENDED_CREDENTIALS= +# The catalog's object store (RustFS), host:port or a URL +# [POLARIS_CATALOG_S3_ENDPOINT_URL + _PORT]; default localhost:. +S3_ENDPOINT= +AWS_REGION=us-east-1 +# Static key, used when vended credentials are off, and by %ingest when your own +# keys can't be had from RustFS STS [POLARIS_CATALOG_S3_ACCESS_KEY_ID / _SECRET_ACCESS_KEY]. +RUSTFS_ACCESS_KEY= +RUSTFS_SECRET_KEY= +# %ingest: the role your own temporary keys are asked for, and where files are +# staged before they become an Iceberg table (bucket: default the target +# namespace's own). +RUSTFS_ROLE_ARN=arn:aws:iam:::role/eea-datalakehouse +POLARIS_CATALOG_S3_BUCKET= +POLARIS_INGEST_S3_PREFIX=_ingestion +# %gpkg reads through the Arrow Flight gateway. +FLIGHT_HOST=localhost +FLIGHT_HOST_PORT=8815 + # --- SDI catalogue (eea_datalakehouse.sdi) ------------------------------------ # GeoNetwork base URL; the client appends /srv/api/... Empty means the public # EEA catalogue, https://sdi.eea.europa.eu/catalogue. diff --git a/src/eea_datalakehouse/notebook/magics.py b/src/eea_datalakehouse/notebook/magics.py index 59df34d..f94feb9 100644 --- a/src/eea_datalakehouse/notebook/magics.py +++ b/src/eea_datalakehouse/notebook/magics.py @@ -180,13 +180,14 @@ "use", "Set the current path for every call after this one; path must be a whole, " "absolute path — never relative to the current context, unlike every other " - "verb's path/source_path/target_path. None or '' resets it to 'catalog' (the " - "root). Raises if path doesn't exist in the catalog. See %%catalog to set it " - "once at the top of a cell.", + "verb's path/source_path/target_path. None or '' resets it to the root ('catalog' " + "on Dremio, 'eea_lakehouse' on Polaris). Raises if path doesn't exist in the " + "catalog. See %%catalog to set it once at the top of a cell.", ), ( "get_context", - "Show the current path. A new session starts at 'catalog' (the root); " + "Show the current path. A new session starts at the root ('catalog' on Dremio, " + "'eea_lakehouse' on Polaris); " "use(None)/use('') reset back to it too — None only after an explicit " "set_context(None).", ), @@ -260,7 +261,11 @@ 'by existing fields, in order: a list for every view (partition_by=["year", "country"]), ' 'or a dict for each view\'s own, keyed by its path below the Area ' '(partition_by={"eu_sdg.monitoringsites": ["year"]}; views left out are not ' - "partitioned). A field a view doesn't have raises at once, when publish is called.", + "partitioned). A field a view doesn't have raises at once, when publish is called. " + "On Polaris each #public view goes through the Document Service into the public " + "store at // (DDS_BASE_URL; you must be a publisher): not all " + "or nothing — an error names the views already published — and partition_by / " + "overwrite=False are not available.", ), # -- table ---------------------------------------------------------------- ( @@ -268,7 +273,8 @@ "Show every table/view under path as a JSON array of {type, name} — type TABLE or " "VIEW, name the full dot-separated path: its own, then every child folder's, at any " "depth — walked folder by folder " - "through Dremio's catalog API, no SQL. path may use '.' or '/' separators. " + "through the catalog's own API (Dremio's or Polaris'), no SQL. " + "path may use '.' or '/' separators. " "path may be omitted to list the current context itself — raises " "CatalogSessionError if none is set. Raises CatalogOperationError if path " "doesn't exist.", @@ -313,7 +319,8 @@ ( "set_tags", 'Replace a path\'s tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views ' - "only — raises CatalogOperationError otherwise.", + "only — raises CatalogOperationError otherwise. On Polaris folders take tags too, and " + "tags are kept lower case without '#' ('#public' and 'public' are the same tag).", ), ( "delete_tags", @@ -485,7 +492,10 @@ "\n" "Environment: DDS_BASE_URL — read from the first .env found in the notebook's folder or " "a parent when %dds starts, else from the kernel environment — and a Dremio identity: " - "_DREMIO_USER/_DREMIO_PWD (as %ingest) or DREMIO_USERNAME/DREMIO_TOKEN (as %catalog)." + "_DREMIO_USER/_DREMIO_PWD (as %ingest) or DREMIO_USERNAME/DREMIO_TOKEN (as %catalog). " + "On Polaris (EEA_CATALOG_BACKEND=polaris) your Keycloak sign-in (KEYCLOAK_ACCESS_TOKEN) " + "instead, and the folder is the namespace's path without the catalog name: " + "eea_lakehouse.water.bwd is stored under water/bwd/." ) # Folder names usable bare on a %dds line: `%dds push(METADATA, ...)`. They # win over a notebook variable of the same name, since folder must be one of @@ -570,8 +580,9 @@ def _dds_unknown_folder(line: str, exc: NameError | AttributeError) -> str | Non '(["stations", "sub.areas"]); default all, at any depth. limit caps the rows per table. ' 'srid reprojects every layer (3035 or "EPSG:3035"); default: each keeps its own CRS. ' "filename / output_dir default to .gpkg in the notebook's folder; overwrite=True " - "(default) replaces an existing file. workers tables are streamed from Dremio at once, " - "each over its own Arrow Flight channel.", + "(default) replaces an existing file. workers tables are streamed at once, each over " + "its own Arrow Flight channel — from Dremio, or on Polaris from the EEA Lakehouse " + "Arrow Flight gateway.", ), ] _GPKG_HELP_NOTE = ( @@ -601,7 +612,9 @@ def _dds_unknown_folder(line: str, exc: NameError | AttributeError) -> str | Non " report = %gpkg export()\n" " %dds push(DELIVERABLES, report)\n" "\n" - "Reads with %catalog's connection: DREMIO_BASE_URL / DREMIO_TOKEN. Written with sqlite3, " + "Reads with %catalog's connection: DREMIO_BASE_URL / DREMIO_TOKEN on Dremio; on Polaris " + "the listing comes from Polaris and the rows from the Arrow Flight gateway " + "(FLIGHT_HOST / FLIGHT_HOST_PORT), as you (KEYCLOAK_ACCESS_TOKEN). Written with sqlite3, " "shapely and pyproj (no GDAL)." ) @@ -661,12 +674,17 @@ def _plain_params(func: Any) -> str: # since it applies across every path/source_path/target_path. %ingest help # has no equivalent note. _CATALOG_HELP_NOTE = ( + "Backend: Dremio or Polaris, picked by EEA_CATALOG_BACKEND (unset: Polaris when " + "POLARIS_URI is set). On Polaris paths start with the catalog's name (POLARIS_CATALOG, " + "'eea_lakehouse'), a folder is a namespace, and you are signed in with your Keycloak token " + "(KEYCLOAK_ACCESS_TOKEN; else POLARIS_CLIENT_ID/POLARIS_CLIENT_SECRET).\n" "A new session's context starts at 'catalog' (the root source), not empty — " "use(None)/use('') reset back to it too; only set_context(None) clears it to no " "context at all.\n" "Every path/source_path/target_path (except use's own) is either absolute or " "relative to the current context, once one is set:\n" - " - starts with 'catalog.' (this deployment's one real root source) -> always " + " - starts with 'catalog.' (this deployment's one real root source; 'eea_lakehouse.' " + "on Polaris) -> always " "absolute, used exactly as given, never appended to the context\n" " - '.' or './' alone -> the context itself, exactly as get_context() shows it\n" " - '../' (or a bare '..'), optionally chained ('../../') -> walks up that many " From 95c4372f476ae3b5c6716828a61b193abc7ce67a Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 13:36:49 +0100 Subject: [PATCH 12/25] Fix what the live run against the Polaris stack found Checked against the EEA Lakehouse Kubernetes PoC (Polaris and RustFS port-forwarded) in a scratch namespace, removed afterwards. - Dropping a table purges its data files; a principal Polaris doesn't let purge (DROP_TABLE_WITH_PURGE - root with catalog_admin, here) now gets the table dropped from the catalog instead, so overwrite=True, data_move, delete_table and delete_folder(cascade=True) work for it. Its data files then stay in the bucket. - data_move: when the source can't be dropped, the copy it just made is removed before the error is raised, so a failed move leaves nothing new (the session only undoes steps that finished). - %ingest diagnose: a missing bucket was reported as reachable (listing it finds nothing, like an empty folder); it now checks the bucket. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/object_store.py | 9 +++++ src/eea_datalakehouse/catalog/polaris.py | 26 +++++++++++-- .../dds_ingestion/polaris_ingest.py | 12 +++++- tests/catalog/polaris_fakes.py | 14 ++++++- tests/catalog/test_polaris_data.py | 38 +++++++++++++++++++ tests/dds_ingestion/test_polaris_ingest.py | 22 ++++++++++- 6 files changed, 113 insertions(+), 8 deletions(-) diff --git a/src/eea_datalakehouse/catalog/object_store.py b/src/eea_datalakehouse/catalog/object_store.py index 8cd587d..d3e7178 100644 --- a/src/eea_datalakehouse/catalog/object_store.py +++ b/src/eea_datalakehouse/catalog/object_store.py @@ -175,6 +175,15 @@ def upload(self, local: Path, url: str) -> None: except OSError as exc: raise CatalogOperationError(f"could not upload {local.name} to {url}: {exc}") from exc + def bucket_exists(self, url: str) -> bool: + """Whether the bucket of `url` is there (listing a missing one finds nothing, + which can't be told from an empty folder).""" + bucket, _ = split_url(url) + try: + return bool(self._fs.get_file_info(bucket).type != pafs.FileType.NotFound) + except OSError as exc: + raise CatalogOperationError(f"could not check the bucket {bucket!r}: {exc}") from exc + def list(self, prefix_url: str) -> list[StoredFile]: """Every file under the folder `prefix_url`, at any depth.""" bucket, key = split_url(prefix_url) diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index f458988..999d890 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -489,7 +489,7 @@ def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str for name in self.rest.list_views(namespace): self.rest.drop_view(namespace, name) for name in self.rest.list_tables(namespace): - self.rest.drop_table(namespace, name) + self._drop_table(namespace, name) for name in self.rest.list_generic(namespace): self.rest.drop_generic(namespace, name) self.rest.drop_namespace(namespace) @@ -661,12 +661,24 @@ def _drop(self, namespace: list[str], name: str, kind: EntryType) -> None: """Drop `name` in `namespace`, which is a `kind`: a table with its data files, a view, or a read-only Parquet table's registration (its files stay).""" if kind == "table": - self.rest.drop_table(namespace, name) + self._drop_table(namespace, name) elif kind == "view": self.rest.drop_view(namespace, name) else: self.rest.drop_generic(namespace, name) + def _drop_table(self, namespace: list[str], name: str) -> None: + """Drop an Iceberg table with its data files (purge). A caller Polaris doesn't + allow to purge (``DROP_TABLE_WITH_PURGE`` — e.g. a principal with + catalog_admin only) gets the table dropped from the catalog instead; its data + files then stay in the bucket.""" + try: + self.rest.drop_table(namespace, name) + except CatalogAuthError as exc: + if "PURGE" not in str(exc).upper(): + raise + self.rest.drop_table(namespace, name, purge=False) + def _prepare_target( self, source_path: str, @@ -750,7 +762,15 @@ def datamove( f"target {target!r} does not exist after the copy — the move did not complete" ) namespace, name = self._split(source_path) - self._drop(namespace, name, source_kind) + try: + self._drop(namespace, name, source_kind) + except Exception as exc: + # The source stays, so the copy goes: a failed move leaves nothing new. + try: + self.drop_entry(target, idempotency_key=idempotency_key) + except Exception as cleanup_error: # noqa: BLE001 — the original failure is raised + exc.add_note(f"the copy {target!r} could not be removed: {cleanup_error}") + raise return target def _source_entry(self, path: str) -> EntryType: diff --git a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py index dc2c34d..c396c4b 100644 --- a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py +++ b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py @@ -487,8 +487,16 @@ def report(passed: bool | None, name: str, detail: str) -> None: else f"{self.namespace_location(plan.namespace)}/{plan.table}/" ) creds = self._credentials() - self._store(creds).list(where) - report(True, "storage", f"{where} reachable ({creds.source} keys)") + store = self._store(creds) + if not store.bucket_exists(where): + report( + False, + "storage", + f"the bucket of {where} does not exist (POLARIS_CATALOG_S3_BUCKET?)", + ) + else: + store.list(where) + report(True, "storage", f"{where} reachable ({creds.source} keys)") except (CatalogOperationError, CatalogAuthError) as exc: report(False, "storage", str(exc)) return ok diff --git a/tests/catalog/polaris_fakes.py b/tests/catalog/polaris_fakes.py index d01da84..942e4b3 100644 --- a/tests/catalog/polaris_fakes.py +++ b/tests/catalog/polaris_fakes.py @@ -12,6 +12,7 @@ from dataclasses import dataclass, field from typing import Any +from eea_datalakehouse.catalog.errors import CatalogAuthError from eea_datalakehouse.catalog.polaris_rest import PolarisHttpError, PolarisNotFoundError Key = tuple[str, ...] @@ -49,6 +50,10 @@ def __init__(self, catalog: str = "eea_lakehouse") -> None: self.generic: dict[tuple[Key, str], dict[str, Any]] = {} self.calls: list[tuple[Any, ...]] = [] self.closed = False + # Like a principal with catalog_admin only: Polaris refuses DROP_TABLE_WITH_PURGE. + self.refuse_purge = False + # Table names whose drop fails (any mode). + self.undroppable: set[str] = set() # -- building a catalog for a test ------------------------------------- @@ -182,7 +187,14 @@ def load_view(self, namespace: Sequence[str], name: str) -> dict[str, Any]: return {"properties": dict(entry.properties), **entry.metadata} def drop_table(self, namespace: Sequence[str], name: str, *, purge: bool = True) -> None: - self.calls.append(("drop_table", tuple(namespace), name)) + if purge and self.refuse_purge: + raise CatalogAuthError( + "no permission for this in Polaris: Principal 'root' is not authorized for op " + "DROP_TABLE_WITH_PURGE" + ) + if name in self.undroppable: + raise CatalogAuthError(f"no permission to drop {name}") + self.calls.append(("drop_table", tuple(namespace), name, purge)) if self.tables.pop((tuple(namespace), name), None) is None: raise PolarisNotFoundError(f"Table does not exist: {name}") diff --git a/tests/catalog/test_polaris_data.py b/tests/catalog/test_polaris_data.py index 4355a3b..e88df4a 100644 --- a/tests/catalog/test_polaris_data.py +++ b/tests/catalog/test_polaris_data.py @@ -392,3 +392,41 @@ def test_session_data_move_and_create_view() -> None: assert rest.table_exists(["water", "bathing", "bwd", "draft"], "stations_old") assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") assert rest.view_exists(["water", "bathing", "bwd"], "stations_view") + + +# -- found against the live stack ------------------------------------------------------------ + + +def test_a_refused_purge_drops_the_table_without_it() -> None: + """A principal with catalog_admin only may drop a table, but not purge its files.""" + catalog, rest, _ = _setup() + rest.refuse_purge = True + + catalog.datacopy( + f"{AREA}.draft.stations", f"{AREA}.draft.latest", overwrite=True, idempotency_key=K + ) + catalog.datacopy( + f"{AREA}.draft.stations", f"{AREA}.draft.latest", overwrite=True, idempotency_key=K + ) + catalog.deletetable(f"{AREA}.draft.latest", idempotency_key=K) + + assert ("drop_table", ("water", "bathing", "bwd", "draft"), "latest", False) in rest.calls + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "latest") + + +def test_other_refusals_are_not_retried_without_purge() -> None: + catalog, rest, _ = _setup() + rest.undroppable.add("stations") + with pytest.raises(CatalogOperationError, match="no permission to drop stations"): + catalog.deletetable(f"{AREA}.draft.stations", idempotency_key=K) + + +def test_a_move_whose_source_cannot_be_dropped_leaves_no_copy() -> None: + catalog, rest, _ = _setup() + rest.undroppable.add("stations") + + with pytest.raises(CatalogOperationError, match="no permission to drop stations"): + catalog.datamove(f"{AREA}.draft.stations", f"{AREA}.draft.moved", idempotency_key=K) + + assert rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "moved") diff --git a/tests/dds_ingestion/test_polaris_ingest.py b/tests/dds_ingestion/test_polaris_ingest.py index f62341e..08b1db1 100644 --- a/tests/dds_ingestion/test_polaris_ingest.py +++ b/tests/dds_ingestion/test_polaris_ingest.py @@ -77,7 +77,8 @@ def execute(self, sql: str) -> None: @pytest.fixture def bucket(tmp_path: Path) -> Path: root = tmp_path / "s3" - root.mkdir() + for name in ("lake", "staging"): # the buckets the tests use + (root / name).mkdir(parents=True) return root @@ -220,7 +221,7 @@ def test_iceberg_append_and_replace(tmp_path: Path, bucket: Path) -> None: ) assert _ingest(catalog, folder, bucket, conflict_mode="replace").run().action == "replaced" - assert ("drop_table", ("water", "bwd"), "a") in rest.calls + assert ("drop_table", ("water", "bwd"), "a", True) in rest.calls def test_existing_table_fails_before_any_upload(tmp_path: Path, bucket: Path) -> None: @@ -486,3 +487,20 @@ def test_session_diagnose_on_polaris( def test_session_promote_is_polaris_only() -> None: with pytest.raises(IngestSessionError, match="promote is for the Polaris catalog"): IngestSession(env={}).promote("catalog.a.b") + + +def test_diagnose_reports_a_missing_bucket( + tmp_path: Path, + bucket: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Found against the live stack: an empty listing of a missing bucket read as reachable.""" + catalog, _, _ = _setup() + catalog._settings = PolarisSettings( # noqa: SLF001 + uri=SETTINGS.uri, s3_access_key="ak", s3_secret_key="sk", ingest_bucket="no_such_bucket" + ) + session = _session(catalog, bucket, monkeypatch) + session.ingest(_folder(tmp_path), "water.bwd", data_format="parquet") + session.diagnose() + assert "✗ storage: the bucket of s3://no_such_bucket/" in capsys.readouterr().out From 55b838217b671f0b3d1056d7accc5f132a527e07 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 13:39:45 +0100 Subject: [PATCH 13/25] Trust the stack's own CA for Polaris, DuckDB and DDS behind its gateway The Kubernetes PoC exposes Polaris (and DDS, Keycloak, Trino) through an HTTPS gateway whose certificate is signed by the stack's own CA. - LAKEHOUSE_CA_FILE (fallback TRINO_CA_FILE, where JupyterLab mounts the stack's CA): PolarisSettings.ca_file. PolarisRestClient, the DDS public data client and %dds' DocumentsClient verify against it; DuckDB gets SET ca_cert_file plus enable_server_cert_verification, so its Iceberg REST calls are checked too. - The gateway blocks Polaris' own token endpoint: a 404 there now says to sign in with KEYCLOAK_ACCESS_TOKEN (or reach Polaris directly) instead of "refused the client credentials". - README settings table and debugger/.env.example document it. Checked live: with the CA, httpx and DuckDB reach Polaris through the gateway (401 without a real token); without it, TLS verification fails. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + debugger/.env.example | 4 ++++ src/eea_datalakehouse/catalog/dds_public.py | 3 ++- src/eea_datalakehouse/catalog/duckdb_engine.py | 4 ++++ src/eea_datalakehouse/catalog/polaris.py | 6 ++++-- src/eea_datalakehouse/catalog/polaris_rest.py | 10 ++++++++-- src/eea_datalakehouse/catalog/settings.py | 18 ++++++++++++++++++ src/eea_datalakehouse/dds_documents/client.py | 3 ++- src/eea_datalakehouse/dds_documents/session.py | 12 ++++++++++-- tests/catalog/test_duckdb_engine.py | 10 ++++++++++ tests/catalog/test_polaris_rest.py | 7 +++++++ tests/catalog/test_settings.py | 18 ++++++++++++++++++ 12 files changed, 88 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 1287255..8d35baf 100644 --- a/README.md +++ b/README.md @@ -476,6 +476,7 @@ unchanged). The commands, their arguments and `%%catalog` stay the same. | `RUSTFS_ROLE_ARN`, `POLARIS_CATALOG_S3_BUCKET`, `POLARIS_INGEST_S3_PREFIX` | `…/eea-datalakehouse`, namespace's bucket, `_ingestion` | `%ingest`'s own keys and staging area | | `FLIGHT_HOST` / `FLIGHT_HOST_PORT` | `localhost` / `8815` | Arrow Flight gateway (`%gpkg`) | | `DDS_BASE_URL` | — | Document Service (`%dds`, `publish`) | +| `LAKEHOUSE_CA_FILE` [`TRINO_CA_FILE`] | the system's CAs | CA of the stack's HTTPS gateway (Polaris, DuckDB and DDS behind it) | **What is different on Polaris** diff --git a/debugger/.env.example b/debugger/.env.example index aefbbe5..78e869c 100644 --- a/debugger/.env.example +++ b/debugger/.env.example @@ -20,6 +20,10 @@ EEA_CATALOG_BACKEND= # EEALakeHouse's local-stack/.env (in brackets), so that file can be loaded as is. # Iceberg REST base; without it, http://localhost:/api/catalog. POLARIS_URI=http://localhost:8181/api/catalog +# The CA of the stack's HTTPS gateway when it has its own (Kubernetes PoC: the +# lakehouse-ca secret; JupyterLab mounts it at /etc/lakehouse-ca/ca.crt +# [TRINO_CA_FILE]). Trusted for Polaris, DuckDB and DDS. Empty: the system's CAs. +LAKEHOUSE_CA_FILE= # The catalog — also the root of every %catalog path [POLARIS_CATALOG_NAME]. POLARIS_CATALOG=eea_lakehouse # Who you are: your own Keycloak access token (JupyterHub puts it in the kernel). diff --git a/src/eea_datalakehouse/catalog/dds_public.py b/src/eea_datalakehouse/catalog/dds_public.py index e12891c..76af959 100644 --- a/src/eea_datalakehouse/catalog/dds_public.py +++ b/src/eea_datalakehouse/catalog/dds_public.py @@ -51,6 +51,7 @@ def __init__( token_provider: Callable[[], str | None] = user_token, http: httpx.Client | None = None, timeout: float = DEFAULT_TIMEOUT, + verify: str | bool = True, ) -> None: if not base_url: raise CatalogOperationError( @@ -59,7 +60,7 @@ def __init__( self._base_url = base_url.rstrip("/") self._token_provider = token_provider self._owns_http = http is None - self._http = http or httpx.Client(timeout=timeout) + self._http = http or httpx.Client(timeout=timeout, verify=verify) def __repr__(self) -> str: return f"PublicDataClient(base_url={self._base_url!r})" diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py index c47a286..373bf33 100644 --- a/src/eea_datalakehouse/catalog/duckdb_engine.py +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -153,6 +153,10 @@ def setup_statements(self) -> list[str]: """The secrets and the ATTACH that `connection` runs, in order.""" settings = self._settings statements: list[str] = [] + if settings.ca_file: + # The stack's own CA (an HTTPS gateway in front of Polaris): trust it, and check. + statements.append(f"SET ca_cert_file = {quote_literal(settings.ca_file)}") + statements.append("SET enable_server_cert_verification = true") if not settings.vended_credentials: scheme, _, host = settings.s3_endpoint.partition("://") key = ( diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index 999d890..ecc49e8 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -27,7 +27,7 @@ from .layout import NOT_PUBLISHED, PUBLIC_TAG from .operations import TableInfo, VersionResult from .polaris_rest import PARQUET_FORMAT, PolarisHttpError, PolarisRestClient -from .settings import PolarisSettings +from .settings import PolarisSettings, tls_verify Kind = Literal["TABLE", "VIEW"] EntryType = Literal["table", "view", "parquet"] @@ -983,7 +983,9 @@ def _plan_version( def public(self) -> PublicDataClient: """The Document Service's public-data client (built on first use).""" if self._public is None: - self._public = PublicDataClient(self._settings.dds_base_url) + self._public = PublicDataClient( + self._settings.dds_base_url, verify=tls_verify(self._settings.ca_file) + ) return self._public def public_folder(self, path: str) -> str: diff --git a/src/eea_datalakehouse/catalog/polaris_rest.py b/src/eea_datalakehouse/catalog/polaris_rest.py index c2ac66b..794d35a 100644 --- a/src/eea_datalakehouse/catalog/polaris_rest.py +++ b/src/eea_datalakehouse/catalog/polaris_rest.py @@ -36,7 +36,7 @@ import httpx from .errors import CatalogAuthError, CatalogOperationError -from .settings import PolarisSettings, user_token +from .settings import PolarisSettings, tls_verify, user_token SEP = "\x1f" # between nested namespace parts in Iceberg REST URLs DEFAULT_TIMEOUT = 60.0 @@ -109,7 +109,7 @@ def __init__( ) -> None: self._settings = settings self._owns_http = http is None - self._http = http or httpx.Client(timeout=timeout) + self._http = http or httpx.Client(timeout=timeout, verify=tls_verify(settings.ca_file)) self._token_provider = token_provider self._minted: tuple[str, float] | None = None # (token, renew after) self._prefix: str | None = None @@ -157,6 +157,12 @@ def _mint(self) -> str: raise CatalogOperationError( f"Polaris can't be reached at {settings.uri}: {exc}" ) from exc + if response.status_code == 404: + raise CatalogAuthError( + f"{settings.uri} does not issue Polaris client-credential tokens (a gateway in " + "front of Polaris may block them): sign in with KEYCLOAK_ACCESS_TOKEN, or reach " + "Polaris directly" + ) if response.status_code >= 400: raise CatalogAuthError( f"Polaris refused the client credentials of {settings.client_id!r}: " diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py index 3b41145..663d31c 100644 --- a/src/eea_datalakehouse/catalog/settings.py +++ b/src/eea_datalakehouse/catalog/settings.py @@ -65,6 +65,20 @@ def polaris_catalog_name(environ: Mapping[str, str] | None = None) -> str: return _get(env, "POLARIS_CATALOG", "POLARIS_CATALOG_NAME") or DEFAULT_POLARIS_CATALOG +def lakehouse_ca_file(environ: Mapping[str, str] | None = None) -> str | None: + """The CA certificate that signs the lakehouse's HTTPS endpoints (its gateway, Trino), + when they use their own: ``LAKEHOUSE_CA_FILE``, else ``TRINO_CA_FILE`` (where the + stack mounts it in JupyterLab: ``/etc/lakehouse-ca/ca.crt``). None: the system's.""" + env = os.environ if environ is None else environ + path = _get(env, "LAKEHOUSE_CA_FILE", "TRINO_CA_FILE") + return os.path.expanduser(path) if path else None + + +def tls_verify(ca_file: str | None) -> str | bool: + """What httpx's ``verify`` takes: the CA file when there is one, else the system's.""" + return ca_file or True + + def user_token(environ: Mapping[str, str] | None = None) -> str | None: """The signed-in user's Keycloak access token (``KEYCLOAK_ACCESS_TOKEN``), or None. @@ -128,6 +142,8 @@ class PolarisSettings: ``localhost``/``8815``. - ``dds_base_url``: ``DDS_BASE_URL`` — the Document Service, which `publish` sends public files through. + - ``ca_file``: ``LAKEHOUSE_CA_FILE`` (``TRINO_CA_FILE``) — the CA of the stack's + HTTPS gateway, when it has its own; trusted for Polaris, DuckDB and DDS. The user's own identity, ``KEYCLOAK_ACCESS_TOKEN``, is not stored here — see `user_token`, read on every request. @@ -148,6 +164,7 @@ class PolarisSettings: flight_host: str = "localhost" flight_port: int = DEFAULT_FLIGHT_PORT dds_base_url: str = "" + ca_file: str | None = None @property def root(self) -> str: @@ -199,4 +216,5 @@ def from_env(cls, environ: Mapping[str, str] | None = None) -> PolarisSettings: flight_host=_get(env, "FLIGHT_HOST") or "localhost", flight_port=port, dds_base_url=_get(env, "DDS_BASE_URL").rstrip("/"), + ca_file=lakehouse_ca_file(env), ) diff --git a/src/eea_datalakehouse/dds_documents/client.py b/src/eea_datalakehouse/dds_documents/client.py index 6568e15..58bae10 100644 --- a/src/eea_datalakehouse/dds_documents/client.py +++ b/src/eea_datalakehouse/dds_documents/client.py @@ -85,6 +85,7 @@ def __init__( keycloak_token: str | None = None, timeout: float = DEFAULT_TIMEOUT, http_client: httpx.Client | None = None, + verify: str | bool = True, ) -> None: """Signs in with the Dremio PAT in `creds` (``Authorization: Bearer``), or — on the Polaris stack — with the user's Keycloak token (``X-Keycloak-Token``, @@ -94,7 +95,7 @@ def __init__( raise ValueError("DocumentsClient needs either creds or keycloak_token, not both") self._base_url = base_url.rstrip("/") self._owns_client = http_client is None - self._http = http_client or httpx.Client(timeout=timeout) + self._http = http_client or httpx.Client(timeout=timeout, verify=verify) self._auth_headers = ( {"X-Keycloak-Token": keycloak_token} if keycloak_token is not None diff --git a/src/eea_datalakehouse/dds_documents/session.py b/src/eea_datalakehouse/dds_documents/session.py index ede2789..eeb4903 100644 --- a/src/eea_datalakehouse/dds_documents/session.py +++ b/src/eea_datalakehouse/dds_documents/session.py @@ -41,7 +41,13 @@ import httpx -from ..catalog.settings import backend_name, polaris_catalog_name, user_token +from ..catalog.settings import ( + backend_name, + lakehouse_ca_file, + polaris_catalog_name, + tls_verify, + user_token, +) from ..dds_ingestion.credentials import ( ENV_BASE_URL, ENV_PWD, @@ -327,7 +333,9 @@ def _dds(self) -> DdsController: "%dds on Polaris signs in with your Keycloak token: " "KEYCLOAK_ACCESS_TOKEN is not set in the kernel environment" ) - client = DocumentsClient(url, keycloak_token=token) + client = DocumentsClient( + url, keycloak_token=token, verify=tls_verify(lakehouse_ca_file(env)) + ) else: client = DocumentsClient(url, load_dds_creds(env)) self._controller = DdsController(client) diff --git a/tests/catalog/test_duckdb_engine.py b/tests/catalog/test_duckdb_engine.py index b68c4cd..867b5bc 100644 --- a/tests/catalog/test_duckdb_engine.py +++ b/tests/catalog/test_duckdb_engine.py @@ -184,3 +184,13 @@ def test_query_refusals_are_auth_errors() -> None: engine, _ = _engine(connection=FakeConnection(fail_on={"SELECT": "HTTP 403 Forbidden"})) with pytest.raises(CatalogAuthError, match="no permission"): engine.execute("SELECT 1") + + +def test_the_stacks_own_ca_is_trusted_and_checked() -> None: + engine, _ = _engine(PolarisSettings(uri="https://gateway/api/catalog", ca_file="/ca.crt")) + statements = engine.setup_statements() + assert statements[:2] == [ + "SET ca_cert_file = '/ca.crt'", + "SET enable_server_cert_verification = true", + ] + assert not any("ca_cert_file" in s for s in _engine()[0].setup_statements()) diff --git a/tests/catalog/test_polaris_rest.py b/tests/catalog/test_polaris_rest.py index 39bd4c4..94f2bfb 100644 --- a/tests/catalog/test_polaris_rest.py +++ b/tests/catalog/test_polaris_rest.py @@ -465,3 +465,10 @@ def test_generic_tables_not_offered_list_as_empty(status: int) -> None: return_value=httpx.Response(status) ) assert _client().list_generic(["water"]) == [] + + +@respx.mock +def test_a_gateway_that_blocks_client_credential_tokens_says_so() -> None: + respx.post(f"{URI}/v1/oauth/tokens").mock(return_value=httpx.Response(404)) + with pytest.raises(CatalogAuthError, match="does not issue Polaris client-credential tokens"): + _client(token=None).token() diff --git a/tests/catalog/test_settings.py b/tests/catalog/test_settings.py index 6663b60..c103894 100644 --- a/tests/catalog/test_settings.py +++ b/tests/catalog/test_settings.py @@ -143,3 +143,21 @@ def test_bad_flight_port() -> None: def test_user_token() -> None: assert user_token({}) is None assert user_token({"KEYCLOAK_ACCESS_TOKEN": " jwt "}) == "jwt" + + +def test_lakehouse_ca_file() -> None: + from eea_datalakehouse.catalog.settings import lakehouse_ca_file, tls_verify + + assert lakehouse_ca_file({}) is None + assert lakehouse_ca_file({"TRINO_CA_FILE": "/etc/lakehouse-ca/ca.crt"}) == ( + "/etc/lakehouse-ca/ca.crt" + ) + assert lakehouse_ca_file({"LAKEHOUSE_CA_FILE": "/a.crt", "TRINO_CA_FILE": "/b.crt"}) == "/a.crt" + assert ( + PolarisSettings.from_env( + {"POLARIS_URI": "https://g", "LAKEHOUSE_CA_FILE": "/a.crt"} + ).ca_file + == "/a.crt" + ) + assert tls_verify(None) is True + assert tls_verify("/a.crt") == "/a.crt" From 4315571a28895db20f315a4c76de5b5e27762592 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 13:43:47 +0100 Subject: [PATCH 14/25] Adapt the %catalog smoke-test notebook to Polaris debugger/test_catalog_magic.ipynb now tests the magics against the Polaris stack in debugger/.env, inside one scratch folder (eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test) that the Cleanup section removes, with any data files left behind: - the env cell shows the backend, Polaris URI, CA and who is signed in; every check goes through an independent PolarisCatalog; - folders, use/relative paths, wiki with meta tags, tags, a failed call; - data_copy / schema / create_view / overwrite / data_move into a folder; - a dataflow release: draft_to_version and update_latest_release; - %ingest: Iceberg from Parquet and CSV, a read-only Parquet table with sub_path, diagnose, commit and promote (on generated files); - %dds target/push/list, %gpkg export (needs the Flight gateway); - publish left commented out: it writes to the real public store. The ad-hoc cells that ran draft_to_version, update_latest_release and publish on real dataflows are gone (see git history). Executed end to end against the 172.28.1.6 cluster (root client over a port-forward): everything passes except %dds and %gpkg, which need a Keycloak token (and %gpkg a Flight gateway the cluster doesn't have). Co-Authored-By: Claude Opus 5.5 --- debugger/test_catalog_magic.ipynb | 2053 +++++------------------------ 1 file changed, 350 insertions(+), 1703 deletions(-) diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index deee183..6a34d01 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -4,39 +4,34 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# `%catalog` smoke test — immediate execution, no commit\n", + "# `%catalog` smoke test on Polaris — immediate execution, no commit\n", "\n", - "A functional test notebook for the `%catalog` magic (`src/eea_datalakehouse/notebook/magics.py`),\n", - "meant to be run against this project's own debug/local Dremio stack (`debugger/.env` — see\n", - "`debugger/debug_run.py`, whose `run_createfolder`/`run_setmeta2wiki`/... functions exercise the\n", - "same underlying `Catalog` calls the hard way). Unlike `docs/notebooks/catalog_session_example.ipynb`\n", - "(a documentation walkthrough), this one exists to actually **prove** the behaviour: every\n", - "`%catalog` call below is followed by an independent check, through a fresh `Catalog` client the\n", - "magic never touched, that the change already landed — no separate `%catalog commit` anywhere in\n", - "this notebook.\n", + "A functional test notebook for the notebook magics (`src/eea_datalakehouse/notebook/magics.py`)\n", + "against the EEA Lakehouse **Polaris** stack configured in `debugger/.env`\n", + "(`EEA_CATALOG_BACKEND=polaris`). Every `%catalog` call below is followed by an independent\n", + "check, through a fresh `PolarisCatalog` client the magic never touched, that the change has\n", + "already landed — no `%catalog commit` anywhere.\n", "\n", - "**This writes to the catalog for real** (a scratch folder, cleaned up at the end — see\n", - "\"Cleanup\"). Run from this project's own dev environment (`pip install -e \".[dev]\"`), which already\n", - "includes the `notebook` extra; `debugger/.env` must be filled in (copy from `.env.example`) and\n", - "the stack it points at reachable." - ] + "Everything is written under one scratch folder (`TEST_FOLDER`, below) and removed in\n", + "**Cleanup**; the only existing table touched is `SOURCE_TABLE`, and only read.\n", + "\n", + "**Before running**\n", + "\n", + "1. Port-forward RustFS (the catalog's object store) — the command is at the top of\n", + " `debugger/.env`.\n", + "2. Paste a fresh Keycloak access token into `KEYCLOAK_ACCESS_TOKEN` in `debugger/.env`\n", + " (Polaris through the gateway accepts nothing else; tokens expire after a few minutes) —\n", + " or switch `POLARIS_URI` to a port-forwarded Polaris to run as the root client\n", + " (`%dds` then can't run).\n", + "3. Restart the kernel after changing `debugger/.env`: it is read once, in the next cell." + ], + "id": "64fef81a" }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "env file /home/esparza/EEADatahub/EEALakeHouse.python/debugger/.env\n", - "DREMIO_BASE_URL https://dremio.eea.europa.eu:9047/\n", - "DREMIO_USERNAME esparza@discomap.eea.europa.eu\n", - "DREMIO_TOKEN set\n" - ] - } - ], + "outputs": [], "source": [ "import os\n", "from pathlib import Path\n", @@ -44,9 +39,8 @@ "\n", "def _find_debugger_env(start: Path | None = None) -> Path:\n", " \"\"\"`debugger/.env` — located by walking up from this notebook rather than\n", - " hardcoded, so it works wherever Jupyter's cwd happens to be (same\n", - " reasoning as `03_ingest.ipynb`'s `_repo_root()`). Identified by sitting\n", - " next to `debug_run.py`, not just any `.env`.\"\"\"\n", + " hardcoded, so it works wherever Jupyter's cwd happens to be. Identified by\n", + " sitting next to `debug_run.py`, not just any `.env`.\"\"\"\n", " here = start or Path.cwd()\n", " for candidate in (here, *here.parents):\n", " if (candidate / \"debug_run.py\").exists() and (candidate / \".env\").exists():\n", @@ -65,393 +59,283 @@ " _key, _, _value = _line.partition(\"=\")\n", " os.environ.setdefault(_key.strip(), _value.strip())\n", "\n", - "# %catalog reads DREMIO_USERNAME (see notebook/magics.py's _build_catalog_session);\n", - "# debugger/.env uses the shorter DREMIO_USER — same bridging debug_run.py itself\n", - "# does for the DDS side (_DREMIO_USER/_DREMIO_PWD).\n", - "os.environ.setdefault(\"DREMIO_USERNAME\", os.environ.get(\"DREMIO_USER\", \"\"))\n", + "from eea_datalakehouse.catalog.settings import PolarisSettings, backend_name, user_token\n", "\n", - "print(f\"env file {ENV_PATH}\")\n", - "print(f\"DREMIO_BASE_URL {os.environ.get('DREMIO_BASE_URL') or ''}\")\n", - "print(f\"DREMIO_USERNAME {os.environ.get('DREMIO_USERNAME') or ''}\")\n", - "print(f\"DREMIO_TOKEN {'set' if os.environ.get('DREMIO_TOKEN') else ''}\")\n" - ] + "SETTINGS = PolarisSettings.from_env()\n", + "print(f\"env file {ENV_PATH}\")\n", + "print(f\"backend {backend_name()}\")\n", + "print(f\"POLARIS_URI {SETTINGS.uri}\")\n", + "print(f\"catalog (root) {SETTINGS.catalog}\")\n", + "print(f\"CA file {SETTINGS.ca_file or ''}\")\n", + "print(f\"signed in as {'your Keycloak token' if user_token() else 'Polaris client ' + repr(SETTINGS.client_id) if SETTINGS.client_id else ''}\")\n", + "print(f\"object store {SETTINGS.s3_endpoint}\")\n", + "print(f\"DDS {SETTINGS.dds_base_url or ''}\")\n", + "assert backend_name() == \"polaris\", \"set EEA_CATALOG_BACKEND=polaris in debugger/.env\"\n", + "if SETTINGS.uri.startswith(\"https://\") and not user_token():\n", + " print(\"\\n!! no KEYCLOAK_ACCESS_TOKEN: Polaris behind the gateway will refuse every call\")" + ], + "id": "3f7af2e9" }, { "cell_type": "code", - "execution_count": 3, - "id": "c5e8b5d6", + "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "import eea_datalakehouse.notebook # registers %catalog/%ingest — no %load_ext needed" - ] + "import eea_datalakehouse.notebook # registers %catalog/%ingest/%dds/%gpkg/%sdi — no %load_ext needed" + ], + "id": "bdfc96fa" }, { "cell_type": "markdown", - "id": "415930da", "metadata": {}, "source": [ "## Help\n", "\n", - "Sanity check before anything else: `%catalog help()` should print the command table without\n", - "needing any of the environment above (it's answered before a session is built)." - ] + "`%catalog help` prints the command table without connecting to anything." + ], + "id": "36010708" }, { "cell_type": "code", - "execution_count": 4, - "id": "8efb16ed", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "%catalog methods — usage: %catalog data_copy(\"a.b\", \"c.d\") | %catalog set_tags(\"a.b\", [\"reviewed\"]) (each call runs immediately)\n", - "A new session's context starts at 'catalog' (the root source), not empty — use(None)/use('') reset back to it too; only set_context(None) clears it to no context at all.\n", - "Every path/source_path/target_path (except use's own) is either absolute or relative to the current context, once one is set:\n", - " - starts with 'catalog.' (this deployment's one real root source) -> always absolute, used exactly as given, never appended to the context\n", - " - '.' or './' alone -> the context itself, exactly as get_context() shows it\n", - " - '../' (or a bare '..'), optionally chained ('../../') -> walks up that many levels of the context first, then appends whatever's left, if anything\n", - " - '.name', or a bare 'name' with no leading '.' at all -> both mean relative to the context; the dot is optional sugar, not what makes it relative\n", - "Only use() ever changes the context — no other call does, even one that fully resolved an absolute path.\n" - ] - }, - { - "data": { - "text/html": [ - "
CommandParametersDescription
usepathSet the current path for every call after this one; path must be a whole, absolute path — never relative to the current context, unlike every other verb's path/source_path/target_path. None or '' resets it to 'catalog' (the root). Raises if path doesn't exist in the catalog. See %%catalog to set it once at the top of a cell.
get_contextShow the current path. A new session starts at 'catalog' (the root); use(None)/use('') reset back to it too — None only after an explicit set_context(None).
data_copysource_path, target_path, overwrite=False, create_target_folder=FalseCopy source_path to target_path. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. A target_path ending in / is a folder, not the table: the folder is created first if it doesn't exist (every missing level), and the table lands inside it under the source's own name — data_copy("draft.t", "archive/2027/") makes archive.2027.t; "./" is the context itself; undo removes the folders it created. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
data_movesource_path, target_path, overwrite=False, create_target_folder=FalseMove source_path to target_path, always as a TABLE (use create_view for a view). overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. A target_path ending in / is a folder, not the table: the folder is created first if it doesn't exist (every missing level), and the table lands inside it under the source's own name — data_copy("draft.t", "archive/2027/") makes archive.2027.t; "./" is the context itself; undo removes the folders it created. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
create_versionsource_path, version_name, tables=None, target_path=None, overwrite=False, create_target_folder=TrueCopy the listed tables from source_path into a new folder target_path.version_name (as CREATE TABLE snapshots, keeping each table's sub-folders). source_path and version_name must not be blank. tables omitted or empty copies everything under source_path. Each entry is a table or a folder (= every table under it), named as listed under source_path or as list() shows them. target_path omitted means the current context — use() picks where versions go; a missing target_path is created unless create_target_folder=False. Reference/vocabulary tables (a folder named reference(s)/vocabulary(ies) in the path) and views are skipped; the report's notes say which. An existing version folder is an error unless overwrite=True (replaces the listed tables, keeps the rest).
draft_to_versionversion_name, tables=None, overwrite=Falsecreate_version from the dataflow's draft folder, with no paths to type: the source is the draft folder the context is in (or the draft folder inside the context), the target is draft's parent.versions.version_name (versions is created if missing). tables as in create_version: omitted or empty copies everything in draft. Unlike create_version, views in draft are not skipped: each is copied into the version as a table (a snapshot of what it returns); the report's notes say which.
update_latest_releaseversion_name, overwrite=TrueCreate a view at the Area's root for every table in versions.version_name, keeping its sub-folders (versions.v1.a.t gets the view a.t; missing folders are created). The context must be the Area folder — one with draft and versions folders just below it, typically catalog.<domain>.<subdomain>.<area> — and versions.version_name must exist — raises at once otherwise. Views in the version are skipped. An existing view is dropped and recreated over the version (overwrite=True, the default; not undoable) — overwrite=False makes it an error instead; an existing table is always an error. Each view is tagged #public, and #public is removed from every table/view under versions, so only the latest release is public.
publishpath=None, overwrite=True, partition_by=NoneCopy every #public view of a dataflow folder (as update_latest_release leaves them) into public_s3."dh-prod-data-public", as tables at the same full catalog path (catalog.x.y.dataflow.a.t is copied to public_s3."dh-prod-data-public".catalog.x.y.dataflow.a.t). The dataflow folder is path when given (absolute, or relative to the context), else the %catalog use(...) context; with neither it raises. It must have draft, versions and reference (or references) folders just below it — raises at once otherwise. Views and tables in those three folders are ignored; views without the tag are skipped and the report's notes say which. An existing table is replaced (overwrite=True, the default; not undoable) — overwrite=False makes it an error, and then nothing is copied. Each table is checked once copied, and the report's notes give its row count. All or nothing: if any table fails, everything the publish did is rolled back (replaced tables are restored) and an error says which table failed. partition_by (optional) partitions the tables by existing fields, in order: a list for every view (partition_by=["year", "country"]), or a dict for each view's own, keyed by its path below the Area (partition_by={"eu_sdg.monitoringsites": ["year"]}; views left out are not partitioned). A field a view doesn't have raises at once, when publish is called.
listpath=''Show every table/view under path as a JSON array of {type, name} — type TABLE or VIEW, name the full dot-separated path: its own, then every child folder's, at any depth — walked folder by folder through Dremio's catalog API, no SQL. path may use '.' or '/' separators. path may be omitted to list the current context itself — raises CatalogSessionError if none is set. Raises CatalogOperationError if path doesn't exist.
schemapathShow path's column schema and row count (never fetches the actual rows). path must be a table or view — raises CatalogOperationError otherwise, or if path doesn't exist at all.
delete_tablepathDelete the table at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP TABLE, this doesn't quietly no-op on a typo).
create_viewsource_path, target_path, overwrite=False, create_target_folder=FalseCreate a VIEW at target_path over source_path, leaving source_path untouched. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
delete_viewpathDelete the view at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP VIEW, this doesn't quietly no-op on a typo).
set_wikipath, text, tags=NoneSet a path's wiki text. tags: a list of {tag_name, tag_value, tag_title} dicts, e.g. [{"tag_name": "owner", "tag_value": "bw-team", "tag_title": "Owner"}]. Ignored if path is a table/view (they have set_tags/get_tags for that instead).
delete_wikipathDelete a path's wiki text.
get_wikipathShow a path's wiki text. Raises CatalogOperationError if the path doesn't exist, or exists but has no wiki at all.
set_tagspath, tagsReplace a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise.
delete_tagspath, tagsRemove tags from a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise.
get_tagspathShow the tags on a path — tables/views only. Raises CatalogOperationError if the path doesn't exist or isn't a table/view.
create_folderpath, create_parents=FalseCreate a folder. create_parents=True creates every missing level of the full path; create_parents=False (default) raises CatalogOperationError if the parent folder doesn't already exist.
delete_folderpath, cascade=FalseDelete a folder. Not undoable. cascade=True also deletes everything at path and below; cascade=False (default) raises CatalogOperationError if the folder isn't empty. A path that's already gone is not an error.
" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "outputs": [], "source": [ "%catalog help" - ] + ], + "id": "b94a800b" }, { - "cell_type": "code", - "execution_count": 7, - "id": "c311fdb0", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "%catalog methods — usage: %catalog data_copy(\"a.b\", \"c.d\") | %catalog set_tags(\"a.b\", [\"reviewed\"]) (each call runs immediately)\n", - "A new session's context starts at 'catalog' (the root source), not empty — use(None)/use('') reset back to it too; only set_context(None) clears it to no context at all.\n", - "Every path/source_path/target_path (except use's own) is either absolute or relative to the current context, once one is set:\n", - " - starts with 'catalog.' (this deployment's one real root source) -> always absolute, used exactly as given, never appended to the context\n", - " - '.' or './' alone -> the context itself, exactly as get_context() shows it\n", - " - '../' (or a bare '..'), optionally chained ('../../') -> walks up that many levels of the context first, then appends whatever's left, if anything\n", - " - '.name', or a bare 'name' with no leading '.' at all -> both mean relative to the context; the dot is optional sugar, not what makes it relative\n", - "Only use() ever changes the context — no other call does, even one that fully resolved an absolute path.\n" - ] - }, - { - "data": { - "text/html": [ - "
CommandParametersDescription
usepathSet the current path for every call after this one; path must be a whole, absolute path — never relative to the current context, unlike every other verb's path/source_path/target_path. None or '' resets it to 'catalog' (the root). Raises if path doesn't exist in the catalog. See %%catalog to set it once at the top of a cell.
get_contextShow the current path. A new session starts at 'catalog' (the root); use(None)/use('') reset back to it too — None only after an explicit set_context(None).
data_copysource_path, target_path, overwrite=False, create_target_folder=FalseCopy source_path to target_path. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
data_movesource_path, target_path, overwrite=False, create_target_folder=FalseMove source_path to target_path, always as a TABLE (use create_view for a view). overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
create_versionsource_path, version_name, tables=None, target_path=None, overwrite=False, create_target_folder=TrueCopy the listed tables from source_path into a new folder target_path.version_name (as CREATE TABLE snapshots, keeping each table's sub-folders). source_path and version_name must not be blank. tables omitted or empty copies everything under source_path. Each entry is a table or a folder (= every table under it), named as listed under source_path or as list() shows them. target_path omitted means the current context — use() picks where versions go; a missing target_path is created unless create_target_folder=False. Reference/vocabulary tables (a folder named reference(s)/vocabulary(ies) in the path) and views are skipped; the report's notes say which. An existing version folder is an error unless overwrite=True (replaces the listed tables, keeps the rest).
draft_to_versionversion_name, tables=None, overwrite=Falsecreate_version from the dataflow's draft folder, with no paths to type: the source is the draft folder the context is in (or the draft folder inside the context), the target is draft's parent.versions.version_name (versions is created if missing). tables as in create_version: omitted or empty copies everything in draft. Unlike create_version, views in draft are not skipped: each is copied into the version as a table (a snapshot of what it returns); the report's notes say which.
update_latest_releaseversion_name, overwrite=TrueCreate a view at the Area's root for every table in versions.version_name, keeping its sub-folders (versions.v1.a.t gets the view a.t; missing folders are created). The context must be the Area folder — one with draft and versions folders just below it, typically catalog.<domain>.<subdomain>.<area> — and versions.version_name must exist — raises at once otherwise. Views in the version are skipped. An existing view is dropped and recreated over the version (overwrite=True, the default; not undoable) — overwrite=False makes it an error instead; an existing table is always an error.
listpath=''Show every table/view under path as a JSON array of {type, name} — type TABLE or VIEW, name the full dot-separated path: its own, then every child folder's, at any depth — walked folder by folder through Dremio's catalog API, no SQL. path may use '.' or '/' separators. path may be omitted to list the current context itself — raises CatalogSessionError if none is set. Raises CatalogOperationError if path doesn't exist.
schemapathShow path's column schema and row count (never fetches the actual rows). path must be a table or view — raises CatalogOperationError otherwise, or if path doesn't exist at all.
delete_tablepathDelete the table at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP TABLE, this doesn't quietly no-op on a typo).
create_viewsource_path, target_path, overwrite=False, create_target_folder=FalseCreate a VIEW at target_path over source_path, leaving source_path untouched. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
delete_viewpathDelete the view at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP VIEW, this doesn't quietly no-op on a typo).
set_wikipath, text, tags=NoneSet a path's wiki text. tags: a list of {tag_name, tag_value, tag_title} dicts, e.g. [{"tag_name": "owner", "tag_value": "bw-team", "tag_title": "Owner"}]. Ignored if path is a table/view (they have set_tags/get_tags for that instead).
delete_wikipathDelete a path's wiki text.
get_wikipathShow a path's wiki text. Raises CatalogOperationError if the path doesn't exist, or exists but has no wiki at all.
set_tagspath, tagsReplace a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise.
delete_tagspath, tagsRemove tags from a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise.
get_tagspathShow the tags on a path — tables/views only. Raises CatalogOperationError if the path doesn't exist or isn't a table/view.
create_folderpath, create_parents=FalseCreate a folder. create_parents=True creates every missing level of the full path; create_parents=False (default) raises CatalogOperationError if the parent folder doesn't already exist.
delete_folderpath, cascade=FalseDelete a folder. Not undoable. cascade=True also deletes everything at path and below; cascade=False (default) raises CatalogOperationError if the folder isn't empty. A path that's already gone is not an error.
" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], "source": [ - "%catalog help()" - ] + "## Scratch space\n", + "\n", + "`TEST_FOLDER` is the one folder this notebook writes to; **Cleanup** deletes it with everything\n", + "inside. `SOURCE_TABLE` is an existing table the data cells copy from — only read. `verify` is\n", + "an independent client for the checks." + ], + "id": "39af68b3" }, { "cell_type": "code", - "execution_count": 12, - "id": "4eb4c501", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "context set to 'catalog.water_management_resources.bathing_water.bwd.draft'\n" - ] - } - ], + "outputs": [], "source": [ - "%catalog use('catalog.water_management_resources.bathing_water.bwd.draft')" - ] + "from eea_datalakehouse.catalog.polaris import PolarisCatalog\n", + "\n", + "ROOT = SETTINGS.catalog\n", + "TEST_ROOT = f\"{ROOT}.non_domain_datasets\"\n", + "TEST_FOLDER = f\"{TEST_ROOT}.catalog_magic_smoke_test\"\n", + "SOURCE_TABLE = f\"{ROOT}.biodiversity_ecosystems.protected_areas.dfl_natura2000.draft.sites.aaaa\"\n", + "\n", + "verify = PolarisCatalog(SETTINGS) # an independent client: the magic never touches it\n", + "print(\"TEST_FOLDER \", TEST_FOLDER, \"(exists already!)\" if verify.exists(TEST_FOLDER) else \"\")\n", + "print(\"SOURCE_TABLE \", SOURCE_TABLE, \"exists:\", verify.exists(SOURCE_TABLE))" + ], + "id": "c4c97822" }, { - "cell_type": "code", - "execution_count": 9, - "id": "f975f358", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'catalog'" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ - "%catalog get_context()" - ] + "## 1. A call runs immediately\n", + "\n", + "`create_folder` is the only `%catalog` call in the cell — no `%catalog commit` after it. On\n", + "Polaris a folder is a namespace." + ], + "id": "6d53a1cd" }, { "cell_type": "code", - "execution_count": 13, - "id": "099bff73", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['catalog.water_management_resources.bathing_water.bwd.draft.bw_assessment.assessments']" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog list()" - ] + "%catalog create_folder(TEST_FOLDER, create_parents=True)" + ], + "id": "45d8ff5e" }, { "cell_type": "code", - "execution_count": 14, - "id": "5c4813fb", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "catalog error: commit failed at step 1/1 (delete folder 'catalog.water_management_resources.bathing_water.bwd.draft.aaaaa'): could not look up 'catalog.water_management_resources.bathing_water.bwd.draft.aaaaa' (400): {\"errorMessage\":\"Can not get internal item from non-filesystem source [catalog] of type [com.dremio.plugins.dremiocatalog.store.DremioCatalogLocalPlugin]\",\"moreInfo\":\"\"}. Everything before it was rolled back.\n" - ] - } - ], + "outputs": [], "source": [ - "%catalog delete_folder('aaaaa',cascade=True)" - ] + "print(\"folder exists right now:\", verify.exists(TEST_FOLDER), \"| is a namespace:\", verify.is_folder(TEST_FOLDER))" + ], + "id": "d90b81ed" }, { - "cell_type": "code", - "execution_count": 16, - "id": "338b04ca", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"data_copy 'catalog.water_management_resources.bathing_water.bwd.draft.bw_assessment.assessments' -> 'catalog.water_management_resources.bathing_water.bwd.draft.aaaaa.tttt.jkjkjkk'\"])" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ - "%catalog data_copy('bw_assessment.assessments', 'aaaaa.tttt.jkjkjkk',create_target_folder= True)" - ] + "## 2. Context and relative paths\n", + "\n", + "`use` sets the context; a bare name (or `.name`) is then relative to it. Absolute paths start\n", + "with the catalog's name (`eea_lakehouse.`) — on Dremio they started with `catalog.`." + ], + "id": "d450519d" }, { - "cell_type": "markdown", - "id": "a6f909ab", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## Scratch space\n", - "\n", - "Everything below happens under a folder distinctly named for this notebook, alongside the\n", - "`altia_test` scratch folder `debug_run.py` already uses for the same kind of manual testing —\n", - "so it's obviously not real data, and `delete_folder(cascade=True)` in \"Cleanup\" removes all of\n", - "it at the end." - ] + "%catalog use(TEST_FOLDER)\n", + "%catalog get_context()" + ], + "id": "3721db27" }, { "cell_type": "code", "execution_count": null, - "id": "844929cf", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "%catalog create_folder(\"nested\") # -> TEST_FOLDER + \".nested\"" + ], + "id": "bedfc770" }, { "cell_type": "code", "execution_count": null, - "id": "25a4af1d", "metadata": {}, "outputs": [], "source": [ - "TEST_ROOT = \"catalog.water_management_resources.bathing_water.bwd.draft\"\n", - "TEST_FOLDER = f\"{TEST_ROOT}.catalog_magic_smoke_test\"\n", - "print(TEST_FOLDER)" - ] + "print(\"nested folder exists right now:\", verify.exists(f\"{TEST_FOLDER}.nested\"))" + ], + "id": "3bd26c7e" }, { "cell_type": "markdown", - "id": "1e79e191", "metadata": {}, "source": [ - "## 1. A call runs immediately\n", + "## 3. Wiki and tags — also immediate\n", "\n", - "`create_folder` below is the only `%catalog` call in this cell — nothing else queues it, and\n", - "there's no `%catalog commit` after it." - ] + "On Polaris the wiki is the namespace's (or table's) `wiki` property, and tags are kept as the\n", + "Polaris Navigator keeps them: lower case, without `#` (`#Smoke` and `smoke` are the same tag).\n", + "Folders take tags too. `tags=` on a folder's wiki renders a \"# Meta Data\" block, as on Dremio." + ], + "id": "40f2527a" }, { "cell_type": "code", "execution_count": null, - "id": "e563984c", "metadata": {}, "outputs": [], "source": [ - "%catalog create_folder(TEST_FOLDER, create_parents=True)" - ] + "%catalog set_wiki(\".\", \"# Catalog magic smoke test\\n\\nCreated by the %catalog debugger notebook.\", tags=[{\"tag_name\": \"owner\", \"tag_value\": \"debugger\", \"tag_title\": \"Owner\"}])" + ], + "id": "29ac62a2" }, { - "cell_type": "markdown", - "id": "97f7f415", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "**Proof:** the next cell builds a brand new `Catalog` client — one the magic's\n", - "`CatalogSession` never touched — and asks Dremio directly whether the folder is there. If\n", - "`%catalog` only queued the step, this would say `False`." - ] + "print(verify.getwikifrom(TEST_FOLDER, idempotency_key=\"smoke-read-wiki\"))" + ], + "id": "f76508c9" }, { "cell_type": "code", - "execution_count": 4, - "id": "0fca8ccf", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "ename": "NameError", - "evalue": "name 'os' is not defined", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mNameError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[4]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;28;01mfrom\u001b[39;00m eea_datalakehouse.catalog \u001b[38;5;28;01mimport\u001b[39;00m Catalog\n\u001b[32m 2\u001b[39m \n\u001b[32m 3\u001b[39m verify_catalog = Catalog(\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m os.environ[\u001b[33m\"DREMIO_BASE_URL\"\u001b[39m], os.environ[\u001b[33m\"DREMIO_TOKEN\"\u001b[39m],\n\u001b[32m 5\u001b[39m username=os.environ.get(\u001b[33m\"DREMIO_USERNAME\"\u001b[39m),\n\u001b[32m 6\u001b[39m )\n\u001b[32m 7\u001b[39m \u001b[38;5;66;03m# `_catalog_rest.exists` is the same private check `CatalogSession.create_folder`'s own\u001b[39;00m\n", - "\u001b[31mNameError\u001b[39m: name 'os' is not defined" - ] - } - ], + "outputs": [], "source": [ - "from eea_datalakehouse.catalog import Catalog\n", - "\n", - "verify_catalog = Catalog(\n", - " os.environ[\"DREMIO_BASE_URL\"], os.environ[\"DREMIO_TOKEN\"],\n", - " username=os.environ.get(\"DREMIO_USERNAME\"),\n", - ")\n", - "# `_catalog_rest.exists` is the same private check `CatalogSession.create_folder`'s own\n", - "# `run()` uses internally (see session.py) — reached into directly here only because this\n", - "# is a debug/verification notebook, same spirit as debug_run.py's `catalog._flight_executor`\n", - "# access elsewhere in this folder.\n", - "print(\"folder exists right now:\", verify_catalog._catalog_rest.exists(TEST_FOLDER)) # noqa" - ] + "%catalog set_tags(\".\", [\"#Smoke\", \"test\"])\n", + "%catalog get_tags(\".\")" + ], + "id": "2a3d9a5b" }, { "cell_type": "markdown", - "id": "68efceb9", "metadata": {}, "source": [ - "## 2. Relative paths still work\n", + "## 4. What a failed call looks like\n", "\n", - "`create_folder` sets the session's context to the folder it just created (not its parent —\n", - "see `CatalogSession.create_folder`'s docstring), so a following `.name` call lands *inside*\n", - "it without spelling out `TEST_FOLDER` again." - ] + "`TEST_FOLDER` holds `nested`, so deleting it without `cascade=True` fails — `%catalog` prints a\n", + "short message instead of a traceback." + ], + "id": "8b2cdc00" }, { "cell_type": "code", "execution_count": null, - "id": "3c41cfca", "metadata": {}, "outputs": [], "source": [ - "%catalog create_folder(\".nested\") # -> TEST_FOLDER + \".nested\"" - ] + "%catalog delete_folder(TEST_FOLDER) # cascade=False (the default) — expected to fail, folder not empty" + ], + "id": "5ca5d62e" }, { - "cell_type": "code", - "execution_count": null, - "id": "1cd340ad", + "cell_type": "markdown", "metadata": {}, - "outputs": [], "source": [ - "print(\"nested folder exists right now:\", verify_catalog._catalog_rest.exists(f\"{TEST_FOLDER}.nested\")) # noqa" - ] + "## 5. Data: copy, schema, views, move\n", + "\n", + "`data_copy` runs `CREATE TABLE … AS SELECT` in this kernel's DuckDB, writing an Iceberg table\n", + "through Polaris (columns Iceberg can't hold are cast: nanosecond timestamps, geometry, …).\n", + "`schema` of a table comes from its Iceberg metadata; of a view, from running its SQL." + ], + "id": "6e4f220e" }, { - "cell_type": "markdown", - "id": "24a3cbc3", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## 3. Wiki text — also immediate\n", - "\n", - "`set_wiki` works on any catalog entity, folders included. Commits itself the moment its\n", - "cell runs, exactly like `create_folder` above." - ] + "%catalog data_copy(SOURCE_TABLE, \"nested.copy\")" + ], + "id": "a4e6d60b" }, { "cell_type": "code", "execution_count": null, - "id": "9bfe34e1", "metadata": {}, "outputs": [], "source": [ - "%catalog set_wiki(TEST_FOLDER, \"# Catalog magic smoke test\\n\\nCreated by the %catalog debugger notebook.\")" - ] + "%catalog schema(\"nested.copy\")" + ], + "id": "f3a7c4aa" }, { "cell_type": "code", "execution_count": null, - "id": "a83f08c6", "metadata": {}, "outputs": [], "source": [ - "print(verify_catalog.getwikifrom(TEST_FOLDER, idempotency_key=\"smoke-test-read-wiki\"))" - ] + "print(\"copy is a:\", verify.entry_kind(f\"{TEST_FOLDER}.nested.copy\", idempotency_key=\"smoke\"))" + ], + "id": "faec2ef2" }, { - "cell_type": "markdown", - "id": "59854882", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## 4. Read-only queries answer immediately too\n", - "\n", - "`get_wiki`/`get_tags`/`list`/`schema` are read-only `CatalogSession` methods — no `%catalog\n", - "commit` involved, same as every other call in this notebook. `get_wiki` reads back the wiki\n", - "just set above; `list` finds no tables/views here since `TEST_FOLDER` only holds folders —\n", - "an empty list, not an error (it would only raise if `TEST_FOLDER` itself didn't exist)." - ] + "%catalog create_view(\"nested.copy\", \"nested.copy_view\")\n", + "%catalog schema(\"nested.copy_view\")" + ], + "id": "d7b20734" }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## 5. What a failed call looks like\n", - "\n", - "`TEST_FOLDER` still has `.nested` inside it, so deleting it without `cascade=True` should\n", - "fail — `%catalog` prints a short message instead of a traceback (see the design doc's\n", - "\"Exceptions translated at the boundary\")." - ] + "print(verify.view_sql(f\"{TEST_FOLDER}.nested.copy_view\"))" + ], + "id": "27b35c16" }, { "cell_type": "code", @@ -459,26 +343,38 @@ "metadata": {}, "outputs": [], "source": [ - "%catalog delete_folder(TEST_FOLDER) # cascade=False (the default) — expected to fail, folder not empty" - ] + "%catalog data_copy(SOURCE_TABLE, \"nested.copy\", overwrite=True) # replaces the table\n", + "%catalog data_move(\"nested.copy\", \"moved/\") # a target ending in / is a folder, created\n", + "%catalog list()" + ], + "id": "4509ca89" }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Cleanup\n", + "## 6. A dataflow release: draft → version → latest views\n", "\n", - "`cascade=True` removes `.nested` along with `TEST_FOLDER` itself — this, like `%catalog`'s\n", - "other calls, has already happened by the time the cell below finishes." - ] + "An Area folder holds `draft`, `versions` and `reference`. `draft_to_version` copies the draft\n", + "into `versions.` (views as tables); `update_latest_release` puts a view at the Area's\n", + "root over every table of that version and tags it `public`." + ], + "id": "5785c55a" }, { "cell_type": "code", "execution_count": null, - "id": "9a1afe5c", "metadata": {}, "outputs": [], - "source": [] + "source": [ + "AREA = f\"{TEST_FOLDER}.dfl_smoke\"\n", + "%catalog create_folder(f\"{AREA}.draft\", create_parents=True)\n", + "%catalog create_folder(f\"{AREA}.versions\")\n", + "%catalog create_folder(f\"{AREA}.reference\")\n", + "%catalog data_copy(SOURCE_TABLE, f\"{AREA}.draft.stations\")\n", + "%catalog use(AREA)" + ], + "id": "73a7e215" }, { "cell_type": "code", @@ -486,8 +382,9 @@ "metadata": {}, "outputs": [], "source": [ - "%catalog delete_folder(TEST_FOLDER, cascade=True)" - ] + "%catalog draft_to_version(\"v2026_1\")" + ], + "id": "fb1e2aec" }, { "cell_type": "code", @@ -495,1516 +392,266 @@ "metadata": {}, "outputs": [], "source": [ - "print(\"folder exists after cleanup:\", verify_catalog._catalog_rest.exists(TEST_FOLDER)) # noqa" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "6d7cde28", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "catalog error: 'catalog.water_management_resources.bathing_water' does not exist in the catalog\n" - ] - } + "%catalog update_latest_release(\"v2026_1\")" ], - "source": [ - "%catalog use('catalog.water_management_resources.bathing_water')" - ] + "id": "3d8855a5" }, { "cell_type": "code", - "execution_count": 4, - "id": "ec8e9359", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designated_areas\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designation_types\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.protected_site_polygon\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designated_areas\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designation_types\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.protected_site_polygon\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.cdda_region_code\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designated_area_type\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designation_type_category\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designation_type_code\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.eionet_change_type\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.iucn_category\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.major_ecosystem_type\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.regions\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.spatial_data_dissemination\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.spatial_resolution_code\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.designated_areas\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.designation_types\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.protected_site_polygon\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.draft.sebi027.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.sebi027.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.versions.v2026_1.sebi027.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.draft.ied_eprtr.sites\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.ied_eprtr.sites\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.countries\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.eprtrannexiactivityvalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.eprtrpollutantcodevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.iedannexiactivityvalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.mediumcodevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.nacevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.unitcodevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.wastetreatmentvalue\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.versions.v2026_1.ied_eprtr.sites\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.draft.eu_ets.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.eu_ets.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.countries\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.country\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.ets_information\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.main_activity\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.nace_r2\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.versions.v2026_1.eu_ets.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.draft.eu_sdg_06_30.monitoringsites\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.draft.eu_sdg_06_30.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.eu_sdg_06_30.monitoringsites\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.eu_sdg_06_30.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.observedproperty\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.versions.v2026_1.eu_sdg_06_30.monitoringsites\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.versions.v2026_1.eu_sdg_06_30.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bwd.bw_assessment.assessments\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bwd.draft.bw_assessment.assessments\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bwd.versions.2025_6.bw_assessment.assessments\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.draft.eu_sdg_06_50.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.draft.eu_sdg_06_50.waterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.eu_sdg_06_50.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.eu_sdg_06_50.waterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.observedproperty\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versions.v2026_1.eu_sdg_06_50.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versions.v2026_1.eu_sdg_06_50.waterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.draft.eu_sdg_06_40.groundwaterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.draft.eu_sdg_06_40.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.eu_sdg_06_40.groundwaterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.eu_sdg_06_40.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.observedproperty\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.versions.v2026_1.eu_sdg_06_40.groundwaterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.versions.v2026_1.eu_sdg_06_40.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.draft.eu_sdg_06_60.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.eu_sdg_06_60.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.wat_proc\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.wat_src\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.versions.v2026_1.eu_sdg_06_60.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.draft.wat007.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.wat_proc\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.wat_src\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.versions.v2026_1.wat007.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.wat007.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.draft.lsi001.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.lsi001.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.versions.v2026_1.lsi001.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.draft.sdg_11_32.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.freq\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.sdg_11_32.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.versions.v2026_1.sdg_11_32.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.non_domain_datasets.system.show_role_members\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.non_domain_datasets.system.show_roles\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.non_domain_datasets.system.show_users\"\n", - " }\n", - "]" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog list()" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "a653e15f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TableInfo(schema={'country_code': 'CHARACTER VARYING', 'bathing_water_identifier': 'CHARACTER VARYING', 'group_identifier': 'CHARACTER VARYING', 'bathing_water_name': 'CHARACTER VARYING', 'bathing_water_type': 'CHARACTER VARYING', 'geographical_constraint': 'BOOLEAN', 'lon': 'DOUBLE', 'lat': 'DOUBLE', 'bw_profile': 'CHARACTER VARYING', 'season': 'INTEGER', 'quality_raw': 'CHARACTER VARYING', 'quality_code': 'INTEGER', 'quality_label': 'CHARACTER VARYING', 'quality_scheme': 'CHARACTER VARYING', 'monitoring_calendar_code': 'INTEGER', 'monitoring_calendar_label': 'CHARACTER VARYING', 'management_code': 'INTEGER', 'management_label': 'CHARACTER VARYING', 'release': 'CHARACTER VARYING'}, row_count=694918)" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } ], - "source": [ - "%catalog schema('bwd.draft.bw_assessment.assessments') # should be empty now, after the delete" - ] + "id": "65299b51" }, { "cell_type": "code", - "execution_count": 1, - "id": "ca2ba7e1", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "UUUU\n" - ] - } - ], + "outputs": [], "source": [ - "print(\"UUUU\")" - ] + "%catalog get_tags(\"stations\")" + ], + "id": "076f21a5" }, { "cell_type": "code", - "execution_count": 3, - "id": "0299f0e6", + "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "dataflow_path ='catalog/water_management_resources/surface_water/bod_rivers'\n", - "target_version = 'v2026_1'" - ] + "print(\"latest view reads the version:\", verify.view_sql(f\"{AREA}.stations\"))" + ], + "id": "32c56703" }, { - "cell_type": "code", - "execution_count": 4, - "id": "e420e563", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "catalog error: 'catalog.water_management_resources.surface_water.bod_rivers' does not exist in the catalog\n" - ] - } - ], "source": [ - "%catalog use(dataflow_path)" - ] + "### Publishing (writes to the real public store — off by default)\n", + "\n", + "`publish` pushes every `public` view of the Area through the Document Service to the public\n", + "store, at `//`. It needs a Keycloak token of a member of the publishers'\n", + "group, and DDS. Uncomment to run — and unpublish afterwards." + ], + "id": "81655c19" }, { "cell_type": "code", - "execution_count": 5, - "id": "3591ec2a", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designated_areas\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designation_types\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.protected_site_polygon\n", - "VIEW catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designated_areas\n", - "VIEW catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designation_types\n", - "VIEW catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.protected_site_polygon\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.cdda_region_code\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designated_area_type\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designation_type_category\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designation_type_code\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.eionet_change_type\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.iucn_category\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.major_ecosystem_type\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.regions\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.spatial_data_dissemination\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.spatial_resolution_code\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.designated_areas\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.designation_types\n", - "TABLE catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.protected_site_polygon\n", - "TABLE catalog.biodiversity_ecosystems.species.common_bird_index.draft.sebi027.observations\n", - "TABLE catalog.biodiversity_ecosystems.species.common_bird_index.reference.dimension\n", - "TABLE catalog.biodiversity_ecosystems.species.common_bird_index.reference.geo\n", - "TABLE catalog.biodiversity_ecosystems.species.common_bird_index.reference.unit\n", - "VIEW catalog.biodiversity_ecosystems.species.common_bird_index.sebi027.observations\n", - "TABLE catalog.biodiversity_ecosystems.species.common_bird_index.versions.v2026_1.sebi027.observations\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.draft.ied_eprtr.sites\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.ied_eprtr.sites\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.countries\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.eprtrannexiactivityvalue\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.eprtrpollutantcodevalue\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.iedannexiactivityvalue\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.mediumcodevalue\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.nacevalue\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.unitcodevalue\n", - "VIEW catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.wastetreatmentvalue\n", - "TABLE catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.versions.v2026_1.ied_eprtr.sites\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.draft.eu_ets.observations\n", - "VIEW catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.eu_ets.observations\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.countries\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.country\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.ets_information\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.geo\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.main_activity\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.nace_r2\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.unit\n", - "TABLE catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.versions.v2026_1.eu_ets.observations\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.draft.eu_sdg_06_30.monitoringsites\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.draft.eu_sdg_06_30.observations\n", - "VIEW catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.eu_sdg_06_30.monitoringsites\n", - "VIEW catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.eu_sdg_06_30.observations\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.dimension\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.geo\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.obs_status\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.observedproperty\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.unit\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.versions.v2026_1.eu_sdg_06_30.monitoringsites\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.versions.v2026_1.eu_sdg_06_30.observations\n", - "VIEW catalog.freshwater_water_management.water_bodies_ecological_status.bwd.bw_assessment.assessments\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bwd.draft.bw_assessment.assessments\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.bwd.versions.2025_6.bw_assessment.assessments\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.draft.eu_sdg_06_50.observations\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.draft.eu_sdg_06_50.waterbodies\n", - "VIEW catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.eu_sdg_06_50.observations\n", - "VIEW catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.eu_sdg_06_50.waterbodies\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.dimension\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.geo\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.obs_status\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.observedproperty\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.unit\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versions.v2026_1.eu_sdg_06_50.observations\n", - "TABLE catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versions.v2026_1.eu_sdg_06_50.waterbodies\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.draft.eu_sdg_06_40.groundwaterbodies\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.draft.eu_sdg_06_40.observations\n", - "VIEW catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.eu_sdg_06_40.groundwaterbodies\n", - "VIEW catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.eu_sdg_06_40.observations\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.dimension\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.geo\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.obs_status\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.observedproperty\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.unit\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.versions.v2026_1.eu_sdg_06_40.groundwaterbodies\n", - "TABLE catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.versions.v2026_1.eu_sdg_06_40.observations\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.draft.eu_sdg_06_60.observations\n", - "VIEW catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.eu_sdg_06_60.observations\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.dimension\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.geo\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.obs_status\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.unit\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.wat_proc\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.wat_src\n", - "TABLE catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.versions.v2026_1.eu_sdg_06_60.observations\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.draft.wat007.observations\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.dimension\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.geo\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.unit\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.wat_proc\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.wat_src\n", - "TABLE catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.versions.v2026_1.wat007.observations\n", - "VIEW catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.wat007.observations\n", - "TABLE catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.draft.lsi001.observations\n", - "VIEW catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.lsi001.observations\n", - "TABLE catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.dimension\n", - "TABLE catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.geo\n", - "TABLE catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.unit\n", - "TABLE catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.versions.v2026_1.lsi001.observations\n", - "TABLE catalog.land_agriculture_soil_forestry.soil.soil_sealing.draft.sdg_11_32.observations\n", - "TABLE catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.freq\n", - "TABLE catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.geo\n", - "TABLE catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.obs_status\n", - "TABLE catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.unit\n", - "VIEW catalog.land_agriculture_soil_forestry.soil.soil_sealing.sdg_11_32.observations\n", - "TABLE catalog.land_agriculture_soil_forestry.soil.soil_sealing.versions.v2026_1.sdg_11_32.observations\n", - "VIEW catalog.non_domain_datasets.system.show_role_members\n", - "VIEW catalog.non_domain_datasets.system.show_roles\n", - "VIEW catalog.non_domain_datasets.system.show_users" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog list()" - ] + "# %catalog publish()" + ], + "id": "fd47c58f" }, { - "cell_type": "code", - "execution_count": 9, - "id": "4d1edf60", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create version 'catalog.water_management_resources.surface_water.bod_rivers.versions.v2026_1' from 'catalog.water_management_resources.surface_water.bod_rivers.draft' (all tables)\"], notes=[])" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ - "%catalog draft_to_version(target_version)" - ] + "## 7. `%ingest`: upload to the object store, then a table\n", + "\n", + "`table_format=\"iceberg\"` (the default) stages the files under `_ingestion/…`, loads them into an\n", + "Iceberg table (Parquet, CSV or JSON) and removes the staged files; `\"parquet\"` keeps Parquet\n", + "files as they are, registered as a read-only table (`sub_path` adds a sub-folder each time), and\n", + "`promote` turns that into Iceberg later. Small local files are generated first." + ], + "id": "21202009" }, { "cell_type": "code", - "execution_count": 3, - "id": "b60442a5", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "context set to 'catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr'\n" - ] - } - ], + "outputs": [], "source": [ - "%catalog use('catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr')\n" - ] + "import tempfile\n", + "\n", + "import pyarrow as pa\n", + "import pyarrow.parquet as pq\n", + "\n", + "INGEST_DIR = Path(tempfile.mkdtemp(prefix=\"catalog_magic_smoke_\"))\n", + "(INGEST_DIR / \"temps\").mkdir()\n", + "pq.write_table(\n", + " pa.table({\"site\": [\"a\", \"b\"], \"temp\": [21.5, 22.0],\n", + " \"at\": pa.array([1735722000000000000, 1735725600000000000], pa.timestamp(\"ns\"))}),\n", + " INGEST_DIR / \"temps\" / \"part-1.parquet\",\n", + ")\n", + "(INGEST_DIR / \"samples\").mkdir()\n", + "(INGEST_DIR / \"samples\" / \"samples.csv\").write_text(\"id;value\\n1;3.5\\n2;4.0\\n3;4.5\\n\")\n", + "TEMPS, SAMPLES = str(INGEST_DIR / \"temps\"), str(INGEST_DIR / \"samples\")\n", + "print(INGEST_DIR)" + ], + "id": "dba0484a" }, { "cell_type": "code", - "execution_count": 5, - "id": "756f3592", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designated_areas\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designation_types\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.protected_site_polygon\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designated_areas\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designation_types\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.protected_site_polygon\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.cdda_region_code\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designated_area_type\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designation_type_category\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.designation_type_code\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.eionet_change_type\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.iucn_category\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.major_ecosystem_type\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.regions\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.spatial_data_dissemination\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.reference.spatial_resolution_code\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.designated_areas\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.designation_types\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.2024_07.natda.protected_site_polygon\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.draft.sebi027.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.sebi027.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.biodiversity_ecosystems.species.common_bird_index.versions.v2026_1.sebi027.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.draft.ied_eprtr.sites\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.ied_eprtr.sites\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.countries\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.eprtrannexiactivityvalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.eprtrpollutantcodevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.iedannexiactivityvalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.mediumcodevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.nacevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.unitcodevalue\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.reference.wastetreatmentvalue\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.versions.v2026_1.ied_eprtr.sites\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.draft.eu_ets.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.eu_ets.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.countries\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.country\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.ets_information\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.main_activity\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.nace_r2\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.climate_change_mitigation_energy.greenhouse_gas_emissions.eu_ets.versions.v2026_1.eu_ets.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.draft.eu_sdg_06_30.monitoringsites\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.draft.eu_sdg_06_30.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.eu_sdg_06_30.monitoringsites\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.eu_sdg_06_30.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.observedproperty\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.versions.v2026_1.eu_sdg_06_30.monitoringsites\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bod_rivers.versions.v2026_1.eu_sdg_06_30.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bwd.bw_assessment.assessments\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bwd.draft.bw_assessment.assessments\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.bwd.versions.2025_6.bw_assessment.assessments\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.draft.eu_sdg_06_50.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.draft.eu_sdg_06_50.waterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.eu_sdg_06_50.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.eu_sdg_06_50.waterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.observedproperty\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versions.v2026_1.eu_sdg_06_50.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versions.v2026_1.eu_sdg_06_50.waterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.draft.eu_sdg_06_40.groundwaterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.draft.eu_sdg_06_40.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.eu_sdg_06_40.groundwaterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.eu_sdg_06_40.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.observedproperty\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.versions.v2026_1.eu_sdg_06_40.groundwaterbodies\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_quality_pollution.nitrate_groundwater.versions.v2026_1.eu_sdg_06_40.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.draft.eu_sdg_06_60.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.eu_sdg_06_60.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.wat_proc\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.reference.wat_src\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_resources_hydrology.water_exploitation_index.versions.v2026_1.eu_sdg_06_60.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.draft.wat007.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.wat_proc\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.reference.wat_src\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.versions.v2026_1.wat007.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.freshwater_water_management.water_use_supply_sanitation.water_abstraction.wat007.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.draft.lsi001.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.lsi001.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.dimension\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.land_cover_land_use.net_land_take.versions.v2026_1.lsi001.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.draft.sdg_11_32.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.freq\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.geo\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.obs_status\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.reference.unit\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.sdg_11_32.observations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"catalog.land_agriculture_soil_forestry.soil.soil_sealing.versions.v2026_1.sdg_11_32.observations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.non_domain_datasets.system.show_role_members\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.non_domain_datasets.system.show_roles\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"catalog.non_domain_datasets.system.show_users\"\n", - " }\n", - "]" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog list()" - ] + "%ingest ingest(folder=TEMPS, target_catalog_path=f\"{AREA}.draft\", data_format=\"parquet\", table_name=\"temps\")\n", + "%ingest ingest(folder=SAMPLES, target_catalog_path=f\"{AREA}.draft\", data_format=\"csv\", csv_options={\"delimiter\": \";\"})\n", + "%ingest ingest(folder=TEMPS, target_catalog_path=f\"{AREA}.reference\", data_format=\"parquet\", table_format=\"parquet\", table_name=\"temps_ro\", sub_path=\"2026\")\n", + "%ingest diagnose" + ], + "id": "b42ca6d2" }, { "cell_type": "code", - "execution_count": 5, - "id": "88f0ccac", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create version 'catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.versions.v2026_1' from 'catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.draft' (all tables)\"], notes=[\"copied view 'catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.draft.ied_eprtr.sites' as a table\"])" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog draft_to_version('v2026_1')" - ] + "report = %ingest commit\n", + "for outcome in report.outcomes:\n", + " print(outcome)\n", + " for note in outcome.notes:\n", + " print(\" note:\", note)" + ], + "id": "f8b18f98" }, { "cell_type": "code", - "execution_count": 6, - "id": "7af86802", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create views under 'catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr' for the tables in 'catalog.circular_economy_resources_clean_industry.production_industry.ied_eprtr.versions.v2026_1'\"], notes=[])" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog update_latest_release('v2026_1', overwrite=False)\n", - "\n", - "\n" - ] + "%catalog schema(\"draft.temps\")" + ], + "id": "2d3e7b30" }, { "cell_type": "code", - "execution_count": 22, - "id": "c3da92f5", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "catalog error: commit failed at step 1/1 (delete folder 'catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versionss'): could not look up 'catalog.freshwater_water_management.water_bodies_ecological_status.phosphate_rivers.versionss' (400): {\"errorMessage\":\"Can not get internal item from non-filesystem source [catalog] of type [com.dremio.plugins.dremiocatalog.store.DremioCatalogLocalPlugin]\",\"moreInfo\":\"\"}. Everything before it was rolled back.\n" - ] - } - ], + "outputs": [], "source": [ - "%catalog delete_folder(\"versionss\", cascade=True)\n" - ] + "%catalog schema(\"reference.temps_ro\")" + ], + "id": "2858c4fc" }, { "cell_type": "code", - "execution_count": 3, - "id": "85cec681", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "%gpkg methods — usage: %gpkg export() | %gpkg export(tables=[\"stations\"], limit=1000, srid=3035) (the %catalog use(...) folder, into the notebook's folder)\n", - "A table is spatial when a column holds geometries — WKB/EWKB, WKT/EWKT, hex WKB or GeoJSON (columns named geom, geometry, wkt, shape, ... are tried first) — or, failing that, it has latitude/longitude columns (points in EPSG:4326).\n", - "Each row's CRS: the SRID inside the geometry (EWKB/EWKT), else a CRS column (srid, sr_id, epsg, crs, ...: 3035, \"EPSG:3035\", a URN or a CRS name). A layer with no CRS at all is written with the undefined SRS (-1).\n", - "Streaming: rows are read over Arrow Flight a batch at a time — workers tables at once, each on its own channel — decoded and encoded in those workers, and written by one thread; memory stays a few batches per worker whatever the table size.\n", - "\n", - "export examples:\n", - " %gpkg export()\n", - " %gpkg export(tables=[\"stations\", \"areas\"])\n", - " %gpkg export(limit=1000)\n", - " %gpkg export(srid=3035)\n", - " %gpkg export(workers=8)\n", - " %gpkg export(path=\"../wfd\", filename=\"wfd_2025.gpkg\", output_dir=\"exports\")\n", - " %gpkg export(path=\"catalog.water.bwd\", tables=[\"stations\"], limit=100, srid=\"EPSG:4326\", overwrite=False, workers=2)\n", - "\n", - "Reads with %catalog's connection: DREMIO_BASE_URL / DREMIO_TOKEN. Written with sqlite3, shapely and pyproj (no GDAL).\n" - ] - }, - { - "data": { - "text/html": [ - "
CommandParametersDescription
exportpath=None, tables=None, limit=None, srid=None, filename=None, output_dir=None, overwrite=True, workers=4Write the tables and views under path to a GeoPackage file: spatial ones as feature layers, the rest as attribute tables. path defaults to the %catalog use(...) context and is resolved like any %catalog path. tables picks some, by name below path (["stations", "sub.areas"]); default all, at any depth. limit caps the rows per table. srid reprojects every layer (3035 or "EPSG:3035"); default: each keeps its own CRS. filename / output_dir default to <dataset>.gpkg in the notebook's folder; overwrite=True (default) replaces an existing file. workers tables are streamed from Dremio at once, each over its own Arrow Flight channel.
" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "outputs": [], "source": [ - "%gpkg help()" - ] + "%ingest promote(f\"{AREA}.reference.temps_ro\")" + ], + "id": "7ca12f16" }, { "cell_type": "code", - "execution_count": 10, - "id": "228ebbc7", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "context set to 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda'\n" - ] - } - ], + "outputs": [], "source": [ - "%catalog use('catalog.biodiversity_ecosystems.protected_areas.dfl_natda')" - ] + "%catalog schema(\"reference.temps_ro\")" + ], + "id": "be93abcd" }, { - "cell_type": "code", - "execution_count": 12, - "id": "63a23350", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create version 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.v2026_1' from 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft' (all tables)\"], notes=[])" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ - "%catalog draft_to_version('v2026_1')" - ] + "## 8. `%dds` — the context's document folders\n", + "\n", + "On Polaris `%dds` signs in with your Keycloak token and stores under the namespace's path\n", + "without the catalog name (`…non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/…`).\n", + "Needs `KEYCLOAK_ACCESS_TOKEN`." + ], + "id": "134d95ff" }, { "cell_type": "code", - "execution_count": 14, - "id": "b0e99c79", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create views under 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda' for the tables in 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.v2026_1'\"], notes=[\"replaced view 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designated_areas'\", \"replaced view 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designation_types'\", \"replaced view 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.protected_site_polygon'\", \"removed '#public' from 3 table(s)/view(s) under 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions'\"])" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog update_latest_release('v2026_1', overwrite=True)" - ] + "(INGEST_DIR / \"readme.txt\").write_text(\"catalog magic smoke test\")\n", + "%dds target(DELIVERABLES)" + ], + "id": "299b0378" }, { "cell_type": "code", - "execution_count": 15, - "id": "0076c290", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"publish the #public views of 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda' to 'public_s3.dh-prod-data-public.catalog.biodiversity_ecosystems.protected_areas.dfl_natda'\"], notes=[\"replaced 'public_s3.dh-prod-data-public.catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designated_areas' from 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designated_areas' (151709 rows)\", \"replaced 'public_s3.dh-prod-data-public.catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designation_types' from 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.designation_types' (739 rows)\", \"replaced 'public_s3.dh-prod-data-public.catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.protected_site_polygon' from 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.natda.protected_site_polygon' (148695 rows)\"])" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%catalog publish()" - ] + "%dds push(DELIVERABLES, str(INGEST_DIR / \"readme.txt\"), overwrite=True)\n", + "%dds list(DELIVERABLES)" + ], + "id": "959cbdc3" }, { - "cell_type": "code", - "execution_count": 11, - "id": "8fc04ebd", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"delete folder 'catalog.biodiversity_ecosystems.protected_areas.dfl_natda.versions.v2026_1'\"], notes=[])" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ - "%catalog delete_folder(\"versions.v2026_1\", cascade=True)" - ] + "## 9. `%gpkg` — GeoPackage export\n", + "\n", + "On Polaris `%gpkg` reads the rows through the EEA Lakehouse Arrow Flight gateway\n", + "(`FLIGHT_HOST`/`FLIGHT_HOST_PORT`, your Keycloak token). The 172.28.1.6 cluster has no Flight\n", + "gateway deployed, so this is expected to fail there: without a token it asks for your sign-in,\n", + "with one it says the gateway \"can't be reached\". The export then writes no file." + ], + "id": "511131a3" }, { "cell_type": "code", - "execution_count": 12, - "id": "5d690288", + "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "aa= %dds list(METADATA)\n" - ] + "%gpkg export(limit=100, filename=\"catalog_magic_smoke.gpkg\", output_dir=str(INGEST_DIR))" + ], + "id": "3091f085" }, { - "cell_type": "code", - "execution_count": 8, - "id": "6b76127e", + "cell_type": "markdown", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "exporting 3 table(s)/view(s) from catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft to /home/esparza/EEADatahub/EEALakeHouse.python/debugger/output.gpkg, 3 at a time\n", - "✓ 1/3 designation_types ← catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designation_types: attributes, 100 rows, 0.9s\n", - "✓ 2/3 designated_areas ← catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.designated_areas: attributes, 100 rows, 1.0s\n", - "✓ 3/3 protected_site_polygon ← catalog.biodiversity_ecosystems.protected_areas.dfl_natda.draft.protected_site_polygon: features, MULTIPOLYGON, SRS 4326, 100 rows, 2.7s\n", - "done: /home/esparza/EEADatahub/EEALakeHouse.python/debugger/output.gpkg — 3 layer(s), 300 rows in 2.7s\n" - ] - } - ], "source": [ - "result=%gpkg export(limit =100, filename=\"output.gpkg\")" - ] + "## Cleanup\n", + "\n", + "`delete_folder(cascade=True)` removes `TEST_FOLDER` with every table, view and folder inside.\n", + "A principal Polaris doesn't let purge files (e.g. the root client) drops tables from the catalog\n", + "only; the cell after it removes whatever data files are left in the scratch folder's own\n", + "storage location — nothing else." + ], + "id": "028069c5" }, { "cell_type": "code", - "execution_count": 9, - "id": "8cc55f42", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "pushed 1 file(s) to catalog/biodiversity_ecosystems/protected_areas/dfl_natda/draft/deliverables:\n", - " catalog/biodiversity_ecosystems/protected_areas/dfl_natda/draft/deliverables/output.gpkg" - ] - }, - "execution_count": 9, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "%dds push(DELIVERABLES, result, overwrite=True)" - ] + "SCRATCH_LOCATION = verify.rest.namespace_properties(verify.parts(TEST_FOLDER)).get(\"location\")\n", + "%catalog use(None)\n", + "%catalog delete_folder(TEST_FOLDER, cascade=True)\n", + "print(\"folder exists after cleanup:\", verify.exists(TEST_FOLDER))" + ], + "id": "9da6681c" }, { "cell_type": "code", - "execution_count": 13, - "id": "82afbc85", + "execution_count": null, "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "got catalog/biodiversity_ecosystems/protected_areas/dfl_natda/draft/deliverables/output.gpkg (860.0 KB) -> /home/esparza/EEADatahub/EEALakeHouse.python/debugger/output.gpkg" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ - "result=%dds get(DELIVERABLES, \"output.gpkg\")\n", - "result" - ] + "from eea_datalakehouse.catalog.object_store import ObjectStore, s3_credentials\n", + "\n", + "if SCRATCH_LOCATION:\n", + " store = ObjectStore(SETTINGS, s3_credentials(SETTINGS))\n", + " left = [f.url for f in store.list(SCRATCH_LOCATION) if f.url.startswith(SCRATCH_LOCATION)]\n", + " store.delete(left)\n", + " print(f\"removed {len(left)} leftover file(s) under {SCRATCH_LOCATION}\")\n", + "verify.close()" + ], + "id": "e255abde" } ], "metadata": { From 49d5153bb431eb1665ca4c3fcdf5dea2a73ec335 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 14:44:51 +0100 Subject: [PATCH 15/25] %gpkg on Polaris without a Flight gateway: read through the kernel's DuckDB - geopackage/polaris_source.py: PolarisSource, the listing, column types and SELECT both Polaris sources share, and DuckDbSource: rows from the kernel's own DuckDB (the catalog attached as for %catalog, signed in the same way), each table streamed in batches on a cursor of its own, so tables read at once don't share a connection. FlightSource builds on PolarisSource. - open_source: on Polaris, FlightSource when FLIGHT_HOST names a gateway, else DuckDbSource. PolarisSettings.flight_host is empty unless set (flight_configured); the Flight location still defaults to localhost. - DuckDbEngine.stream_batches(); _run lets a stream's StopIteration through. - %ingest table_format="parquet": a new read-only table refuses files already at its location that belong to no table (e.g. an earlier table dropped without purging its files, which would have become rows), and conflict_mode="replace" removes them first. Found running the smoke notebook after an interrupted run. - %gpkg help, README, the .env example and the smoke notebook say so. Checked live against the 172.28.1.6 cluster (no Flight gateway there): %gpkg exported the dfl_natura2000 draft tables (a POLYGON feature layer and attribute tables), and the smoke notebook runs clean end to end. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- debugger/.env.example | 5 +- debugger/test_catalog_magic.ipynb | 8 +- .../catalog/duckdb_engine.py | 22 +++- src/eea_datalakehouse/catalog/settings.py | 16 ++- .../dds_ingestion/polaris_ingest.py | 15 ++- .../geopackage/controller.py | 13 ++- .../geopackage/flight_source.py | 41 +------ .../geopackage/polaris_source.py | 75 ++++++++++++ src/eea_datalakehouse/notebook/magics.py | 5 +- tests/dds_ingestion/test_polaris_ingest.py | 20 ++++ tests/geopackage/test_duckdb_source.py | 108 ++++++++++++++++++ tests/geopackage/test_flight_source.py | 9 +- 13 files changed, 282 insertions(+), 61 deletions(-) create mode 100644 src/eea_datalakehouse/geopackage/polaris_source.py create mode 100644 tests/geopackage/test_duckdb_source.py diff --git a/README.md b/README.md index 8d35baf..af420f0 100644 --- a/README.md +++ b/README.md @@ -474,7 +474,7 @@ unchanged). The commands, their arguments and `%%catalog` stay the same. | `S3_ENDPOINT` [`POLARIS_CATALOG_S3_ENDPOINT_URL` + `_PORT`], `AWS_REGION` | `localhost:9100`, `us-east-1` | the catalog's object store (RustFS) | | `RUSTFS_ACCESS_KEY` / `_SECRET_KEY` [`POLARIS_CATALOG_S3_ACCESS_KEY_ID` / `_SECRET_ACCESS_KEY`] | — | static storage key (vended credentials off, or no STS) | | `RUSTFS_ROLE_ARN`, `POLARIS_CATALOG_S3_BUCKET`, `POLARIS_INGEST_S3_PREFIX` | `…/eea-datalakehouse`, namespace's bucket, `_ingestion` | `%ingest`'s own keys and staging area | -| `FLIGHT_HOST` / `FLIGHT_HOST_PORT` | `localhost` / `8815` | Arrow Flight gateway (`%gpkg`) | +| `FLIGHT_HOST` / `FLIGHT_HOST_PORT` | empty / `8815` | Arrow Flight gateway (`%gpkg`); empty: `%gpkg` reads through the kernel's DuckDB | | `DDS_BASE_URL` | — | Document Service (`%dds`, `publish`) | | `LAKEHOUSE_CA_FILE` [`TRINO_CA_FILE`] | the system's CAs | CA of the stack's HTTPS gateway (Polaris, DuckDB and DDS behind it) | @@ -494,7 +494,9 @@ unchanged). The commands, their arguments and `%%catalog` stay the same. `//` in the public store (you must be a publisher). It is not all or nothing — an error names the views already published — and `partition_by` / `overwrite=False` are not available. -- **`%gpkg`** reads the rows through the Arrow Flight gateway. +- **`%gpkg`** reads the rows through the Arrow Flight gateway (`FLIGHT_HOST`, as + you) — or, with `FLIGHT_HOST` empty, through the kernel's own DuckDB, signed in as + `%catalog` is. - **`%dds`** signs in with your Keycloak token and stores under the namespace's path without the catalog name (`eea_lakehouse.water.bwd` → `water/bwd/`). - **`%ingest`** uploads the files to the catalog's object store — with your diff --git a/debugger/.env.example b/debugger/.env.example index 78e869c..b0f8c57 100644 --- a/debugger/.env.example +++ b/debugger/.env.example @@ -48,8 +48,9 @@ RUSTFS_SECRET_KEY= RUSTFS_ROLE_ARN=arn:aws:iam:::role/eea-datalakehouse POLARIS_CATALOG_S3_BUCKET= POLARIS_INGEST_S3_PREFIX=_ingestion -# %gpkg reads through the Arrow Flight gateway. -FLIGHT_HOST=localhost +# %gpkg reads through the Arrow Flight gateway when FLIGHT_HOST names one; empty: +# through the kernel's own DuckDB, signed in as %catalog is. +FLIGHT_HOST= FLIGHT_HOST_PORT=8815 # --- SDI catalogue (eea_datalakehouse.sdi) ------------------------------------ diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index 6a34d01..6a5b1d3 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -593,10 +593,10 @@ "source": [ "## 9. `%gpkg` — GeoPackage export\n", "\n", - "On Polaris `%gpkg` reads the rows through the EEA Lakehouse Arrow Flight gateway\n", - "(`FLIGHT_HOST`/`FLIGHT_HOST_PORT`, your Keycloak token). The 172.28.1.6 cluster has no Flight\n", - "gateway deployed, so this is expected to fail there: without a token it asks for your sign-in,\n", - "with one it says the gateway \"can't be reached\". The export then writes no file." + "On Polaris `%gpkg` reads the rows through the EEA Lakehouse Arrow Flight gateway when\n", + "`FLIGHT_HOST` names one (as you: your Keycloak token). With `FLIGHT_HOST` empty — the\n", + "172.28.1.6 cluster has no Flight gateway — it reads them through this kernel's own DuckDB,\n", + "signed in as `%catalog` is. Spatial tables become feature layers, the rest attribute tables." ], "id": "511131a3" }, diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py index 373bf33..9b692d2 100644 --- a/src/eea_datalakehouse/catalog/duckdb_engine.py +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -28,7 +28,7 @@ from __future__ import annotations import threading -from collections.abc import Callable, Sequence +from collections.abc import Callable, Iterator, Sequence from typing import Any import pyarrow as pa @@ -227,7 +227,7 @@ def _run(self, sql: str, query: Callable[[Any], Any] | None = None) -> Any: try: connection = self.connection return query(connection) if query else connection.execute(sql) - except CatalogOperationError: + except (CatalogOperationError, StopIteration): raise except Exception as exc: message = str(exc) @@ -261,6 +261,24 @@ def query(connection: Any) -> pa.Table: return self._run(sql, query) + def stream_batches(self, sql: str, batch_size: int = 100_000) -> Iterator[pa.RecordBatch]: + """The result of `sql`, a batch at a time, on a cursor of its own — so several + streams can run at once, from different threads (DuckDB connections aren't + shared across threads; a cursor sees the same attached catalog and secrets).""" + cursor = self._run(sql, lambda connection: connection.cursor()) + try: + relation = self._run(sql, lambda _: cursor.sql(sql)) + reader = getattr(relation, "to_arrow_reader", None) or relation.fetch_arrow_reader + stream = self._run(sql, lambda _: reader(batch_size)) + while True: + try: + batch = self._run(sql, lambda _: stream.read_next_batch()) + except StopIteration: + return + yield batch + finally: + cursor.close() + def record_batches(self, sql: str, batch_size: int = 100_000) -> pa.RecordBatchReader: """The result of `sql`, streamed as Arrow record batches.""" diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py index 663d31c..9e91655 100644 --- a/src/eea_datalakehouse/catalog/settings.py +++ b/src/eea_datalakehouse/catalog/settings.py @@ -138,8 +138,8 @@ class PolarisSettings: - ``ingest_bucket``: ``POLARIS_CATALOG_S3_BUCKET``; the target namespace's bucket. - ``ingest_prefix``: ``POLARIS_INGEST_S3_PREFIX``; ``_ingestion``. - ``role_arn``: ``RUSTFS_ROLE_ARN``; ``arn:aws:iam:::role/eea-datalakehouse``. - - ``flight_host``/``flight_port``: ``FLIGHT_HOST``/``FLIGHT_HOST_PORT``; - ``localhost``/``8815``. + - ``flight_host``/``flight_port``: ``FLIGHT_HOST``/``FLIGHT_HOST_PORT``; empty + (``%gpkg`` then reads through the kernel's DuckDB) / ``8815``. - ``dds_base_url``: ``DDS_BASE_URL`` — the Document Service, which `publish` sends public files through. - ``ca_file``: ``LAKEHOUSE_CA_FILE`` (``TRINO_CA_FILE``) — the CA of the stack's @@ -161,7 +161,7 @@ class PolarisSettings: ingest_bucket: str = "" ingest_prefix: str = DEFAULT_INGEST_PREFIX role_arn: str = DEFAULT_ROLE_ARN - flight_host: str = "localhost" + flight_host: str = "" flight_port: int = DEFAULT_FLIGHT_PORT dds_base_url: str = "" ca_file: str | None = None @@ -173,7 +173,13 @@ def root(self) -> str: @property def flight_location(self) -> str: - return f"grpc://{self.flight_host}:{self.flight_port}" + return f"grpc://{self.flight_host or 'localhost'}:{self.flight_port}" + + @property + def flight_configured(self) -> bool: + """Whether ``FLIGHT_HOST`` names an Arrow Flight gateway. Without one, + ``%gpkg`` reads through the kernel's own DuckDB instead.""" + return bool(self.flight_host) @classmethod def from_env(cls, environ: Mapping[str, str] | None = None) -> PolarisSettings: @@ -213,7 +219,7 @@ def from_env(cls, environ: Mapping[str, str] | None = None) -> PolarisSettings: ingest_bucket=_get(env, "POLARIS_CATALOG_S3_BUCKET"), ingest_prefix=_get(env, "POLARIS_INGEST_S3_PREFIX").strip("/") or DEFAULT_INGEST_PREFIX, role_arn=_get(env, "RUSTFS_ROLE_ARN") or DEFAULT_ROLE_ARN, - flight_host=_get(env, "FLIGHT_HOST") or "localhost", + flight_host=_get(env, "FLIGHT_HOST"), flight_port=port, dds_base_url=_get(env, "DDS_BASE_URL").rstrip("/"), ca_file=lakehouse_ca_file(env), diff --git a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py index c396c4b..2399b19 100644 --- a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py +++ b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py @@ -390,6 +390,16 @@ def _run_parquet(self, plan: _Plan) -> PolarisIngestOutcome: folder_url = f"{location}{self.sub_path}/" if self.sub_path else location creds = self._credentials() store = self._store(creds) + registered = plan.existing == "parquet" + # A new read-only table is everything under its location: files already there + # (e.g. an earlier table dropped without purging its files) would become rows. + strays = [] if registered else store.list(location) + if strays and self.conflict_mode != "replace": + raise CatalogOperationError( + f"{location} already holds {len(strays)} file(s) that belong to no table " + f"(e.g. {strays[0].url}) — they would become part of it: pass " + "conflict_mode='replace' to remove them first, or pick another table_name" + ) present = store.list(folder_url) if present and self.conflict_mode == "fail": raise CatalogOperationError( @@ -409,11 +419,10 @@ def _run_parquet(self, plan: _Plan) -> PolarisIngestOutcome: action = "appended" # more files, or a new sub-folder, in the same table else: action = "created" - registered = plan.existing == "parquet" if plan.existing == "table" and self.conflict_mode == "replace": catalog._drop(plan.namespace, plan.table, "table") # noqa: SLF001 — same package - if self.conflict_mode == "replace" and present: - store.delete([f.url for f in present]) + if self.conflict_mode == "replace" and (present or strays): + store.delete(sorted({f.url for f in [*present, *strays]})) created_registration = False if not registered: # Registered first: Polaris checks the caller may write here before diff --git a/src/eea_datalakehouse/geopackage/controller.py b/src/eea_datalakehouse/geopackage/controller.py index c1d872a..08662fe 100644 --- a/src/eea_datalakehouse/geopackage/controller.py +++ b/src/eea_datalakehouse/geopackage/controller.py @@ -174,14 +174,19 @@ def _channel(self) -> FlightSqlExecutor: def open_source(catalog: Any) -> Any: - """The :class:`DatasetSource` for `catalog`: a :class:`~.flight_source.FlightSource` - (the Arrow Flight gateway) on Polaris, a :class:`DremioSource` on Dremio. Use it - as a context manager: it is closed when the export ends.""" + """The :class:`DatasetSource` for `catalog`. On Polaris: a + :class:`~.flight_source.FlightSource` (the Arrow Flight gateway) when + ``FLIGHT_HOST`` names one, else a :class:`~.polaris_source.DuckDbSource` (this + kernel's DuckDB). On Dremio: a :class:`DremioSource`. Use it as a context manager: + it is closed when the export ends.""" from ..catalog.polaris import PolarisCatalog from .flight_source import FlightSource + from .polaris_source import DuckDbSource if isinstance(catalog, PolarisCatalog): - return FlightSource(catalog) + if catalog.settings.flight_configured: + return FlightSource(catalog) + return DuckDbSource(catalog) return DremioSource(catalog) diff --git a/src/eea_datalakehouse/geopackage/flight_source.py b/src/eea_datalakehouse/geopackage/flight_source.py index 798350e..b91aaa6 100644 --- a/src/eea_datalakehouse/geopackage/flight_source.py +++ b/src/eea_datalakehouse/geopackage/flight_source.py @@ -12,18 +12,14 @@ connection. The gateway has no shared identity to fall back on: without ``KEYCLOAK_ACCESS_TOKEN`` there is nothing to read with. -The listing and the column types come from the Polaris catalog (`PolarisCatalog`, -as `%catalog list()`/`schema()`); the SELECT is the catalog's own -(`PolarisCatalog.source_sql`), so a view is read through its stored SQL and a -read-only Parquet table through ``read_parquet`` — the gateway attaches the -catalog under the same name. +The listing, the column types and the SELECT come from `PolarisSource` (see +``polaris_source.py``) — the gateway attaches the catalog under the same name, so +the catalog's own SQL runs there unchanged. """ from __future__ import annotations -import uuid from collections.abc import Callable, Iterator -from types import TracebackType from typing import Any import pyarrow as pa @@ -32,6 +28,7 @@ from ..catalog.errors import CatalogAuthError, CatalogOperationError from ..catalog.polaris import PolarisCatalog from ..catalog.settings import user_token +from .polaris_source import PolarisSource def _gateway_message(exc: Exception) -> str: @@ -46,7 +43,7 @@ def _client(location: str) -> Any: return flight.FlightClient(location) -class FlightSource: +class FlightSource(PolarisSource): """A :class:`~.controller.DatasetSource` over Polaris and the Flight gateway. `location` defaults to the catalog settings' ``FLIGHT_HOST``/``FLIGHT_HOST_PORT``; @@ -60,7 +57,7 @@ def __init__( token_provider: Callable[[], str | None] = user_token, client: Callable[[str], Any] = _client, ) -> None: - self._catalog = catalog + super().__init__(catalog) self._location = location or catalog.settings.flight_location self._token_provider = token_provider self._client = client @@ -68,32 +65,6 @@ def __init__( def __repr__(self) -> str: return f"FlightSource(location={self._location!r})" - def __enter__(self) -> FlightSource: - return self - - def __exit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - self.close() - - def close(self) -> None: - """Nothing is kept open between streams.""" - - def datasets(self, path: str) -> list[tuple[str, str]]: - return self._catalog.list_dataset_kinds(path) - - def columns(self, path: str) -> list[tuple[str, str]]: - info = self._catalog.gettableitemsfrom(path, idempotency_key=f"gpkg-{uuid.uuid4()}") - return list(info.schema.items()) - - def select_sql(self, path: str, limit: int | None) -> str: - """The SELECT that reads `path` on the gateway, with an optional row limit.""" - sql = f"SELECT * FROM {self._catalog.source_sql(path)}" - return f"{sql} LIMIT {int(limit)}" if limit else sql - def batches(self, sql: str) -> Iterator[pa.RecordBatch]: token = self._token_provider() if not token: diff --git a/src/eea_datalakehouse/geopackage/polaris_source.py b/src/eea_datalakehouse/geopackage/polaris_source.py new file mode 100644 index 0000000..8c2ab63 --- /dev/null +++ b/src/eea_datalakehouse/geopackage/polaris_source.py @@ -0,0 +1,75 @@ +"""`%gpkg`'s sources on Polaris: what both share, and `DuckDbSource`. + +The listing and the column types come from the Polaris catalog (`PolarisCatalog`, +as `%catalog list()`/`schema()`); the SELECT is the catalog's own +(`PolarisCatalog.source_sql`), so a view is read through its stored SQL and a +read-only Parquet table through ``read_parquet``. Where the rows come from differs: + +* :class:`~.flight_source.FlightSource` — the EEA Lakehouse Arrow Flight gateway, + as the signed-in user (``FLIGHT_HOST`` set); +* :class:`DuckDbSource` — this kernel's own DuckDB, the catalog attached as for + `%catalog` (no Flight gateway configured: ``FLIGHT_HOST`` empty). +""" + +from __future__ import annotations + +import uuid +from collections.abc import Iterator +from types import TracebackType + +import pyarrow as pa + +from ..catalog.polaris import PolarisCatalog + +BATCH_ROWS = 64 * 1024 # rows per Arrow batch, as the Flight gateway sends them + + +class PolarisSource: + """The listing, the column types and the SELECT of a Polaris `DatasetSource`; + subclasses supply `batches`.""" + + def __init__(self, catalog: PolarisCatalog) -> None: + self._catalog = catalog + + def __enter__(self) -> PolarisSource: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """Nothing is kept open between streams.""" + + def datasets(self, path: str) -> list[tuple[str, str]]: + return self._catalog.list_dataset_kinds(path) + + def columns(self, path: str) -> list[tuple[str, str]]: + info = self._catalog.gettableitemsfrom(path, idempotency_key=f"gpkg-{uuid.uuid4()}") + return list(info.schema.items()) + + def select_sql(self, path: str, limit: int | None) -> str: + """The SELECT that reads `path`, with an optional row limit.""" + sql = f"SELECT * FROM {self._catalog.source_sql(path)}" + return f"{sql} LIMIT {int(limit)}" if limit else sql + + def batches(self, sql: str) -> Iterator[pa.RecordBatch]: + raise NotImplementedError + + +class DuckDbSource(PolarisSource): + """Rows from this kernel's DuckDB — the catalog's own engine, signed in as for + `%catalog` (your Keycloak token, or the Polaris client credentials). Each stream + runs on a cursor of its own, so tables read at once don't share a connection.""" + + def __repr__(self) -> str: + return "DuckDbSource()" + + def batches(self, sql: str) -> Iterator[pa.RecordBatch]: + for batch in self._catalog.engine.stream_batches(sql, BATCH_ROWS): + if batch.num_rows: + yield batch diff --git a/src/eea_datalakehouse/notebook/magics.py b/src/eea_datalakehouse/notebook/magics.py index f94feb9..2ded8b7 100644 --- a/src/eea_datalakehouse/notebook/magics.py +++ b/src/eea_datalakehouse/notebook/magics.py @@ -582,7 +582,7 @@ def _dds_unknown_folder(line: str, exc: NameError | AttributeError) -> str | Non "filename / output_dir default to .gpkg in the notebook's folder; overwrite=True " "(default) replaces an existing file. workers tables are streamed at once, each over " "its own Arrow Flight channel — from Dremio, or on Polaris from the EEA Lakehouse " - "Arrow Flight gateway.", + "Arrow Flight gateway (FLIGHT_HOST), else from this kernel's DuckDB.", ), ] _GPKG_HELP_NOTE = ( @@ -614,7 +614,8 @@ def _dds_unknown_folder(line: str, exc: NameError | AttributeError) -> str | Non "\n" "Reads with %catalog's connection: DREMIO_BASE_URL / DREMIO_TOKEN on Dremio; on Polaris " "the listing comes from Polaris and the rows from the Arrow Flight gateway " - "(FLIGHT_HOST / FLIGHT_HOST_PORT), as you (KEYCLOAK_ACCESS_TOKEN). Written with sqlite3, " + "(FLIGHT_HOST / FLIGHT_HOST_PORT, as you: KEYCLOAK_ACCESS_TOKEN) — or, with FLIGHT_HOST " + "empty, from this kernel's DuckDB, signed in as %catalog is. Written with sqlite3, " "shapely and pyproj (no GDAL)." ) diff --git a/tests/dds_ingestion/test_polaris_ingest.py b/tests/dds_ingestion/test_polaris_ingest.py index 08b1db1..6996cd6 100644 --- a/tests/dds_ingestion/test_polaris_ingest.py +++ b/tests/dds_ingestion/test_polaris_ingest.py @@ -504,3 +504,23 @@ def test_diagnose_reports_a_missing_bucket( session.ingest(_folder(tmp_path), "water.bwd", data_format="parquet") session.diagnose() assert "✗ storage: the bucket of s3://no_such_bucket/" in capsys.readouterr().out + + +def test_a_new_parquet_table_refuses_stray_files_at_its_location( + tmp_path: Path, bucket: Path +) -> None: + """Found against the live stack: files of an earlier table dropped without purge + were silently read as part of a new read-only table.""" + catalog, rest, _ = _setup() + stray = bucket / "lake/catalog/water/bwd/temps/data/old.parquet" + stray.parent.mkdir(parents=True) + pq.write_table(pa.table({"id": [9]}), stray) + args = {"table_format": "parquet", "table_name": "temps", "sub_path": "2026"} + + with pytest.raises(CatalogOperationError, match="belong to no table"): + _ingest(catalog, _folder(tmp_path), bucket, **args).run() + assert (("water", "bwd"), "temps") not in rest.generic # nothing registered + assert _files(bucket) == ["lake/catalog/water/bwd/temps/data/old.parquet"] + + _ingest(catalog, _folder(tmp_path), bucket, conflict_mode="replace", **args).run() + assert _files(bucket) == ["lake/catalog/water/bwd/temps/2026/a.parquet"] diff --git a/tests/geopackage/test_duckdb_source.py b/tests/geopackage/test_duckdb_source.py new file mode 100644 index 0000000..3439f0a --- /dev/null +++ b/tests/geopackage/test_duckdb_source.py @@ -0,0 +1,108 @@ +"""`%gpkg` on Polaris without a Flight gateway: rows from the kernel's DuckDB (`DuckDbSource`).""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import cast + +import duckdb +import pytest +import shapely + +from catalog.polaris_fakes import FakePolarisRest # tests/catalog, on sys.path via pytest +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogOperationError +from eea_datalakehouse.catalog.polaris import PolarisCatalog +from eea_datalakehouse.catalog.polaris_rest import PolarisRestClient +from eea_datalakehouse.catalog.settings import PolarisSettings +from eea_datalakehouse.geopackage.controller import GpkgController, open_source +from eea_datalakehouse.geopackage.polaris_source import DuckDbSource + +AREA = "eea_lakehouse.water.bwd" +_SCHEMA = {"current-schema-id": 0, "schemas": [{"schema-id": 0, "fields": []}]} + + +def _catalog(rows: int = 3) -> PolarisCatalog: + """A PolarisCatalog whose DuckDB holds the tables in a local database attached as + "eea_lakehouse" — the same names the Iceberg catalog has when attached.""" + connection = duckdb.connect() + connection.execute("ATTACH ':memory:' AS eea_lakehouse") + connection.execute('CREATE SCHEMA eea_lakehouse."water.bwd"') + points = ", ".join( + f"({i}, 'site {i}', from_hex('{shapely.to_wkb(shapely.Point(10 + i, 45)).hex()}'), 4326)" + for i in range(rows) + ) + connection.execute( + 'CREATE TABLE eea_lakehouse."water.bwd"."stations" ' + "(id BIGINT, name VARCHAR, geom BLOB, srid INTEGER)" + ) + connection.execute(f'INSERT INTO eea_lakehouse."water.bwd"."stations" VALUES {points}') + connection.execute( + 'CREATE TABLE eea_lakehouse."water.bwd"."counts" AS ' + "SELECT range AS n, range * 2 AS twice FROM range(200000)" + ) + connection.execute('CREATE TABLE eea_lakehouse."water.bwd"."empty" (id BIGINT)') + + rest = ( + FakePolarisRest() + .add_table("water.bwd.stations", _SCHEMA) + .add_table("water.bwd.counts", _SCHEMA) + .add_table( + "water.bwd.empty", + { + "current-schema-id": 0, + "schemas": [{"schema-id": 0, "fields": [{"id": 1, "name": "id", "type": "long"}]}], + "current-snapshot-id": -1, + }, + ) + .add_view("water.bwd.latest", 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations"') + ) + settings = PolarisSettings(uri="http://polaris.test/api/catalog") + engine = DuckDbEngine(settings, connect=lambda: None, token_provider=lambda: "t") + engine._connection = connection # noqa: SLF001 — skip the Iceberg ATTACH + return PolarisCatalog(settings, rest=cast(PolarisRestClient, rest), engine=engine) + + +def test_without_a_flight_gateway_the_kernel_duckdb_is_used() -> None: + assert isinstance(open_source(_catalog()), DuckDbSource) + + +def test_batches_stream_on_their_own_cursor() -> None: + source = DuckDbSource(_catalog()) + batches = list(source.batches(source.select_sql(f"{AREA}.counts", None))) + assert len(batches) > 1 # streamed, not one table + assert sum(b.num_rows for b in batches) == 200000 + + +def test_a_view_is_read_through_its_sql() -> None: + source = DuckDbSource(_catalog()) + rows = [ + r for b in source.batches(source.select_sql(f"{AREA}.latest", 2)) for r in b.to_pylist() + ] + assert [r["name"] for r in rows] == ["site 0", "site 1"] + + +def test_a_query_error_is_a_catalog_error() -> None: + source = DuckDbSource(_catalog()) + with pytest.raises(CatalogOperationError, match="in: SELECT \\* FROM nowhere"): + list(source.batches("SELECT * FROM nowhere")) + + +def test_export_reads_tables_at_once_into_a_geopackage(tmp_path: Path) -> None: + output = tmp_path / "bwd.gpkg" + with DuckDbSource(_catalog()) as source: + report = GpkgController(source).export(AREA, output, limit=None, workers=4) + + layers = {layer.layer: layer for layer in report.layers} + assert layers["stations"].kind == "features" and layers["stations"].rows == 3 + assert layers["latest"].kind == "features" + assert layers["counts"].rows == 200000 + assert layers["empty"].rows == 0 + with sqlite3.connect(output) as db: + assert db.execute('SELECT COUNT(*) FROM "counts"').fetchone() == (200000,) + assert db.execute('SELECT name FROM "stations" ORDER BY id').fetchall() == [ + ("site 0",), + ("site 1",), + ("site 2",), + ] diff --git a/tests/geopackage/test_flight_source.py b/tests/geopackage/test_flight_source.py index 6c8b4d2..04f0d9f 100644 --- a/tests/geopackage/test_flight_source.py +++ b/tests/geopackage/test_flight_source.py @@ -5,6 +5,7 @@ import sqlite3 import threading from collections.abc import Iterator +from dataclasses import replace from pathlib import Path from typing import Any, cast @@ -21,6 +22,7 @@ from eea_datalakehouse.catalog.settings import PolarisSettings from eea_datalakehouse.geopackage.controller import DremioSource, GpkgController, open_source from eea_datalakehouse.geopackage.flight_source import FlightSource +from eea_datalakehouse.geopackage.polaris_source import DuckDbSource AREA = "eea_lakehouse.water.bwd" TOKEN = "user-jwt" @@ -167,8 +169,11 @@ def test_an_unreachable_gateway() -> None: list(source.batches("SELECT 1")) -def test_open_source_picks_flight_on_polaris() -> None: - assert isinstance(open_source(_catalog()), FlightSource) +def test_open_source_picks_flight_when_a_gateway_is_configured() -> None: + catalog = _catalog() + assert isinstance(open_source(catalog), DuckDbSource) # FLIGHT_HOST empty + catalog._settings = replace(catalog.settings, flight_host="flight") # noqa: SLF001 + assert isinstance(open_source(catalog), FlightSource) assert isinstance(open_source(object()), DremioSource) From 7006948ca5693d0dfc0fc54b3618c76b75df83b4 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 14:52:58 +0100 Subject: [PATCH 16/25] Sign in to Keycloak outside JupyterLab with the device-code flow - catalog/keycloak.py: login() runs OAuth 2.0 device authorization against KEYCLOAK_URL with a public client (KEYCLOAK_CLIENT_ID, default eea-notebook): it shows a link and a code, waits while the user signs in in a browser, and keeps the session. settings.user_token() then returns that session's access token, renewed with the refresh token shortly before it expires, so Polaris, DuckDB, DDS, the Flight gateway and RustFS STS act as that user. logout(). No password passes through it. - DuckDbEngine reopens its connection when the user's token changes (renewed, or a new sign-in): the connection keeps the token it was opened with. - The smoke notebook signs in (as eea-admin) in its first cell when KEYCLOAK_URL is set and no token is present. - Flight source tests: wait until the test server answers and connect to 127.0.0.1 - the cause of an intermittent "connection refused" failure. - README and debugger/.env.example document it. The realm needs the public client: EEALakeHouse's realm files gain eea-notebook (device-code flow, the jupyterlab client's scopes). Co-Authored-By: Claude Opus 5.5 --- README.md | 15 ++ debugger/.env.example | 5 + debugger/test_catalog_magic.ipynb | 23 +- .../catalog/duckdb_engine.py | 15 +- src/eea_datalakehouse/catalog/keycloak.py | 221 ++++++++++++++++++ src/eea_datalakehouse/catalog/settings.py | 8 +- tests/catalog/test_duckdb_engine.py | 1 + tests/catalog/test_keycloak.py | 190 +++++++++++++++ tests/geopackage/test_duckdb_source.py | 1 + tests/geopackage/test_flight_source.py | 27 ++- 10 files changed, 493 insertions(+), 13 deletions(-) create mode 100644 src/eea_datalakehouse/catalog/keycloak.py create mode 100644 tests/catalog/test_keycloak.py diff --git a/README.md b/README.md index af420f0..9581d16 100644 --- a/README.md +++ b/README.md @@ -469,6 +469,7 @@ unchanged). The commands, their arguments and `%%catalog` stay the same. | `POLARIS_URI` | `http://localhost:/api/catalog` | Iceberg REST base | | `POLARIS_CATALOG` [`POLARIS_CATALOG_NAME`] | `eea_lakehouse` | the catalog, and the root of every path | | `KEYCLOAK_ACCESS_TOKEN` | — | you: Polaris, the Flight gateway and DDS apply your grants | +| `KEYCLOAK_URL`, `KEYCLOAK_CLIENT_ID` | —, `eea-notebook` | outside JupyterLab: the realm to sign in to with `keycloak.login()` (below) | | `POLARIS_CLIENT_ID` / `_SECRET` [`POLARIS_ROOT_CLIENT_ID` / `_SECRET`] | — | `%catalog` only, when there is no user token | | `POLARIS_VENDED_CREDENTIALS` | off | per-table storage keys from Polaris | | `S3_ENDPOINT` [`POLARIS_CATALOG_S3_ENDPOINT_URL` + `_PORT`], `AWS_REGION` | `localhost:9100`, `us-east-1` | the catalog's object store (RustFS) | @@ -478,6 +479,19 @@ unchanged). The commands, their arguments and `%%catalog` stay the same. | `DDS_BASE_URL` | — | Document Service (`%dds`, `publish`) | | `LAKEHOUSE_CA_FILE` [`TRINO_CA_FILE`] | the system's CAs | CA of the stack's HTTPS gateway (Polaris, DuckDB and DDS behind it) | +**Signing in outside JupyterLab.** Inside the stack's JupyterLab your token is +already in `KEYCLOAK_ACCESS_TOKEN`. Anywhere else, sign in once with the device +login — it prints a link and a code, you sign in in a browser, and the library +keeps that user's token renewed for every call: + +```python +from eea_datalakehouse.catalog.keycloak import login +login() # KEYCLOAK_URL, e.g. https:///auth/realms/eea_datalakehouse +``` + +It needs a public client of the realm with the device-code flow and the same +client scopes as `jupyterlab` (`eea-notebook` in EEALakeHouse's realm files). + **What is different on Polaris** - **Paths** start with the catalog's name instead of `catalog`: @@ -673,6 +687,7 @@ context itself — raises `CatalogSessionError` if none is set yet: | `catalog/polaris_rest.py` | `PolarisRestClient` — Iceberg REST (namespaces, tables, views, properties) and Polaris generic tables | | `catalog/duckdb_engine.py` | `DuckDbEngine` — the kernel's DuckDB with the Polaris catalog attached | | `catalog/object_store.py` | `ObjectStore` / `s3_credentials` — the catalog's RustFS from the kernel (the user's STS keys, else the static key) | +| `catalog/keycloak.py` | `login()` — device-code sign-in to Keycloak outside JupyterLab; the token is renewed for every client | | `catalog/dds_public.py` | `PublicDataClient` — the Document Service's public data store, for `publish` on Polaris | | `geopackage/flight_source.py` | `FlightSource` — `%gpkg` rows from Polaris over the Arrow Flight gateway | | `dds_ingestion/polaris_ingest.py` | `PolarisIngest` / `promote` — `%ingest` on Polaris: upload, then an Iceberg or a read-only Parquet table | diff --git a/debugger/.env.example b/debugger/.env.example index b0f8c57..2734726 100644 --- a/debugger/.env.example +++ b/debugger/.env.example @@ -30,6 +30,11 @@ POLARIS_CATALOG=eea_lakehouse # Without it, Polaris client credentials [POLARIS_ROOT_CLIENT_ID / _SECRET] — # enough for %catalog, not for %gpkg, %dds or publishing, which need a real user. KEYCLOAK_ACCESS_TOKEN= +# Outside JupyterLab: sign in with eea_datalakehouse.catalog.keycloak.login() (device +# code: a link and a code to open in a browser). The realm's URL, and a public client +# of it with the device-code flow (EEALakeHouse's realm files define eea-notebook). +KEYCLOAK_URL= +KEYCLOAK_CLIENT_ID=eea-notebook POLARIS_CLIENT_ID= POLARIS_CLIENT_SECRET= # true: Polaris hands out per-table storage keys and the static key below is unused. diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index 6a5b1d3..551a1c8 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -19,10 +19,10 @@ "\n", "1. Port-forward RustFS (the catalog's object store) — the command is at the top of\n", " `debugger/.env`.\n", - "2. Paste a fresh Keycloak access token into `KEYCLOAK_ACCESS_TOKEN` in `debugger/.env`\n", - " (Polaris through the gateway accepts nothing else; tokens expire after a few minutes) —\n", - " or switch `POLARIS_URI` to a port-forwarded Polaris to run as the root client\n", - " (`%dds` then can't run).\n", + "2. Run the next cell: it signs you in to Keycloak with the device login — it shows a link\n", + " and a code; open it in a browser and sign in as **eea-admin**. The notebook then runs as\n", + " that user (Polaris, DuckDB, DDS, RustFS), and the token is renewed by itself. Needs\n", + " `KEYCLOAK_URL` in `debugger/.env` and the realm's `eea-notebook` client.\n", "3. Restart the kernel after changing `debugger/.env`: it is read once, in the next cell." ], "id": "64fef81a" @@ -59,20 +59,25 @@ " _key, _, _value = _line.partition(\"=\")\n", " os.environ.setdefault(_key.strip(), _value.strip())\n", "\n", + "from eea_datalakehouse.catalog import keycloak\n", + "from eea_datalakehouse.catalog.object_store import token_username\n", "from eea_datalakehouse.catalog.settings import PolarisSettings, backend_name, user_token\n", "\n", + "if os.environ.get(\"KEYCLOAK_URL\") and not user_token():\n", + " keycloak.login() # prints a link and a code — sign in there as eea-admin\n", + "\n", "SETTINGS = PolarisSettings.from_env()\n", "print(f\"env file {ENV_PATH}\")\n", "print(f\"backend {backend_name()}\")\n", "print(f\"POLARIS_URI {SETTINGS.uri}\")\n", "print(f\"catalog (root) {SETTINGS.catalog}\")\n", "print(f\"CA file {SETTINGS.ca_file or ''}\")\n", - "print(f\"signed in as {'your Keycloak token' if user_token() else 'Polaris client ' + repr(SETTINGS.client_id) if SETTINGS.client_id else ''}\")\n", + "print(f\"signed in as {token_username(user_token()) if user_token() else 'Polaris client ' + repr(SETTINGS.client_id) if SETTINGS.client_id else ''}\")\n", "print(f\"object store {SETTINGS.s3_endpoint}\")\n", "print(f\"DDS {SETTINGS.dds_base_url or ''}\")\n", "assert backend_name() == \"polaris\", \"set EEA_CATALOG_BACKEND=polaris in debugger/.env\"\n", "if SETTINGS.uri.startswith(\"https://\") and not user_token():\n", - " print(\"\\n!! no KEYCLOAK_ACCESS_TOKEN: Polaris behind the gateway will refuse every call\")" + " print(\"\\n!! nobody signed in: Polaris behind the gateway will refuse every call\")" ], "id": "3f7af2e9" }, @@ -559,9 +564,9 @@ "source": [ "## 8. `%dds` — the context's document folders\n", "\n", - "On Polaris `%dds` signs in with your Keycloak token and stores under the namespace's path\n", - "without the catalog name (`…non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/…`).\n", - "Needs `KEYCLOAK_ACCESS_TOKEN`." + "On Polaris `%dds` signs in with your Keycloak token (the eea-admin sign-in above) and stores\n", + "under the namespace's path without the catalog name\n", + "(`…non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/…`)." ], "id": "134d95ff" }, diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py index 9b692d2..1bf6a14 100644 --- a/src/eea_datalakehouse/catalog/duckdb_engine.py +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -77,6 +77,7 @@ def __init__( self._connect = connect self._token_provider = token_provider self._connection: Any = None + self._token: str | None = None # the token the connection was opened with self._lock = threading.Lock() def __repr__(self) -> str: @@ -103,11 +104,21 @@ def table_ref(self, namespace: Sequence[str], name: str) -> str: @property def connection(self) -> Any: - """The DuckDB connection, opened (and the catalog attached) on first use.""" + """The DuckDB connection, opened (and the catalog attached) on first use — and + again when the user's token has changed (renewed, or a new sign-in), since the + connection keeps the token it was opened with.""" + token = self._token_provider() + stale = None with self._lock: + if self._connection is not None and token != self._token: + stale, self._connection = self._connection, None if self._connection is None: self._connection = self._open() - return self._connection + self._token = token + connection = self._connection + if stale is not None: + stale.close() + return connection def reset(self) -> None: """Close the connection; the next query opens a new one (with a fresh token).""" diff --git a/src/eea_datalakehouse/catalog/keycloak.py b/src/eea_datalakehouse/catalog/keycloak.py new file mode 100644 index 0000000..ae2e261 --- /dev/null +++ b/src/eea_datalakehouse/catalog/keycloak.py @@ -0,0 +1,221 @@ +"""Sign in to the EEA Lakehouse Keycloak from a notebook or script — the device-code flow. + +Inside the stack's JupyterLab the signed-in user's token is already in +``KEYCLOAK_ACCESS_TOKEN``. Anywhere else (a laptop, the debugger notebooks), +`login` gets one:: + + from eea_datalakehouse.catalog.keycloak import login + login() # prints a link and a code; sign in there, in any browser + +It uses OAuth 2.0 device authorization (RFC 8628) with a public client of the +realm (``KEYCLOAK_CLIENT_ID``, default ``eea-notebook``, which must allow the +device-code flow and give the lakehouse's audiences and ``principal_roles`` claim, +as the ``jupyterlab`` client does). No password goes through this code. + +Afterwards `settings.user_token` returns this session's access token — so +Polaris, DuckDB, the Document Service, the Flight gateway and RustFS STS all act +as you — and renews it with the refresh token shortly before it expires, for as +long as Keycloak's session lasts. `logout` ends it. + +Settings: ``KEYCLOAK_URL`` — the realm's URL, e.g. +``https://172.28.1.6:31443/auth/realms/eea_datalakehouse``; ``KEYCLOAK_CLIENT_ID``; +``LAKEHOUSE_CA_FILE`` when Keycloak's certificate is signed by the stack's own CA. +""" + +from __future__ import annotations + +import os +import threading +import time +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from typing import Any + +import httpx + +from .errors import CatalogAuthError +from .settings import lakehouse_ca_file, tls_verify + +DEFAULT_CLIENT_ID = "eea-notebook" +_DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" +_RENEW_MARGIN = 60.0 # seconds before expiry when the access token is renewed +_ENV_TOKEN = "KEYCLOAK_ACCESS_TOKEN" + + +@dataclass +class KeycloakSession: + """A signed-in user's tokens and where to renew them.""" + + realm_url: str + client_id: str + access_token: str + refresh_token: str | None + expires_at: float # time.monotonic() when the access token expires + verify: str | bool = True + + def __repr__(self) -> str: # never the tokens + return f"KeycloakSession(realm_url={self.realm_url!r}, client_id={self.client_id!r})" + + @property + def token_url(self) -> str: + return f"{self.realm_url}/protocol/openid-connect/token" + + +_session: KeycloakSession | None = None +_lock = threading.Lock() + + +def _env(environ: Mapping[str, str] | None) -> Mapping[str, str]: + return os.environ if environ is None else environ + + +def _error(response: httpx.Response) -> str: + try: + body = response.json() + except ValueError: + return f"HTTP {response.status_code}" + return str(body.get("error_description") or body.get("error") or response.status_code) + + +def _session_from( + body: Mapping[str, Any], realm_url: str, client_id: str, verify: str | bool +) -> KeycloakSession: + return KeycloakSession( + realm_url=realm_url, + client_id=client_id, + access_token=str(body["access_token"]), + refresh_token=body.get("refresh_token"), + expires_at=time.monotonic() + float(body.get("expires_in") or 300), + verify=verify, + ) + + +def login( + realm_url: str | None = None, + client_id: str | None = None, + *, + environ: Mapping[str, str] | None = None, + show: Callable[[str], None] = print, + http: httpx.Client | None = None, + timeout: float | None = None, +) -> KeycloakSession: + """Sign in with the device-code flow — see the module docstring. Shows the + link and code with `show`, waits until you have signed in (or the code + expires), and makes the session the one `settings.user_token` returns.""" + global _session + env = _env(environ) + realm_url = (realm_url or env.get("KEYCLOAK_URL") or "").rstrip("/") + if not realm_url: + raise CatalogAuthError( + "KEYCLOAK_URL is not set — the realm's URL, e.g. " + "https:///auth/realms/eea_datalakehouse" + ) + client_id = client_id or env.get("KEYCLOAK_CLIENT_ID") or DEFAULT_CLIENT_ID + verify = tls_verify(lakehouse_ca_file(env)) + client = http or httpx.Client(timeout=30, verify=verify) + try: + start = client.post( + f"{realm_url}/protocol/openid-connect/auth/device", + data={"client_id": client_id, "scope": "openid"}, + ) + if start.status_code >= 400: + raise CatalogAuthError( + f"Keycloak refused to start a device login for client {client_id!r}: " + f"{_error(start)} — the client must exist in the realm and allow the " + "device-code flow" + ) + device = start.json() + link = device.get("verification_uri_complete") or device["verification_uri"] + show( + f"Sign in to the EEA Lakehouse: open {link}" + + ("" if "verification_uri_complete" in device else f" and enter {device['user_code']}") + + f" (code {device['user_code']})" + ) + interval = float(device.get("interval") or 5) + deadline = time.monotonic() + float(timeout or device.get("expires_in") or 600) + while True: + if time.monotonic() > deadline: + raise CatalogAuthError("the sign-in was not completed in time — run login() again") + time.sleep(interval) + answer = client.post( + f"{realm_url}/protocol/openid-connect/token", + data={ + "grant_type": _DEVICE_GRANT, + "device_code": device["device_code"], + "client_id": client_id, + }, + ) + if answer.status_code < 400: + break + error = (answer.json() if answer.content else {}).get("error") + if error == "authorization_pending": + continue + if error == "slow_down": + interval += 5 + continue + raise CatalogAuthError(f"the sign-in did not complete: {_error(answer)}") + session = _session_from(answer.json(), realm_url, client_id, verify) + finally: + if http is None: + client.close() + with _lock: + _session = session + if environ is None: + os.environ[_ENV_TOKEN] = session.access_token + show(f"signed in as {_username(session.access_token) or 'unknown'}") + return session + + +def _username(token: str) -> str | None: + from .object_store import token_username + + return token_username(token) + + +def _renew(session: KeycloakSession, http: httpx.Client | None = None) -> KeycloakSession: + if not session.refresh_token: + raise CatalogAuthError("your sign-in expired and can't be renewed — run login() again") + client = http or httpx.Client(timeout=30, verify=session.verify) + try: + response = client.post( + session.token_url, + data={ + "grant_type": "refresh_token", + "refresh_token": session.refresh_token, + "client_id": session.client_id, + }, + ) + finally: + if http is None: + client.close() + if response.status_code >= 400: + raise CatalogAuthError( + f"your sign-in could not be renewed ({_error(response)}) — run login() again" + ) + return _session_from(response.json(), session.realm_url, session.client_id, session.verify) + + +def current_token(http: httpx.Client | None = None) -> str | None: + """The signed-in session's access token, renewed when it is about to expire; + None when `login` was not used.""" + global _session + with _lock: + session = _session + if session is None: + return None + if time.monotonic() > session.expires_at - _RENEW_MARGIN: + session = _session = _renew(session, http) + os.environ[_ENV_TOKEN] = session.access_token + return session.access_token + + +def logout() -> None: + """Forget the session (the token in ``KEYCLOAK_ACCESS_TOKEN`` too).""" + global _session + with _lock: + _session = None + os.environ.pop(_ENV_TOKEN, None) + + +def active() -> bool: + return _session is not None diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py index 9e91655..3e612bf 100644 --- a/src/eea_datalakehouse/catalog/settings.py +++ b/src/eea_datalakehouse/catalog/settings.py @@ -83,7 +83,13 @@ def user_token(environ: Mapping[str, str] | None = None) -> str | None: """The signed-in user's Keycloak access token (``KEYCLOAK_ACCESS_TOKEN``), or None. Read on every call, not once: the Kubernetes deployment refreshes it in the - server's environment, and a kernel started later sees the new one.""" + server's environment, and a kernel started later sees the new one. After + `keycloak.login()` it is that session's token, renewed before it expires.""" + if environ is None: + from . import keycloak # here, not at the top: keycloak imports this module + + if keycloak.active(): + return keycloak.current_token() env = os.environ if environ is None else environ return _get(env, "KEYCLOAK_ACCESS_TOKEN") or None diff --git a/tests/catalog/test_duckdb_engine.py b/tests/catalog/test_duckdb_engine.py index 867b5bc..16c0dd7 100644 --- a/tests/catalog/test_duckdb_engine.py +++ b/tests/catalog/test_duckdb_engine.py @@ -164,6 +164,7 @@ def _real_engine() -> DuckDbEngine: """An engine on a plain in-memory DuckDB, without the catalog (no Polaris here).""" engine = DuckDbEngine(PolarisSettings(uri=URI), token_provider=lambda: "t") engine._connection = duckdb.connect() # noqa: SLF001 — skip the ATTACH + engine._token = "t" # noqa: SLF001 — opened with the current token return engine diff --git a/tests/catalog/test_keycloak.py b/tests/catalog/test_keycloak.py new file mode 100644 index 0000000..37f6399 --- /dev/null +++ b/tests/catalog/test_keycloak.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import os +from collections.abc import Iterator +from typing import Any + +import httpx +import pytest +import respx + +from eea_datalakehouse.catalog import keycloak +from eea_datalakehouse.catalog.duckdb_engine import DuckDbEngine +from eea_datalakehouse.catalog.errors import CatalogAuthError +from eea_datalakehouse.catalog.settings import PolarisSettings, user_token + +REALM = "https://gateway.test/auth/realms/eea_datalakehouse" +DEVICE = f"{REALM}/protocol/openid-connect/auth/device" +TOKEN = f"{REALM}/protocol/openid-connect/token" +# A JWT whose payload is {"preferred_username": "eea-admin"} +JWT = "x.eyJwcmVmZXJyZWRfdXNlcm5hbWUiOiAiZWVhLWFkbWluIn0.y" +ENV = {"KEYCLOAK_URL": REALM} + + +@pytest.fixture(autouse=True) +def _no_session(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + monkeypatch.setattr(keycloak.time, "sleep", lambda seconds: None) + monkeypatch.delenv("KEYCLOAK_ACCESS_TOKEN", raising=False) + keycloak.logout() + yield + keycloak.logout() + + +def _device(**extra: Any) -> httpx.Response: + return httpx.Response( + 200, + json={ + "device_code": "dev-123", + "user_code": "WDJB-MJHT", + "verification_uri": f"{REALM}/device", + "verification_uri_complete": f"{REALM}/device?user_code=WDJB-MJHT", + "expires_in": 600, + "interval": 5, + **extra, + }, + ) + + +def _tokens(access: str = JWT, expires_in: int = 43200) -> httpx.Response: + return httpx.Response( + 200, json={"access_token": access, "refresh_token": "refresh-1", "expires_in": expires_in} + ) + + +@respx.mock +def test_device_login_waits_for_the_user_then_holds_the_token() -> None: + start = respx.post(DEVICE).mock(return_value=_device()) + poll = respx.post(TOKEN).mock( + side_effect=[ + httpx.Response(400, json={"error": "authorization_pending"}), + httpx.Response(400, json={"error": "slow_down"}), + _tokens(), + ] + ) + shown: list[str] = [] + + session = keycloak.login(environ=ENV, show=shown.append) + + assert dict(x.split("=") for x in start.calls[0].request.content.decode().split("&")) == { + "client_id": "eea-notebook", + "scope": "openid", + } + form = poll.calls[0].request.content.decode() + assert "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code" in form + assert "device_code=dev-123" in form + assert shown[0] == ( + f"Sign in to the EEA Lakehouse: open {REALM}/device?user_code=WDJB-MJHT (code WDJB-MJHT)" + ) + assert shown[-1] == "signed in as eea-admin" + assert session.access_token == JWT + assert keycloak.active() + assert user_token() == JWT # every client asks this + + +@respx.mock +def test_without_a_complete_link_the_code_is_shown() -> None: + respx.post(DEVICE).mock( + return_value=httpx.Response( + 200, + json={"device_code": "d", "user_code": "ABCD", "verification_uri": f"{REALM}/device"}, + ) + ) + respx.post(TOKEN).mock(return_value=_tokens()) + shown: list[str] = [] + keycloak.login(environ=ENV, show=shown.append) + assert shown[0].startswith(f"Sign in to the EEA Lakehouse: open {REALM}/device and enter ABCD") + + +@respx.mock +def test_a_refused_sign_in_is_an_auth_error() -> None: + respx.post(DEVICE).mock(return_value=_device()) + respx.post(TOKEN).mock( + return_value=httpx.Response( + 400, json={"error": "access_denied", "error_description": "denied"} + ) + ) + with pytest.raises(CatalogAuthError, match="did not complete: denied"): + keycloak.login(environ=ENV, show=lambda line: None) + assert not keycloak.active() + + +@respx.mock +def test_a_client_without_the_device_flow_says_so() -> None: + respx.post(DEVICE).mock(return_value=httpx.Response(401, json={"error": "unauthorized_client"})) + with pytest.raises(CatalogAuthError, match="allow the device-code flow"): + keycloak.login(environ=ENV, show=lambda line: None) + + +def test_login_needs_the_realm_url() -> None: + with pytest.raises(CatalogAuthError, match="KEYCLOAK_URL"): + keycloak.login(environ={}, show=lambda line: None) + + +@respx.mock +def test_the_token_is_renewed_before_it_expires() -> None: + respx.post(DEVICE).mock(return_value=_device()) + refresh = respx.post(TOKEN).mock( + side_effect=[_tokens(access="first", expires_in=30), _tokens(access="second")] + ) + keycloak.login(environ=ENV, show=lambda line: None) + + assert keycloak.current_token() == "second" # 30 s left < the renewal margin + assert "grant_type=refresh_token" in refresh.calls[1].request.content.decode() + assert os.environ["KEYCLOAK_ACCESS_TOKEN"] == "second" + assert keycloak.current_token() == "second" # not renewed again + assert refresh.call_count == 2 + + +@respx.mock +def test_a_renewal_that_fails_says_to_sign_in_again() -> None: + respx.post(DEVICE).mock(return_value=_device()) + respx.post(TOKEN).mock( + side_effect=[ + _tokens(expires_in=10), + httpx.Response( + 400, json={"error": "invalid_grant", "error_description": "Session not active"} + ), + ] + ) + keycloak.login(environ=ENV, show=lambda line: None) + with pytest.raises(CatalogAuthError, match="Session not active.*login\\(\\) again"): + keycloak.current_token() + + +def test_logout_forgets_the_session() -> None: + os.environ["KEYCLOAK_ACCESS_TOKEN"] = "x" + keycloak.logout() + assert not keycloak.active() + assert user_token() is None + + +def test_duckdb_reconnects_when_the_token_changes() -> None: + class Connection: + def __init__(self) -> None: + self.statements: list[str] = [] + self.closed = False + + def execute(self, sql: str) -> Any: + self.statements.append(sql) + return self + + def close(self) -> None: + self.closed = True + + made: list[Connection] = [] + current = {"token": "first"} + + def connect() -> Connection: + made.append(Connection()) + return made[-1] + + engine = DuckDbEngine( + PolarisSettings(uri="http://p"), connect=connect, token_provider=lambda: current["token"] + ) + engine.execute("SELECT 1") + engine.execute("SELECT 2") + current["token"] = "renewed" + engine.execute("SELECT 3") + + assert len(made) == 2 and made[0].closed + assert any("TOKEN 'renewed'" in s for s in made[1].statements) diff --git a/tests/geopackage/test_duckdb_source.py b/tests/geopackage/test_duckdb_source.py index 3439f0a..302c7a5 100644 --- a/tests/geopackage/test_duckdb_source.py +++ b/tests/geopackage/test_duckdb_source.py @@ -61,6 +61,7 @@ def _catalog(rows: int = 3) -> PolarisCatalog: settings = PolarisSettings(uri="http://polaris.test/api/catalog") engine = DuckDbEngine(settings, connect=lambda: None, token_provider=lambda: "t") engine._connection = connection # noqa: SLF001 — skip the Iceberg ATTACH + engine._token = "t" # noqa: SLF001 — opened with the current token return PolarisCatalog(settings, rest=cast(PolarisRestClient, rest), engine=engine) diff --git a/tests/geopackage/test_flight_source.py b/tests/geopackage/test_flight_source.py index 04f0d9f..bfa7082 100644 --- a/tests/geopackage/test_flight_source.py +++ b/tests/geopackage/test_flight_source.py @@ -4,6 +4,7 @@ import sqlite3 import threading +import time from collections.abc import Iterator from dataclasses import replace from pathlib import Path @@ -55,6 +56,25 @@ def do_get(self, context: Any, ticket: flight.Ticket) -> flight.RecordBatchStrea return flight.RecordBatchStream(self.tables[sql]) +def _wait_until_serving(port: int, seconds: float = 10.0) -> None: + """Block until the test server answers (a refused sign-in counts): the thread + may not be serving yet when the first test call is made.""" + deadline = time.monotonic() + seconds + while True: + client = flight.FlightClient(f"grpc://127.0.0.1:{port}") + try: + list(client.list_actions()) + return + except flight.FlightUnauthenticatedError: + return + except flight.FlightUnavailableError: + if time.monotonic() > deadline: + raise + time.sleep(0.05) + finally: + client.close() + + @pytest.fixture def gateway() -> Iterator[Gateway]: stations = pa.table( @@ -81,6 +101,7 @@ def gateway() -> Iterator[Gateway]: ) thread = threading.Thread(target=server.serve, daemon=True) thread.start() + _wait_until_serving(server.port) yield server server.shutdown() @@ -111,7 +132,11 @@ def _catalog(port: int = 1) -> PolarisCatalog: def _source(gateway: Gateway, token: str | None = TOKEN) -> FlightSource: - return FlightSource(_catalog(gateway.port), token_provider=lambda: token) + return FlightSource( + _catalog(gateway.port), + location=f"grpc://127.0.0.1:{gateway.port}", # not "localhost": no IPv6 detour + token_provider=lambda: token, + ) # -- the source ----------------------------------------------------------------------------------- From 26099d3f4e6a5d02a633551db732892a55c809ae Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 15:22:22 +0100 Subject: [PATCH 17/25] %ingest as a signed-in user: stage inside the namespace; bucket check Found running the smoke notebook as eea-admin (device login): the Access service gives a user RustFS keys only for catalog//... of the namespaces they have grants on. - Iceberg ingest with the user's own keys (STS) stages the files inside the target namespace's folder, /_ingestion/-/ /, the one place those keys may write; with the shared key it keeps using the stack's staging area. Removed after loading as before. - ObjectStore.bucket_exists: keys limited to some prefixes may not ask about the bucket itself (HeadBucket -> ACCESS_DENIED); refused now means "there", only a missing bucket fails diagnose. - Flight source tests: an in-process Flight server occasionally starts without ever serving; the fixture starts another instead of failing. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/object_store.py | 6 +++ .../dds_ingestion/polaris_ingest.py | 20 +++++--- tests/dds_ingestion/test_polaris_ingest.py | 31 ++++++++++++ tests/geopackage/test_flight_source.py | 47 ++++++++++--------- 4 files changed, 76 insertions(+), 28 deletions(-) diff --git a/src/eea_datalakehouse/catalog/object_store.py b/src/eea_datalakehouse/catalog/object_store.py index d3e7178..c62685a 100644 --- a/src/eea_datalakehouse/catalog/object_store.py +++ b/src/eea_datalakehouse/catalog/object_store.py @@ -182,6 +182,12 @@ def bucket_exists(self, url: str) -> bool: try: return bool(self._fs.get_file_info(bucket).type != pafs.FileType.NotFound) except OSError as exc: + # Keys limited to some prefixes (a user's own) may not ask about the bucket + # itself: refused means it is there, just not for this question. + if any( + word in str(exc) for word in ("ACCESS_DENIED", "AccessDenied", "Forbidden", "403") + ): + return True raise CatalogOperationError(f"could not check the bucket {bucket!r}: {exc}") from exc def list(self, prefix_url: str) -> list[StoredFile]: diff --git a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py index 2399b19..0805e94 100644 --- a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py +++ b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py @@ -318,11 +318,19 @@ def run(self) -> PolarisIngestOutcome: return self._run_iceberg(plan) return self._run_parquet(plan) - def _staging_url(self, namespace: Sequence[str], table: str) -> str: + def _staging_url(self, namespace: Sequence[str], table: str, creds: S3Credentials) -> str: + """Where the files wait before they are loaded. With the user's own keys + (STS), inside the target namespace's folder — the only place those keys may + write: ``/_ingestion/-/
/``. With the + shared key, the stack's staging area: ``s3://// + //
/``.""" settings = self._catalog.settings - bucket = settings.ingest_bucket or split_url(self.namespace_location(namespace))[0] user = to_eea_identifier(token_username(self._token_provider()) or "service") or "service" run = dt.datetime.now(dt.UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + secrets.token_hex(3) + if creds.source == "sts": + location = self.namespace_location(namespace) + return f"{location}/{settings.ingest_prefix}/{user}-{run}/{table}/" + bucket = settings.ingest_bucket or split_url(self.namespace_location(namespace))[0] return f"s3://{bucket}/{settings.ingest_prefix}/{user}/{run}/{table}/" def _run_iceberg(self, plan: _Plan) -> PolarisIngestOutcome: @@ -330,7 +338,7 @@ def _run_iceberg(self, plan: _Plan) -> PolarisIngestOutcome: target = catalog.path_of([*plan.namespace, plan.table]) creds = self._credentials() store = self._store(creds) - staging = self._staging_url(plan.namespace, plan.table) + staging = self._staging_url(plan.namespace, plan.table, creds) self._progress(f"uploading {len(plan.specs)} file(s) to {staging}") urls: list[str] = [] try: @@ -490,13 +498,13 @@ def report(passed: bool | None, name: str, detail: str) -> None: + (f"(exists as {plan.existing}; {self.conflict_mode})" if plan.existing else "(new)"), ) try: + creds = self._credentials() + store = self._store(creds) where = ( - self._staging_url(plan.namespace, plan.table) + self._staging_url(plan.namespace, plan.table, creds) if self.table_format == "iceberg" else f"{self.namespace_location(plan.namespace)}/{plan.table}/" ) - creds = self._credentials() - store = self._store(creds) if not store.bucket_exists(where): report( False, diff --git a/tests/dds_ingestion/test_polaris_ingest.py b/tests/dds_ingestion/test_polaris_ingest.py index 6996cd6..cbbfad2 100644 --- a/tests/dds_ingestion/test_polaris_ingest.py +++ b/tests/dds_ingestion/test_polaris_ingest.py @@ -524,3 +524,34 @@ def test_a_new_parquet_table_refuses_stray_files_at_its_location( _ingest(catalog, _folder(tmp_path), bucket, conflict_mode="replace", **args).run() assert _files(bucket) == ["lake/catalog/water/bwd/temps/2026/a.parquet"] + + +def test_with_the_users_own_keys_staging_is_inside_the_namespace( + tmp_path: Path, bucket: Path +) -> None: + """Found against the live stack: a user's RustFS keys may write only below the + namespaces they have grants on, not the shared staging prefix.""" + catalog, _, engine = _setup() + + def own_keys(job: PolarisIngest) -> S3Credentials: + return S3Credentials("uak", "usk", "ust", source="sts") + + job = _ingest(catalog, _folder(tmp_path), bucket) + job._credentials = lambda: own_keys(job) # type: ignore[method-assign] # noqa: SLF001 + job.run() + + secret = next(s for s in engine.sql if "SECRET" in s) + assert re.search( + r"SCOPE 's3://lake/catalog/water/bwd/_ingestion/service-\d{8}T\d{6}Z-\w+/a/'\)$", secret + ) + assert "SESSION_TOKEN 'ust'" in secret + assert _files(bucket) == [] # staged files removed + + +def test_a_bucket_the_keys_may_not_inspect_counts_as_there() -> None: + class Refusing: + def get_file_info(self, path: str) -> Any: + raise OSError("AWS Error ACCESS_DENIED during HeadBucket operation") + + store = ObjectStore(SETTINGS, S3Credentials("a", "b"), filesystem=Refusing()) + assert store.bucket_exists("s3://lakehouse/x/") is True diff --git a/tests/geopackage/test_flight_source.py b/tests/geopackage/test_flight_source.py index bfa7082..9fc8681 100644 --- a/tests/geopackage/test_flight_source.py +++ b/tests/geopackage/test_flight_source.py @@ -56,23 +56,21 @@ def do_get(self, context: Any, ticket: flight.Ticket) -> flight.RecordBatchStrea return flight.RecordBatchStream(self.tables[sql]) -def _wait_until_serving(port: int, seconds: float = 10.0) -> None: - """Block until the test server answers (a refused sign-in counts): the thread - may not be serving yet when the first test call is made.""" +def _serving(port: int, seconds: float) -> bool: + """Whether the test server answers within `seconds` (a refused sign-in counts).""" deadline = time.monotonic() + seconds - while True: + while time.monotonic() < deadline: client = flight.FlightClient(f"grpc://127.0.0.1:{port}") try: list(client.list_actions()) - return + return True except flight.FlightUnauthenticatedError: - return + return True except flight.FlightUnavailableError: - if time.monotonic() > deadline: - raise time.sleep(0.05) finally: client.close() + return False @pytest.fixture @@ -88,20 +86,25 @@ def gateway() -> Iterator[Gateway]: "srid": [4326, 4326], } ) - server = Gateway( - { - 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations"': stations, - 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations" LIMIT 1': stations.slice(0, 1), - 'SELECT * FROM (SELECT 1 AS "n") LIMIT 1': pa.table({"n": [1]}), - 'SELECT * FROM (SELECT 1 AS "n")': pa.table({"n": [1]}), - 'SELECT * FROM "eea_lakehouse"."water.bwd"."empty"': pa.table( - {"id": pa.array([], pa.int64())} - ), - } - ) - thread = threading.Thread(target=server.serve, daemon=True) - thread.start() - _wait_until_serving(server.port) + tables = { + 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations"': stations, + 'SELECT * FROM "eea_lakehouse"."water.bwd"."stations" LIMIT 1': stations.slice(0, 1), + 'SELECT * FROM (SELECT 1 AS "n") LIMIT 1': pa.table({"n": [1]}), + 'SELECT * FROM (SELECT 1 AS "n")': pa.table({"n": [1]}), + 'SELECT * FROM "eea_lakehouse"."water.bwd"."empty"': pa.table( + {"id": pa.array([], pa.int64())} + ), + } + # Now and then an in-process Flight server starts without ever serving (seen as + # "connection refused" for its whole life): start another one rather than fail. + for _ in range(3): + server = Gateway(tables) + threading.Thread(target=server.serve, daemon=True).start() + if _serving(server.port, seconds=3.0): + break + server.shutdown() + else: + pytest.fail("the test Flight server never answered") yield server server.shutdown() From ec78eceeda3bd749fbe064ceb070e592469698a9 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 15:30:34 +0100 Subject: [PATCH 18/25] DuckDB: apply the stack's CA globally, so %gpkg's cursors get it %gpkg streams each table on a DuckDB cursor of its own. The CA of the stack's HTTPS gateway was set with a plain SET, which holds for the session that ran it only, so the cursors' Iceberg REST calls to Polaris failed certificate verification ("SSL peer certificate ... was not OK"). SET GLOBAL ca_cert_file / enable_server_cert_verification now - global to the engine's own database only. Checked against the 172.28.1.6 gateway: on a cursor, without the CA the request fails TLS; with it, it reaches Polaris (401 without a token). Co-Authored-By: Claude Opus 5.5 --- .../catalog/duckdb_engine.py | 6 +++-- tests/catalog/test_duckdb_engine.py | 25 +++++++++++++++++-- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py index 1bf6a14..da691a1 100644 --- a/src/eea_datalakehouse/catalog/duckdb_engine.py +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -166,8 +166,10 @@ def setup_statements(self) -> list[str]: statements: list[str] = [] if settings.ca_file: # The stack's own CA (an HTTPS gateway in front of Polaris): trust it, and check. - statements.append(f"SET ca_cert_file = {quote_literal(settings.ca_file)}") - statements.append("SET enable_server_cert_verification = true") + # GLOBAL: a plain SET holds for this session only, and the cursors streams run + # on (%gpkg) would go without it. Global to this engine's own database only. + statements.append(f"SET GLOBAL ca_cert_file = {quote_literal(settings.ca_file)}") + statements.append("SET GLOBAL enable_server_cert_verification = true") if not settings.vended_credentials: scheme, _, host = settings.s3_endpoint.partition("://") key = ( diff --git a/tests/catalog/test_duckdb_engine.py b/tests/catalog/test_duckdb_engine.py index 16c0dd7..cc2da6c 100644 --- a/tests/catalog/test_duckdb_engine.py +++ b/tests/catalog/test_duckdb_engine.py @@ -191,7 +191,28 @@ def test_the_stacks_own_ca_is_trusted_and_checked() -> None: engine, _ = _engine(PolarisSettings(uri="https://gateway/api/catalog", ca_file="/ca.crt")) statements = engine.setup_statements() assert statements[:2] == [ - "SET ca_cert_file = '/ca.crt'", - "SET enable_server_cert_verification = true", + "SET GLOBAL ca_cert_file = '/ca.crt'", + "SET GLOBAL enable_server_cert_verification = true", ] assert not any("ca_cert_file" in s for s in _engine()[0].setup_statements()) + + +def test_the_ca_reaches_the_cursors_streams_run_on() -> None: + """Found against the live stack: %gpkg streams on cursors, and a session-only + SET left them without the CA (certificate verification failed).""" + connection = duckdb.connect() + connection.execute("LOAD httpfs") + engine = DuckDbEngine( + PolarisSettings(uri="https://gateway/api/catalog", ca_file="/ca.crt"), + token_provider=lambda: "t", + ) + for statement in engine.setup_statements()[:2]: + connection.execute(statement) + cursor = connection.cursor() + settings = dict( + cursor.execute( + "SELECT name, value FROM duckdb_settings() " + "WHERE name IN ('ca_cert_file', 'enable_server_cert_verification')" + ).fetchall() + ) + assert settings == {"ca_cert_file": "/ca.crt", "enable_server_cert_verification": "true"} From a1fa408fd9ab85e3f2305335cf764b5143ed8b1d Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 15:35:05 +0100 Subject: [PATCH 19/25] Smoke notebook: upload the exported GeoPackage to DDS The %gpkg export cell keeps its report (gpkg); a new step pushes it to the context's deliverables folder with %dds push(DELIVERABLES, gpkg, overwrite=True) - the report is the file - and lists the folder. Co-Authored-By: Claude Opus 5.5 --- debugger/test_catalog_magic.ipynb | 42 +++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index 551a1c8..a2a4a2e 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -611,9 +611,41 @@ "metadata": {}, "outputs": [], "source": [ - "%gpkg export(limit=100, filename=\"catalog_magic_smoke.gpkg\", output_dir=str(INGEST_DIR))" + "gpkg = %gpkg export(limit=100, filename=\"catalog_magic_smoke.gpkg\", output_dir=str(INGEST_DIR))\n", + "gpkg" ], - "id": "3091f085" + "id": "63146098" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Upload the GeoPackage to DDS\n", + "\n", + "The export's report is the file: `%dds push` takes it as it is and stores it under the\n", + "context's `deliverables` folder, replacing an earlier upload of the same name." + ], + "id": "a64d12fb" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%dds push(DELIVERABLES, gpkg, overwrite=True)" + ], + "id": "7c9af9f6" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%dds list(DELIVERABLES)" + ], + "id": "14fc8734" }, { "cell_type": "markdown", @@ -626,7 +658,7 @@ "only; the cell after it removes whatever data files are left in the scratch folder's own\n", "storage location — nothing else." ], - "id": "028069c5" + "id": "b6d9f8dd" }, { "cell_type": "code", @@ -639,7 +671,7 @@ "%catalog delete_folder(TEST_FOLDER, cascade=True)\n", "print(\"folder exists after cleanup:\", verify.exists(TEST_FOLDER))" ], - "id": "9da6681c" + "id": "5484c544" }, { "cell_type": "code", @@ -656,7 +688,7 @@ " print(f\"removed {len(left)} leftover file(s) under {SCRATCH_LOCATION}\")\n", "verify.close()" ], - "id": "e255abde" + "id": "69cde9e9" } ], "metadata": { From 357835dd1c02d4ab090c73387d3fb96c5b7ae2e1 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 15:51:58 +0100 Subject: [PATCH 20/25] Take settings and secrets from the JupyterLab pod's environment In the stack's JupyterLab every setting and secret comes from the pod's environment (POLARIS_URI, POLARIS_CATALOG, POLARIS_VENDED_CREDENTIALS, S3_ENDPOINT, DDS_BASE_URL, TRINO_CA_FILE, KEYCLOAK_ACCESS_TOKEN from the token bridge). Checked by running the library with exactly the pod template's variables: - %dds on Polaris: the kernel environment's DDS_BASE_URL wins over a .env lying in a folder (which only fills in a missing one); Dremio keeps its .env-first rule. - DuckDB gets the stack's CA only when Polaris itself is reached over HTTPS: the pod sets TRINO_CA_FILE for Trino while Polaris is plain HTTP, and the CA would replace DuckDB's own bundle (public HTTPS data too). - A CA file that is set but not there (TRINO_CA_FILE where /etc/lakehouse-ca isn't mounted) is ignored instead of failing every connection. - The smoke notebook runs without debugger/.env: in JupyterLab it uses the kernel environment only; outside, .env never overrides it. - README: where the settings come from in JupyterLab. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 +++++-- debugger/test_catalog_magic.ipynb | 27 +++++++++-------- .../catalog/duckdb_engine.py | 4 ++- src/eea_datalakehouse/catalog/settings.py | 7 +++-- .../dds_documents/session.py | 16 ++++++---- tests/catalog/test_duckdb_engine.py | 7 +++++ tests/catalog/test_settings.py | 30 +++++++++++-------- tests/dds_documents/test_session.py | 15 ++++++++++ 8 files changed, 81 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 9581d16..5947047 100644 --- a/README.md +++ b/README.md @@ -460,9 +460,13 @@ Iceberg REST catalog of the EEA Lakehouse stack (`eeadata/EEALakeHouse`, `POLARIS_URI` is set, else `dremio`, so a Dremio kernel keeps working unchanged). The commands, their arguments and `%%catalog` stay the same. -**Settings.** The names the JupyterLab kernel receives; in brackets the -`local-stack/.env` name read when the first is not set (see -`debugger/.env.example` for all of them): +**Settings.** In the stack's JupyterLab every setting and secret comes from the +pod's environment — `POLARIS_URI`, `POLARIS_CATALOG`, `POLARIS_VENDED_CREDENTIALS`, +`S3_ENDPOINT`, `DDS_BASE_URL`, `TRINO_CA_FILE`, and your Keycloak token in +`KEYCLOAK_ACCESS_TOKEN` — so nothing needs configuring there, and a `.env` file never +overrides them. Outside it (a laptop, `debugger/`), set them yourself. The names the +JupyterLab kernel receives; in brackets the `local-stack/.env` name read when the first +is not set (see `debugger/.env.example` for all of them): | Variable | Default | What | |---|---|---| diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index a2a4a2e..3454e32 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -15,7 +15,10 @@ "Everything is written under one scratch folder (`TEST_FOLDER`, below) and removed in\n", "**Cleanup**; the only existing table touched is `SOURCE_TABLE`, and only read.\n", "\n", - "**Before running**\n", + "**In the stack's JupyterLab** nothing needs setting up: the pod's environment has every\n", + "setting and your Keycloak token, and `debugger/.env` is not needed.\n", + "\n", + "**Outside JupyterLab (debugging from a laptop)**\n", "\n", "1. Port-forward RustFS (the catalog's object store) — the command is at the top of\n", " `debugger/.env`.\n", @@ -23,7 +26,8 @@ " and a code; open it in a browser and sign in as **eea-admin**. The notebook then runs as\n", " that user (Polaris, DuckDB, DDS, RustFS), and the token is renewed by itself. Needs\n", " `KEYCLOAK_URL` in `debugger/.env` and the realm's `eea-notebook` client.\n", - "3. Restart the kernel after changing `debugger/.env`: it is read once, in the next cell." + "3. Restart the kernel after changing `debugger/.env`: it is read once, in the next cell, and\n", + " never overrides what the kernel environment already has." ], "id": "64fef81a" }, @@ -37,22 +41,21 @@ "from pathlib import Path\n", "\n", "\n", - "def _find_debugger_env(start: Path | None = None) -> Path:\n", - " \"\"\"`debugger/.env` — located by walking up from this notebook rather than\n", - " hardcoded, so it works wherever Jupyter's cwd happens to be. Identified by\n", - " sitting next to `debug_run.py`, not just any `.env`.\"\"\"\n", + "def _find_debugger_env(start: Path | None = None) -> Path | None:\n", + " \"\"\"`debugger/.env`, found by walking up from this notebook (it sits next to\n", + " `debug_run.py`); None when there is none — in the stack's JupyterLab the pod's\n", + " environment already has every setting and secret.\"\"\"\n", " here = start or Path.cwd()\n", " for candidate in (here, *here.parents):\n", " if (candidate / \"debug_run.py\").exists() and (candidate / \".env\").exists():\n", " return candidate / \".env\"\n", - " raise RuntimeError(\n", - " f\"could not find debugger/.env from {here} — copy debugger/.env.example to \"\n", - " \"debugger/.env, fill it in, and open this notebook from inside the repository\"\n", - " )\n", + " return None\n", "\n", "\n", + "# Outside JupyterLab, debugger/.env supplies the settings; it never overrides what the\n", + "# kernel environment already has (in JupyterLab: the pod's variables and secrets).\n", "ENV_PATH = _find_debugger_env()\n", - "for _line in ENV_PATH.read_text().splitlines():\n", + "for _line in ENV_PATH.read_text().splitlines() if ENV_PATH else []:\n", " _line = _line.strip()\n", " if not _line or _line.startswith(\"#\") or \"=\" not in _line:\n", " continue\n", @@ -67,7 +70,7 @@ " keycloak.login() # prints a link and a code — sign in there as eea-admin\n", "\n", "SETTINGS = PolarisSettings.from_env()\n", - "print(f\"env file {ENV_PATH}\")\n", + "print(f\"settings from {ENV_PATH or 'the kernel environment only (JupyterLab)'}\")\n", "print(f\"backend {backend_name()}\")\n", "print(f\"POLARIS_URI {SETTINGS.uri}\")\n", "print(f\"catalog (root) {SETTINGS.catalog}\")\n", diff --git a/src/eea_datalakehouse/catalog/duckdb_engine.py b/src/eea_datalakehouse/catalog/duckdb_engine.py index da691a1..f3749b0 100644 --- a/src/eea_datalakehouse/catalog/duckdb_engine.py +++ b/src/eea_datalakehouse/catalog/duckdb_engine.py @@ -164,8 +164,10 @@ def setup_statements(self) -> list[str]: """The secrets and the ATTACH that `connection` runs, in order.""" settings = self._settings statements: list[str] = [] - if settings.ca_file: + if settings.ca_file and settings.uri.startswith("https://"): # The stack's own CA (an HTTPS gateway in front of Polaris): trust it, and check. + # Only then: it replaces DuckDB's own CA bundle, and inside the stack's + # JupyterLab Polaris is plain HTTP while TRINO_CA_FILE is set for Trino. # GLOBAL: a plain SET holds for this session only, and the cursors streams run # on (%gpkg) would go without it. Global to this engine's own database only. statements.append(f"SET GLOBAL ca_cert_file = {quote_literal(settings.ca_file)}") diff --git a/src/eea_datalakehouse/catalog/settings.py b/src/eea_datalakehouse/catalog/settings.py index 3e612bf..667521f 100644 --- a/src/eea_datalakehouse/catalog/settings.py +++ b/src/eea_datalakehouse/catalog/settings.py @@ -68,10 +68,13 @@ def polaris_catalog_name(environ: Mapping[str, str] | None = None) -> str: def lakehouse_ca_file(environ: Mapping[str, str] | None = None) -> str | None: """The CA certificate that signs the lakehouse's HTTPS endpoints (its gateway, Trino), when they use their own: ``LAKEHOUSE_CA_FILE``, else ``TRINO_CA_FILE`` (where the - stack mounts it in JupyterLab: ``/etc/lakehouse-ca/ca.crt``). None: the system's.""" + stack mounts it in JupyterLab: ``/etc/lakehouse-ca/ca.crt``) — when that file is + there. None: the system's CAs (a path that is set but missing is not an error: the + same environment runs where the file isn't mounted).""" env = os.environ if environ is None else environ path = _get(env, "LAKEHOUSE_CA_FILE", "TRINO_CA_FILE") - return os.path.expanduser(path) if path else None + path = os.path.expanduser(path) if path else "" + return path if path and os.path.isfile(path) else None def tls_verify(ca_file: str | None) -> str | bool: diff --git a/src/eea_datalakehouse/dds_documents/session.py b/src/eea_datalakehouse/dds_documents/session.py index eeb4903..6feb66d 100644 --- a/src/eea_datalakehouse/dds_documents/session.py +++ b/src/eea_datalakehouse/dds_documents/session.py @@ -22,10 +22,12 @@ ``_DREMIO_USER`` / ``_DREMIO_PWD`` (what `%ingest` reads), falling back to ``DREMIO_USERNAME`` / ``DREMIO_TOKEN`` (what `%catalog` reads). -**`DDS_BASE_URL` comes from a `.env` file first.** When a `DdsSession` is -built, it looks for `.env` in the notebook's working directory, then in each +**`DDS_BASE_URL` comes from a `.env` file first** (on Dremio). When a `DdsSession` +is built, it looks for `.env` in the notebook's working directory, then in each parent directory, and takes it from the first one found. Only when that `.env` -doesn't set it does the kernel environment's value apply. Nothing else is read +doesn't set it does the kernel environment's value apply. On Polaris it is the +other way round — the kernel environment (in the stack's JupyterLab, the pod's +own setting) first, a `.env` only when it isn't set. Nothing else is read from the file, and it never changes ``os.environ``. `dds_base_url()` shows which URL is in use and where it came from. """ @@ -342,10 +344,14 @@ def _dds(self) -> DdsController: return self._controller def _resolve_url(self) -> tuple[str, str]: - """``(url, source)``: ``DDS_BASE_URL`` from the ``.env`` file, else the kernel env.""" + """``(url, source)``: ``DDS_BASE_URL`` from the ``.env`` file, else the kernel env. + On Polaris the other way round: in the stack's JupyterLab the pod's own setting + is the one to use, and a ``.env`` lying in a folder only fills in a missing one.""" + env = os.environ if self._env is None else self._env + if self._on_polaris() and env.get(ENV_BASE_URL): + return env[ENV_BASE_URL].rstrip("/"), "the kernel environment" if self._dotenv_url and self._dotenv_path is not None: return self._dotenv_url.rstrip("/"), str(self._dotenv_path) - env = os.environ if self._env is None else self._env if env.get(ENV_BASE_URL): return env[ENV_BASE_URL].rstrip("/"), "the kernel environment" where = f"{self._dotenv_path} has none and " if self._dotenv_path else "no .env found and " diff --git a/tests/catalog/test_duckdb_engine.py b/tests/catalog/test_duckdb_engine.py index cc2da6c..daec112 100644 --- a/tests/catalog/test_duckdb_engine.py +++ b/tests/catalog/test_duckdb_engine.py @@ -216,3 +216,10 @@ def test_the_ca_reaches_the_cursors_streams_run_on() -> None: ).fetchall() ) assert settings == {"ca_cert_file": "/ca.crt", "enable_server_cert_verification": "true"} + + +def test_the_ca_is_left_alone_when_polaris_is_plain_http() -> None: + """In the stack's JupyterLab: Polaris is http://polaris:8181 and TRINO_CA_FILE is set + for Trino — DuckDB keeps its own CA bundle (it reads public HTTPS data too).""" + engine, _ = _engine(PolarisSettings(uri="http://polaris:8181/api/catalog", ca_file="/ca.crt")) + assert not any("ca_cert_file" in s for s in engine.setup_statements()) diff --git a/tests/catalog/test_settings.py b/tests/catalog/test_settings.py index c103894..47fde78 100644 --- a/tests/catalog/test_settings.py +++ b/tests/catalog/test_settings.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import Any + import pytest from eea_datalakehouse.catalog.settings import ( @@ -145,19 +147,23 @@ def test_user_token() -> None: assert user_token({"KEYCLOAK_ACCESS_TOKEN": " jwt "}) == "jwt" -def test_lakehouse_ca_file() -> None: +def test_lakehouse_ca_file(tmp_path: Any) -> None: from eea_datalakehouse.catalog.settings import lakehouse_ca_file, tls_verify + a, b = tmp_path / "a.crt", tmp_path / "b.crt" + a.write_text("ca"), b.write_text("ca") assert lakehouse_ca_file({}) is None - assert lakehouse_ca_file({"TRINO_CA_FILE": "/etc/lakehouse-ca/ca.crt"}) == ( - "/etc/lakehouse-ca/ca.crt" - ) - assert lakehouse_ca_file({"LAKEHOUSE_CA_FILE": "/a.crt", "TRINO_CA_FILE": "/b.crt"}) == "/a.crt" - assert ( - PolarisSettings.from_env( - {"POLARIS_URI": "https://g", "LAKEHOUSE_CA_FILE": "/a.crt"} - ).ca_file - == "/a.crt" - ) + assert lakehouse_ca_file({"TRINO_CA_FILE": str(b)}) == str(b) + assert lakehouse_ca_file({"LAKEHOUSE_CA_FILE": str(a), "TRINO_CA_FILE": str(b)}) == str(a) + settings = PolarisSettings.from_env({"POLARIS_URI": "https://g", "LAKEHOUSE_CA_FILE": str(a)}) + assert settings.ca_file == str(a) assert tls_verify(None) is True - assert tls_verify("/a.crt") == "/a.crt" + assert tls_verify(str(a)) == str(a) + + +def test_a_ca_file_that_is_not_there_is_ignored() -> None: + """The JupyterLab pod sets TRINO_CA_FILE=/etc/lakehouse-ca/ca.crt; where that file + isn't mounted, the system's CAs apply rather than every connection failing.""" + from eea_datalakehouse.catalog.settings import lakehouse_ca_file + + assert lakehouse_ca_file({"TRINO_CA_FILE": "/nonexistent/ca.crt"}) is None diff --git a/tests/dds_documents/test_session.py b/tests/dds_documents/test_session.py index 711f7c9..1645301 100644 --- a/tests/dds_documents/test_session.py +++ b/tests/dds_documents/test_session.py @@ -529,3 +529,18 @@ def test_polaris_without_a_keycloak_token() -> None: def test_documents_client_takes_one_identity() -> None: with pytest.raises(ValueError, match="either creds or keycloak_token"): DocumentsClient(DDS_URL) + + +def test_on_polaris_the_kernel_environment_wins_over_a_dotenv(tmp_path: Path) -> None: + """In the stack's JupyterLab the pod's DDS_BASE_URL is the one to use; a .env lying + in a folder only fills in a missing one.""" + dotenv = tmp_path / ".env" + dotenv.write_text("DDS_BASE_URL=https://from-dotenv.test\n") + pod = {**POLARIS_ENV, "DDS_BASE_URL": "http://dds-server:8000"} + assert _session(POLARIS_DATASET, env=pod, dotenv_path=dotenv).dds_base_url() == ( + "http://dds-server:8000 (from the kernel environment)" + ) + without = {k: v for k, v in POLARIS_ENV.items() if k != "DDS_BASE_URL"} + assert _session(POLARIS_DATASET, env=without, dotenv_path=dotenv).dds_base_url() == ( + f"https://from-dotenv.test (from {dotenv})" + ) From c5dfa67094a0a8185248170aef3a4027ee00b658 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 16:05:55 +0100 Subject: [PATCH 21/25] Test: install DuckDB's httpfs before using its CA settings test_the_ca_reaches_the_cursors_streams_run_on loaded httpfs without installing it, which only works where the extension is already cached; on a fresh CI runner it failed ("Extension httpfs ... not found"). ca_cert_file / enable_server_cert_verification are httpfs settings, so the test now installs it as the engine does, and skips with the reason where it can't be downloaded. Co-Authored-By: Claude Opus 5.5 --- tests/catalog/test_duckdb_engine.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/catalog/test_duckdb_engine.py b/tests/catalog/test_duckdb_engine.py index daec112..1d25f77 100644 --- a/tests/catalog/test_duckdb_engine.py +++ b/tests/catalog/test_duckdb_engine.py @@ -201,7 +201,11 @@ def test_the_ca_reaches_the_cursors_streams_run_on() -> None: """Found against the live stack: %gpkg streams on cursors, and a session-only SET left them without the CA (certificate verification failed).""" connection = duckdb.connect() - connection.execute("LOAD httpfs") + try: # the CA settings belong to httpfs, which the engine installs first too + connection.execute("INSTALL httpfs") + connection.execute("LOAD httpfs") + except duckdb.Error as exc: + pytest.skip(f"DuckDB's httpfs extension can't be installed here: {exc}") engine = DuckDbEngine( PolarisSettings(uri="https://gateway/api/catalog", ca_file="/ca.crt"), token_provider=lambda: "t", From 66c58f15f72e6b09e9b377f742b622436d94b91a Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 16:07:36 +0100 Subject: [PATCH 22/25] Ignore debugger/lakehouse-ca.crt The CA of the local stack's HTTPS gateway, copied from the cluster for the debugger notebooks (LAKEHOUSE_CA_FILE): specific to one deployment, not part of the repository. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 3dff1c2..463c1e7 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ debugger/bathing_water/ # Windows download metadata (WSL copies it next to downloaded files) *:Zone.Identifier debugger/output.gpkg +debugger/lakehouse-ca.crt From 731dc56058b35266773794fada61262dcb4455a3 Mon Sep 17 00:00:00 2001 From: oesparza Date: Mon, 30 Nov 2026 16:10:50 +0100 Subject: [PATCH 23/25] %ingest: remove the whole staging folder once the table is loaded After an Iceberg ingest the staged files were deleted, but their folders stayed under _ingestion/: deleting the last file of a "folder" makes pyarrow's S3 layer write an empty marker object for it, so file-by-file deletes leave the folder skeleton behind (seen on the live RustFS). - ObjectStore.remove_folder(folder, up_to=...): deletes the folder with everything in it, markers included, then each parent left empty, up to and including `up_to`; a parent that still holds something (another run's staging) stops it. - PolarisIngest removes its run's staging folder and the empty folders above it up to _ingestion/ after a successful load, and on failure with cleanup_on_failure=True. Checked on the live RustFS: deleting only the file left three empty folders; remove_folder leaves nothing. Co-Authored-By: Claude Opus 5.5 --- src/eea_datalakehouse/catalog/object_store.py | 27 ++++++++++ .../dds_ingestion/polaris_ingest.py | 13 ++++- tests/dds_ingestion/test_polaris_ingest.py | 51 +++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/eea_datalakehouse/catalog/object_store.py b/src/eea_datalakehouse/catalog/object_store.py index c62685a..aae284f 100644 --- a/src/eea_datalakehouse/catalog/object_store.py +++ b/src/eea_datalakehouse/catalog/object_store.py @@ -209,6 +209,33 @@ def list(self, prefix_url: str) -> list[StoredFile]: key=lambda f: f.url, ) + def remove_folder(self, folder_url: str, *, up_to: str | None = None) -> None: + """Delete the folder `folder_url` with everything in it, then each parent that + is left empty, up to and including `up_to` (a parent of it). + + Deleting files one by one is not enough on S3: pyarrow keeps a "folder" in + existence by writing an empty marker object for it when its last file goes, + so a staging area would leave its folders behind.""" + current = folder_url.rstrip("/") + stop = up_to.rstrip("/") if up_to else current + if current != stop and not current.startswith(f"{stop}/"): + raise ValueError(f"{up_to!r} is not a parent of {folder_url!r}") + while True: + bucket, key = split_url(current) + if not key: + return # never the bucket itself + if current != folder_url.rstrip("/") and self.list(f"{current}/"): + return # something else is still there (another run's staging) + try: + self._fs.delete_dir(f"{bucket}/{key}") + except FileNotFoundError: + pass + except OSError as exc: + raise CatalogOperationError(f"could not delete {current}/: {exc}") from exc + if current == stop: + return + current = current.rsplit("/", 1)[0] + def delete(self, urls: Sequence[str]) -> None: for url in urls: bucket, key = split_url(url) diff --git a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py index 0805e94..756e1a4 100644 --- a/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py +++ b/src/eea_datalakehouse/dds_ingestion/polaris_ingest.py @@ -333,6 +333,15 @@ def _staging_url(self, namespace: Sequence[str], table: str, creds: S3Credential bucket = settings.ingest_bucket or split_url(self.namespace_location(namespace))[0] return f"s3://{bucket}/{settings.ingest_prefix}/{user}/{run}/{table}/" + def _remove_staging(self, store: ObjectStore, staging: str) -> None: + """Remove this run's staging folder — files and folder markers — and the folders + above it that are left empty, up to the staging area's root ``_ingestion/`` + (kept while another run still stages there).""" + prefix = f"/{self._catalog.settings.ingest_prefix}/" + root = staging[: staging.index(prefix) + len(prefix)] if prefix in staging else staging + run_folder = staging.rstrip("/").rsplit("/", 1)[0] # <…>/_ingestion/ (or /) + store.remove_folder(run_folder, up_to=root) + def _run_iceberg(self, plan: _Plan) -> PolarisIngestOutcome: catalog, engine = self._catalog, self._catalog.engine target = catalog.path_of([*plan.namespace, plan.table]) @@ -372,14 +381,14 @@ def _run_iceberg(self, plan: _Plan) -> PolarisIngestOutcome: except Exception as exc: if self.cleanup_on_failure: try: - store.delete(urls) + self._remove_staging(store, staging) except CatalogOperationError as cleanup_error: exc.add_note(f"the staged files could not be removed: {cleanup_error}") elif urls: exc.add_note(f"the uploaded files are kept at {staging} (cleanup_on_failure=False)") raise try: - store.delete(urls) + self._remove_staging(store, staging) except CatalogOperationError as exc: self._notes.append(f"the staged files at {staging} could not be removed: {exc}") return PolarisIngestOutcome( diff --git a/tests/dds_ingestion/test_polaris_ingest.py b/tests/dds_ingestion/test_polaris_ingest.py index cbbfad2..604c420 100644 --- a/tests/dds_ingestion/test_polaris_ingest.py +++ b/tests/dds_ingestion/test_polaris_ingest.py @@ -555,3 +555,54 @@ def get_file_info(self, path: str) -> Any: store = ObjectStore(SETTINGS, S3Credentials("a", "b"), filesystem=Refusing()) assert store.bucket_exists("s3://lakehouse/x/") is True + + +def _entries(root: Path) -> list[str]: + """Every file and folder under `root` (an empty folder is what S3 keeps as a marker).""" + return sorted(p.relative_to(root).as_posix() for p in root.rglob("*")) + + +def _own_keys(job: PolarisIngest) -> PolarisIngest: + job._credentials = lambda: S3Credentials("uak", "usk", "ust", source="sts") # type: ignore[method-assign] # noqa: SLF001 + return job + + +def test_a_completed_ingest_leaves_nothing_under_ingestion(tmp_path: Path, bucket: Path) -> None: + """Found against the live stack: the staged files went, but their folders stayed — + pyarrow writes an empty marker for a folder whose last file is deleted.""" + catalog, _, _ = _setup() + + _own_keys(_ingest(catalog, _folder(tmp_path), bucket)).run() # staged inside the namespace + _ingest(catalog, _folder(tmp_path), bucket, table_name="b").run() # the shared staging area + + assert [e for e in _entries(bucket) if "_ingestion" in e] == [] + assert (bucket / "lake/catalog/water/bwd").is_dir() # the namespace's own folder stays + + +def test_another_runs_staging_is_left_alone(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup() + other = bucket / "lake/catalog/water/bwd/_ingestion/someone-20261130T000000Z-abcdef/t/x.parquet" + other.parent.mkdir(parents=True) + other.write_bytes(b"in progress") + + _own_keys(_ingest(catalog, _folder(tmp_path), bucket)).run() + + assert [e for e in _entries(bucket) if "_ingestion" in e] == [ + "lake/catalog/water/bwd/_ingestion", + "lake/catalog/water/bwd/_ingestion/someone-20261130T000000Z-abcdef", + "lake/catalog/water/bwd/_ingestion/someone-20261130T000000Z-abcdef/t", + "lake/catalog/water/bwd/_ingestion/someone-20261130T000000Z-abcdef/t/x.parquet", + ] + + +def test_cleanup_on_failure_leaves_no_folders_either(tmp_path: Path, bucket: Path) -> None: + catalog, _, _ = _setup(fail_on="CREATE TABLE") + with pytest.raises(CatalogOperationError, match="boom"): + _ingest(catalog, _folder(tmp_path), bucket, cleanup_on_failure=True).run() + assert [e for e in _entries(bucket) if "_ingestion" in e] == [] + + +def test_remove_folder_refuses_a_stop_that_is_not_a_parent(bucket: Path) -> None: + store = _store(bucket)(S3Credentials("a", "b")) + with pytest.raises(ValueError, match="is not a parent"): + store.remove_folder("s3://lake/a/b", up_to="s3://lake/x") From c13f48664977989914e2e1ef5c4e0338dbf930bc Mon Sep 17 00:00:00 2001 From: oesparza Date: Tue, 1 Dec 2026 10:34:42 +0100 Subject: [PATCH 24/25] catalog test notebook --- debugger/test_catalog_magic.ipynb | 916 +++++++++++++++++++++++------- 1 file changed, 712 insertions(+), 204 deletions(-) diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index 3454e32..72b0b59 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -2,6 +2,7 @@ "cells": [ { "cell_type": "markdown", + "id": "64fef81a", "metadata": {}, "source": [ "# `%catalog` smoke test on Polaris — immediate execution, no commit\n", @@ -15,10 +16,7 @@ "Everything is written under one scratch folder (`TEST_FOLDER`, below) and removed in\n", "**Cleanup**; the only existing table touched is `SOURCE_TABLE`, and only read.\n", "\n", - "**In the stack's JupyterLab** nothing needs setting up: the pod's environment has every\n", - "setting and your Keycloak token, and `debugger/.env` is not needed.\n", - "\n", - "**Outside JupyterLab (debugging from a laptop)**\n", + "**Before running**\n", "\n", "1. Port-forward RustFS (the catalog's object store) — the command is at the top of\n", " `debugger/.env`.\n", @@ -26,36 +24,53 @@ " and a code; open it in a browser and sign in as **eea-admin**. The notebook then runs as\n", " that user (Polaris, DuckDB, DDS, RustFS), and the token is renewed by itself. Needs\n", " `KEYCLOAK_URL` in `debugger/.env` and the realm's `eea-notebook` client.\n", - "3. Restart the kernel after changing `debugger/.env`: it is read once, in the next cell, and\n", - " never overrides what the kernel environment already has." - ], - "id": "64fef81a" + "3. Restart the kernel after changing `debugger/.env`: it is read once, in the next cell." + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, + "id": "3f7af2e9", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Sign in to the EEA Lakehouse: open https://172.28.1.6:31443/auth/realms/eea_datalakehouse/device?user_code=EWYT-YSAG (code EWYT-YSAG)\n", + "signed in as eea-admin\n", + "env file /home/oesparza/datahub/EEALakeHouse.python/debugger/.env\n", + "backend polaris\n", + "POLARIS_URI https://172.28.1.6:31443/api/catalog\n", + "catalog (root) eea_lakehouse\n", + "CA file /home/oesparza/datahub/EEALakeHouse.python/debugger/lakehouse-ca.crt\n", + "signed in as eea-admin\n", + "object store http://172.28.1.6:9000\n", + "DDS https://172.28.1.6:31443/dds\n" + ] + } + ], "source": [ "import os\n", "from pathlib import Path\n", "\n", "\n", - "def _find_debugger_env(start: Path | None = None) -> Path | None:\n", - " \"\"\"`debugger/.env`, found by walking up from this notebook (it sits next to\n", - " `debug_run.py`); None when there is none — in the stack's JupyterLab the pod's\n", - " environment already has every setting and secret.\"\"\"\n", + "def _find_debugger_env(start: Path | None = None) -> Path:\n", + " \"\"\"`debugger/.env` — located by walking up from this notebook rather than\n", + " hardcoded, so it works wherever Jupyter's cwd happens to be. Identified by\n", + " sitting next to `debug_run.py`, not just any `.env`.\"\"\"\n", " here = start or Path.cwd()\n", " for candidate in (here, *here.parents):\n", " if (candidate / \"debug_run.py\").exists() and (candidate / \".env\").exists():\n", " return candidate / \".env\"\n", - " return None\n", + " raise RuntimeError(\n", + " f\"could not find debugger/.env from {here} — copy debugger/.env.example to \"\n", + " \"debugger/.env, fill it in, and open this notebook from inside the repository\"\n", + " )\n", "\n", "\n", - "# Outside JupyterLab, debugger/.env supplies the settings; it never overrides what the\n", - "# kernel environment already has (in JupyterLab: the pod's variables and secrets).\n", "ENV_PATH = _find_debugger_env()\n", - "for _line in ENV_PATH.read_text().splitlines() if ENV_PATH else []:\n", + "for _line in ENV_PATH.read_text().splitlines():\n", " _line = _line.strip()\n", " if not _line or _line.startswith(\"#\") or \"=\" not in _line:\n", " continue\n", @@ -70,7 +85,7 @@ " keycloak.login() # prints a link and a code — sign in there as eea-admin\n", "\n", "SETTINGS = PolarisSettings.from_env()\n", - "print(f\"settings from {ENV_PATH or 'the kernel environment only (JupyterLab)'}\")\n", + "print(f\"env file {ENV_PATH}\")\n", "print(f\"backend {backend_name()}\")\n", "print(f\"POLARIS_URI {SETTINGS.uri}\")\n", "print(f\"catalog (root) {SETTINGS.catalog}\")\n", @@ -81,41 +96,69 @@ "assert backend_name() == \"polaris\", \"set EEA_CATALOG_BACKEND=polaris in debugger/.env\"\n", "if SETTINGS.uri.startswith(\"https://\") and not user_token():\n", " print(\"\\n!! nobody signed in: Polaris behind the gateway will refuse every call\")" - ], - "id": "3f7af2e9" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, + "id": "bdfc96fa", "metadata": {}, "outputs": [], "source": [ "import eea_datalakehouse.notebook # registers %catalog/%ingest/%dds/%gpkg/%sdi — no %load_ext needed" - ], - "id": "bdfc96fa" + ] }, { "cell_type": "markdown", + "id": "36010708", "metadata": {}, "source": [ "## Help\n", "\n", "`%catalog help` prints the command table without connecting to anything." - ], - "id": "36010708" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, + "id": "b94a800b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "%catalog methods — usage: %catalog data_copy(\"a.b\", \"c.d\") | %catalog set_tags(\"a.b\", [\"reviewed\"]) (each call runs immediately)\n", + "Backend: Dremio or Polaris, picked by EEA_CATALOG_BACKEND (unset: Polaris when POLARIS_URI is set). On Polaris paths start with the catalog's name (POLARIS_CATALOG, 'eea_lakehouse'), a folder is a namespace, and you are signed in with your Keycloak token (KEYCLOAK_ACCESS_TOKEN; else POLARIS_CLIENT_ID/POLARIS_CLIENT_SECRET).\n", + "A new session's context starts at 'catalog' (the root source), not empty — use(None)/use('') reset back to it too; only set_context(None) clears it to no context at all.\n", + "Every path/source_path/target_path (except use's own) is either absolute or relative to the current context, once one is set:\n", + " - starts with 'catalog.' (this deployment's one real root source; 'eea_lakehouse.' on Polaris) -> always absolute, used exactly as given, never appended to the context\n", + " - '.' or './' alone -> the context itself, exactly as get_context() shows it\n", + " - '../' (or a bare '..'), optionally chained ('../../') -> walks up that many levels of the context first, then appends whatever's left, if anything\n", + " - '.name', or a bare 'name' with no leading '.' at all -> both mean relative to the context; the dot is optional sugar, not what makes it relative\n", + "Only use() ever changes the context — no other call does, even one that fully resolved an absolute path.\n" + ] + }, + { + "data": { + "text/html": [ + "
CommandParametersDescription
usepathSet the current path for every call after this one; path must be a whole, absolute path — never relative to the current context, unlike every other verb's path/source_path/target_path. None or '' resets it to the root ('catalog' on Dremio, 'eea_lakehouse' on Polaris). Raises if path doesn't exist in the catalog. See %%catalog to set it once at the top of a cell.
get_contextShow the current path. A new session starts at the root ('catalog' on Dremio, 'eea_lakehouse' on Polaris); use(None)/use('') reset back to it too — None only after an explicit set_context(None).
data_copysource_path, target_path, overwrite=False, create_target_folder=FalseCopy source_path to target_path. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. A target_path ending in / is a folder, not the table: the folder is created first if it doesn't exist (every missing level), and the table lands inside it under the source's own name — data_copy("draft.t", "archive/2027/") makes archive.2027.t; "./" is the context itself; undo removes the folders it created. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
data_movesource_path, target_path, overwrite=False, create_target_folder=FalseMove source_path to target_path, always as a TABLE (use create_view for a view). overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. A target_path ending in / is a folder, not the table: the folder is created first if it doesn't exist (every missing level), and the table lands inside it under the source's own name — data_copy("draft.t", "archive/2027/") makes archive.2027.t; "./" is the context itself; undo removes the folders it created. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
create_versionsource_path, version_name, tables=None, target_path=None, overwrite=False, create_target_folder=TrueCopy the listed tables from source_path into a new folder target_path.version_name (as CREATE TABLE snapshots, keeping each table's sub-folders). source_path and version_name must not be blank. tables omitted or empty copies everything under source_path. Each entry is a table or a folder (= every table under it), named as listed under source_path or as list() shows them. target_path omitted means the current context — use() picks where versions go; a missing target_path is created unless create_target_folder=False. Reference/vocabulary tables (a folder named reference(s)/vocabulary(ies) in the path) and views are skipped; the report's notes say which. An existing version folder is an error unless overwrite=True (replaces the listed tables, keeps the rest).
draft_to_versionversion_name, tables=None, overwrite=Falsecreate_version from the dataflow's draft folder, with no paths to type: the source is the draft folder the context is in (or the draft folder inside the context), the target is draft's parent.versions.version_name (versions is created if missing). tables as in create_version: omitted or empty copies everything in draft. Unlike create_version, views in draft are not skipped: each is copied into the version as a table (a snapshot of what it returns); the report's notes say which.
update_latest_releaseversion_name, overwrite=TrueCreate a view at the Area's root for every table in versions.version_name, keeping its sub-folders (versions.v1.a.t gets the view a.t; missing folders are created). The context must be the Area folder — one with draft and versions folders just below it, typically catalog.<domain>.<subdomain>.<area> — and versions.version_name must exist — raises at once otherwise. Views in the version are skipped. An existing view is dropped and recreated over the version (overwrite=True, the default; not undoable) — overwrite=False makes it an error instead; an existing table is always an error. Each view is tagged #public, and #public is removed from every table/view under versions, so only the latest release is public.
publishpath=None, overwrite=True, partition_by=NoneCopy every #public view of a dataflow folder (as update_latest_release leaves them) into public_s3."dh-prod-data-public", as tables at the same full catalog path (catalog.x.y.dataflow.a.t is copied to public_s3."dh-prod-data-public".catalog.x.y.dataflow.a.t). The dataflow folder is path when given (absolute, or relative to the context), else the %catalog use(...) context; with neither it raises. It must have draft, versions and reference (or references) folders just below it — raises at once otherwise. Views and tables in those three folders are ignored; views without the tag are skipped and the report's notes say which. An existing table is replaced (overwrite=True, the default; not undoable) — overwrite=False makes it an error, and then nothing is copied. Each table is checked once copied, and the report's notes give its row count. All or nothing: if any table fails, everything the publish did is rolled back (replaced tables are restored) and an error says which table failed. partition_by (optional) partitions the tables by existing fields, in order: a list for every view (partition_by=["year", "country"]), or a dict for each view's own, keyed by its path below the Area (partition_by={"eu_sdg.monitoringsites": ["year"]}; views left out are not partitioned). A field a view doesn't have raises at once, when publish is called. On Polaris each #public view goes through the Document Service into the public store at <namespace path>/<view>/ (DDS_BASE_URL; you must be a publisher): not all or nothing — an error names the views already published — and partition_by / overwrite=False are not available.
listpath=''Show every table/view under path as a JSON array of {type, name} — type TABLE or VIEW, name the full dot-separated path: its own, then every child folder's, at any depth — walked folder by folder through the catalog's own API (Dremio's or Polaris'), no SQL. path may use '.' or '/' separators. path may be omitted to list the current context itself — raises CatalogSessionError if none is set. Raises CatalogOperationError if path doesn't exist.
schemapathShow path's column schema and row count (never fetches the actual rows). path must be a table or view — raises CatalogOperationError otherwise, or if path doesn't exist at all.
delete_tablepathDelete the table at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP TABLE, this doesn't quietly no-op on a typo).
create_viewsource_path, target_path, overwrite=False, create_target_folder=FalseCreate a VIEW at target_path over source_path, leaving source_path untouched. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
delete_viewpathDelete the view at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP VIEW, this doesn't quietly no-op on a typo).
set_wikipath, text, tags=NoneSet a path's wiki text. tags: a list of {tag_name, tag_value, tag_title} dicts, e.g. [{"tag_name": "owner", "tag_value": "bw-team", "tag_title": "Owner"}]. Ignored if path is a table/view (they have set_tags/get_tags for that instead).
delete_wikipathDelete a path's wiki text.
get_wikipathShow a path's wiki text. Raises CatalogOperationError if the path doesn't exist, or exists but has no wiki at all.
set_tagspath, tagsReplace a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise. On Polaris folders take tags too, and tags are kept lower case without '#' ('#public' and 'public' are the same tag).
delete_tagspath, tagsRemove tags from a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise.
get_tagspathShow the tags on a path — tables/views only. Raises CatalogOperationError if the path doesn't exist or isn't a table/view.
create_folderpath, create_parents=FalseCreate a folder. create_parents=True creates every missing level of the full path; create_parents=False (default) raises CatalogOperationError if the parent folder doesn't already exist.
delete_folderpath, cascade=FalseDelete a folder. Not undoable. cascade=True also deletes everything at path and below; cascade=False (default) raises CatalogOperationError if the folder isn't empty. A path that's already gone is not an error.
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], "source": [ "%catalog help" - ], - "id": "b94a800b" + ] }, { "cell_type": "markdown", + "id": "39af68b3", "metadata": {}, "source": [ "## Scratch space\n", @@ -123,14 +166,23 @@ "`TEST_FOLDER` is the one folder this notebook writes to; **Cleanup** deletes it with everything\n", "inside. `SOURCE_TABLE` is an existing table the data cells copy from — only read. `verify` is\n", "an independent client for the checks." - ], - "id": "39af68b3" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, + "id": "c4c97822", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "TEST_FOLDER eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test (exists already!)\n", + "SOURCE_TABLE eea_lakehouse.biodiversity_ecosystems.protected_areas.dfl_natura2000.draft.sites.aaaa exists: True\n" + ] + } + ], "source": [ "from eea_datalakehouse.catalog.polaris import PolarisCatalog\n", "\n", @@ -142,84 +194,140 @@ "verify = PolarisCatalog(SETTINGS) # an independent client: the magic never touches it\n", "print(\"TEST_FOLDER \", TEST_FOLDER, \"(exists already!)\" if verify.exists(TEST_FOLDER) else \"\")\n", "print(\"SOURCE_TABLE \", SOURCE_TABLE, \"exists:\", verify.exists(SOURCE_TABLE))" - ], - "id": "c4c97822" + ] }, { "cell_type": "markdown", + "id": "6d53a1cd", "metadata": {}, "source": [ "## 1. A call runs immediately\n", "\n", "`create_folder` is the only `%catalog` call in the cell — no `%catalog commit` after it. On\n", "Polaris a folder is a namespace." - ], - "id": "6d53a1cd" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, + "id": "45d8ff5e", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "CommitReport(succeeded=[\"create folder 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'\"], notes=[])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog create_folder(TEST_FOLDER, create_parents=True)" - ], - "id": "45d8ff5e" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, + "id": "d90b81ed", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "folder exists right now: True | is a namespace: True\n" + ] + } + ], "source": [ "print(\"folder exists right now:\", verify.exists(TEST_FOLDER), \"| is a namespace:\", verify.is_folder(TEST_FOLDER))" - ], - "id": "d90b81ed" + ] }, { "cell_type": "markdown", + "id": "d450519d", "metadata": {}, "source": [ "## 2. Context and relative paths\n", "\n", "`use` sets the context; a bare name (or `.name`) is then relative to it. Absolute paths start\n", "with the catalog's name (`eea_lakehouse.`) — on Dremio they started with `catalog.`." - ], - "id": "d450519d" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, + "id": "3721db27", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "context set to 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'\n" + ] + }, + { + "data": { + "text/plain": [ + "'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog use(TEST_FOLDER)\n", "%catalog get_context()" - ], - "id": "3721db27" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, + "id": "bedfc770", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "CommitReport(succeeded=[\"create folder 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.nested'\"], notes=[])" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog create_folder(\"nested\") # -> TEST_FOLDER + \".nested\"" - ], - "id": "bedfc770" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, + "id": "3bd26c7e", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "nested folder exists right now: True\n" + ] + } + ], "source": [ "print(\"nested folder exists right now:\", verify.exists(f\"{TEST_FOLDER}.nested\"))" - ], - "id": "3bd26c7e" + ] }, { "cell_type": "markdown", + "id": "40f2527a", "metadata": {}, "source": [ "## 3. Wiki and tags — also immediate\n", @@ -227,63 +335,109 @@ "On Polaris the wiki is the namespace's (or table's) `wiki` property, and tags are kept as the\n", "Polaris Navigator keeps them: lower case, without `#` (`#Smoke` and `smoke` are the same tag).\n", "Folders take tags too. `tags=` on a folder's wiki renders a \"# Meta Data\" block, as on Dremio." - ], - "id": "40f2527a" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, + "id": "29ac62a2", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "CommitReport(succeeded=[\"set wiki on 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'\"], notes=[])" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog set_wiki(\".\", \"# Catalog magic smoke test\\n\\nCreated by the %catalog debugger notebook.\", tags=[{\"tag_name\": \"owner\", \"tag_value\": \"debugger\", \"tag_title\": \"Owner\"}])" - ], - "id": "29ac62a2" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, + "id": "f76508c9", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "# Catalog magic smoke test\n", + "\n", + "Created by the %catalog debugger notebook.\n", + "\n", + "# Meta Data\n", + "\tOwner : debugger\n", + "\n", + "\n", + "\n" + ] + } + ], "source": [ "print(verify.getwikifrom(TEST_FOLDER, idempotency_key=\"smoke-read-wiki\"))" - ], - "id": "f76508c9" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, + "id": "2a3d9a5b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "['smoke', 'test']" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog set_tags(\".\", [\"#Smoke\", \"test\"])\n", "%catalog get_tags(\".\")" - ], - "id": "2a3d9a5b" + ] }, { "cell_type": "markdown", + "id": "8b2cdc00", "metadata": {}, "source": [ "## 4. What a failed call looks like\n", "\n", "`TEST_FOLDER` holds `nested`, so deleting it without `cascade=True` fails — `%catalog` prints a\n", "short message instead of a traceback." - ], - "id": "8b2cdc00" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, + "id": "5ca5d62e", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "catalog error: commit failed at step 1/1 (delete folder 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'): 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test' is not empty — pass cascade=True to delete everything in it. Everything before it was rolled back.\n" + ] + } + ], "source": [ "%catalog delete_folder(TEST_FOLDER) # cascade=False (the default) — expected to fail, folder not empty" - ], - "id": "5ca5d62e" + ] }, { "cell_type": "markdown", + "id": "6e4f220e", "metadata": {}, "source": [ "## 5. Data: copy, schema, views, move\n", @@ -291,74 +445,143 @@ "`data_copy` runs `CREATE TABLE … AS SELECT` in this kernel's DuckDB, writing an Iceberg table\n", "through Polaris (columns Iceberg can't hold are cast: nanosecond timestamps, geometry, …).\n", "`schema` of a table comes from its Iceberg metadata; of a view, from running its SQL." - ], - "id": "6e4f220e" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, + "id": "a4e6d60b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "CommitReport(succeeded=[\"data_copy 'eea_lakehouse.biodiversity_ecosystems.protected_areas.dfl_natura2000.draft.sites.aaaa' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.nested.copy'\"], notes=[])" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog data_copy(SOURCE_TABLE, \"nested.copy\")" - ], - "id": "a4e6d60b" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, + "id": "f3a7c4aa", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "TableInfo(schema={'id': 'long', 'station': 'string', 'measured_at': 'timestamptz', 'value': 'double', 'is_valid': 'boolean', 'reported_on': 'date'}, row_count=10)" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog schema(\"nested.copy\")" - ], - "id": "f3a7c4aa" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, + "id": "faec2ef2", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "copy is a: TABLE\n" + ] + } + ], "source": [ "print(\"copy is a:\", verify.entry_kind(f\"{TEST_FOLDER}.nested.copy\", idempotency_key=\"smoke\"))" - ], - "id": "faec2ef2" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, + "id": "d7b20734", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "TableInfo(schema={'id': 'long', 'station': 'string', 'measured_at': 'timestamptz', 'value': 'double', 'is_valid': 'boolean', 'reported_on': 'date'}, row_count=10)" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog create_view(\"nested.copy\", \"nested.copy_view\")\n", "%catalog schema(\"nested.copy_view\")" - ], - "id": "d7b20734" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, + "id": "27b35c16", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "SELECT * FROM \"eea_lakehouse\".\"non_domain_datasets.catalog_magic_smoke_test.nested\".\"copy\"\n" + ] + } + ], "source": [ "print(verify.view_sql(f\"{TEST_FOLDER}.nested.copy_view\"))" - ], - "id": "27b35c16" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, + "id": "4509ca89", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[\n", + " {\n", + " \"type\": \"TABLE\",\n", + " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.moved.copy\"\n", + " },\n", + " {\n", + " \"type\": \"VIEW\",\n", + " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.nested.copy_view\"\n", + " }\n", + "]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog data_copy(SOURCE_TABLE, \"nested.copy\", overwrite=True) # replaces the table\n", "%catalog data_move(\"nested.copy\", \"moved/\") # a target ending in / is a folder, created\n", "%catalog list()" - ], - "id": "4509ca89" + ] }, { "cell_type": "markdown", + "id": "5785c55a", "metadata": {}, "source": [ "## 6. A dataflow release: draft → version → latest views\n", @@ -366,14 +589,22 @@ "An Area folder holds `draft`, `versions` and `reference`. `draft_to_version` copies the draft\n", "into `versions.` (views as tables); `update_latest_release` puts a view at the Area's\n", "root over every table of that version and tags it `public`." - ], - "id": "5785c55a" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, + "id": "73a7e215", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "context set to 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke'\n" + ] + } + ], "source": [ "AREA = f\"{TEST_FOLDER}.dfl_smoke\"\n", "%catalog create_folder(f\"{AREA}.draft\", create_parents=True)\n", @@ -381,61 +612,126 @@ "%catalog create_folder(f\"{AREA}.reference\")\n", "%catalog data_copy(SOURCE_TABLE, f\"{AREA}.draft.stations\")\n", "%catalog use(AREA)" - ], - "id": "73a7e215" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, + "id": "fb1e2aec", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "CommitReport(succeeded=[\"create version 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1' from 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft' (all tables)\"], notes=[])" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog draft_to_version(\"v2026_1\")" - ], - "id": "fb1e2aec" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, + "id": "3d8855a5", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "CommitReport(succeeded=[\"create views under 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke' for the tables in 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1'\"], notes=[])" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog update_latest_release(\"v2026_1\")" - ], - "id": "3d8855a5" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, + "id": "65299b51", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[\n", + " {\n", + " \"type\": \"TABLE\",\n", + " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.stations\"\n", + " },\n", + " {\n", + " \"type\": \"VIEW\",\n", + " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.stations\"\n", + " },\n", + " {\n", + " \"type\": \"TABLE\",\n", + " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1.stations\"\n", + " }\n", + "]" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog list()" - ], - "id": "65299b51" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, + "id": "076f21a5", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "['public']" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog get_tags(\"stations\")" - ], - "id": "076f21a5" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, + "id": "32c56703", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "latest view reads the version: SELECT * FROM \"eea_lakehouse\".\"non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1\".\"stations\"\n" + ] + } + ], "source": [ "print(\"latest view reads the version:\", verify.view_sql(f\"{AREA}.stations\"))" - ], - "id": "32c56703" + ] }, { "cell_type": "markdown", + "id": "81655c19", "metadata": {}, "source": [ "### Publishing (writes to the real public store — off by default)\n", @@ -443,21 +739,21 @@ "`publish` pushes every `public` view of the Area through the Document Service to the public\n", "store, at `//`. It needs a Keycloak token of a member of the publishers'\n", "group, and DDS. Uncomment to run — and unpublish afterwards." - ], - "id": "81655c19" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 62, + "id": "fd47c58f", "metadata": {}, "outputs": [], "source": [ "# %catalog publish()" - ], - "id": "fd47c58f" + ] }, { "cell_type": "markdown", + "id": "21202009", "metadata": {}, "source": [ "## 7. `%ingest`: upload to the object store, then a table\n", @@ -466,14 +762,22 @@ "Iceberg table (Parquet, CSV or JSON) and removes the staged files; `\"parquet\"` keeps Parquet\n", "files as they are, registered as a read-only table (`sub_path` adds a sub-folder each time), and\n", "`promote` turns that into Iceberg later. Small local files are generated first." - ], - "id": "21202009" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, + "id": "dba0484a", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "/tmp/catalog_magic_smoke_jpk0iz9v\n" + ] + } + ], "source": [ "import tempfile\n", "\n", @@ -491,78 +795,162 @@ "(INGEST_DIR / \"samples\" / \"samples.csv\").write_text(\"id;value\\n1;3.5\\n2;4.0\\n3;4.5\\n\")\n", "TEMPS, SAMPLES = str(INGEST_DIR / \"temps\"), str(INGEST_DIR / \"samples\")\n", "print(INGEST_DIR)" - ], - "id": "dba0484a" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 26, + "id": "b42ca6d2", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ingest '/tmp/catalog_magic_smoke_jpk0iz9v/temps' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft' (Polaris):\n", + "✓ sign-in: Keycloak user 'eea-admin'\n", + "✓ files: 1 parquet file(s), 1002 bytes\n", + "✓ target: eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps (new)\n", + "✓ storage: s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091904Z-9e22cb/temps/ reachable (sts keys)\n", + "ingest '/tmp/catalog_magic_smoke_jpk0iz9v/samples' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft' (Polaris):\n", + "✓ sign-in: Keycloak user 'eea-admin'\n", + "✓ files: 1 csv file(s), 27 bytes\n", + "✓ target: eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples (new)\n", + "✓ storage: s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091904Z-5f48fb/samples/ reachable (sts keys)\n", + "ingest '/tmp/catalog_magic_smoke_jpk0iz9v/temps' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference' (Polaris):\n", + "✓ sign-in: Keycloak user 'eea-admin'\n", + "✓ files: 1 parquet file(s), 1002 bytes\n", + "✓ target: eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro (new)\n", + "✓ storage: s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/reference/temps_ro/ reachable (sts keys)\n" + ] + } + ], "source": [ "%ingest ingest(folder=TEMPS, target_catalog_path=f\"{AREA}.draft\", data_format=\"parquet\", table_name=\"temps\")\n", "%ingest ingest(folder=SAMPLES, target_catalog_path=f\"{AREA}.draft\", data_format=\"csv\", csv_options={\"delimiter\": \";\"})\n", "%ingest ingest(folder=TEMPS, target_catalog_path=f\"{AREA}.reference\", data_format=\"parquet\", table_format=\"parquet\", table_name=\"temps_ro\", sub_path=\"2026\")\n", "%ingest diagnose" - ], - "id": "b42ca6d2" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 27, + "id": "f8b18f98", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "uploading 1 file(s) to s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091909Z-d1eec3/temps/\n", + " uploaded 1/1: part-1.parquet\n", + "loading into eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps\n", + "uploading 1 file(s) to s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091910Z-09e10f/samples/\n", + " uploaded 1/1: samples.csv\n", + "loading into eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples\n", + "uploading 1 file(s) to s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/reference/temps_ro/2026/\n", + " uploaded 1/1: part-1.parquet\n", + "created iceberg table eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps (2 rows, 1 files)\n", + "created iceberg table eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples (3 rows, 1 files)\n", + "created parquet table eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro (2 rows, 1 files) at s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/reference/temps_ro/\n" + ] + } + ], "source": [ "report = %ingest commit\n", "for outcome in report.outcomes:\n", " print(outcome)\n", " for note in outcome.notes:\n", " print(\" note:\", note)" - ], - "id": "f8b18f98" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, + "id": "2d3e7b30", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "TableInfo(schema={'site': 'string', 'temp': 'double', 'at': 'timestamp'}, row_count=2)" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog schema(\"draft.temps\")" - ], - "id": "2d3e7b30" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 29, + "id": "2858c4fc", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "TableInfo(schema={'site': 'VARCHAR', 'temp': 'DOUBLE', 'at': 'TIMESTAMP_NS'}, row_count=2)" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog schema(\"reference.temps_ro\")" - ], - "id": "2858c4fc" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, + "id": "7ca12f16", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "PolarisIngestOutcome(table='eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro', table_format='iceberg', action='promoted', rows=2, files=1, location=None, notes=[])" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%ingest promote(f\"{AREA}.reference.temps_ro\")" - ], - "id": "7ca12f16" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 31, + "id": "be93abcd", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "TableInfo(schema={'site': 'string', 'temp': 'double', 'at': 'timestamp'}, row_count=2)" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%catalog schema(\"reference.temps_ro\")" - ], - "id": "be93abcd" + ] }, { "cell_type": "markdown", + "id": "134d95ff", "metadata": {}, "source": [ "## 8. `%dds` — the context's document folders\n", @@ -570,33 +958,56 @@ "On Polaris `%dds` signs in with your Keycloak token (the eea-admin sign-in above) and stores\n", "under the namespace's path without the catalog name\n", "(`…non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/…`)." - ], - "id": "134d95ff" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, + "id": "299b0378", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables'" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "(INGEST_DIR / \"readme.txt\").write_text(\"catalog magic smoke test\")\n", "%dds target(DELIVERABLES)" - ], - "id": "299b0378" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, + "id": "959cbdc3", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "1 file(s) in non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables:\n", + " readme.txt" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%dds push(DELIVERABLES, str(INGEST_DIR / \"readme.txt\"), overwrite=True)\n", "%dds list(DELIVERABLES)" - ], - "id": "959cbdc3" + ] }, { "cell_type": "markdown", + "id": "511131a3", "metadata": {}, "source": [ "## 9. `%gpkg` — GeoPackage export\n", @@ -605,53 +1016,109 @@ "`FLIGHT_HOST` names one (as you: your Keycloak token). With `FLIGHT_HOST` empty — the\n", "172.28.1.6 cluster has no Flight gateway — it reads them through this kernel's own DuckDB,\n", "signed in as `%catalog` is. Spatial tables become feature layers, the rest attribute tables." - ], - "id": "511131a3" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 34, + "id": "63146098", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "exporting 6 table(s)/view(s) from eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke to /tmp/catalog_magic_smoke_jpk0iz9v/catalog_magic_smoke.gpkg, 4 at a time\n", + "✓ 1/6 temps_ro ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro: attributes, 2 rows, 0.3s\n", + "✓ 2/6 temps ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps: attributes, 2 rows, 0.3s\n", + "✓ 3/6 draft_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.stations: attributes, 10 rows, 0.8s\n", + "✓ 4/6 samples ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples: attributes, 3 rows, 0.9s\n", + "✓ 5/6 versions_v2026_1_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1.stations: attributes, 10 rows, 0.6s\n", + "✓ 6/6 stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.stations: attributes, 10 rows, 0.6s\n", + "done: /tmp/catalog_magic_smoke_jpk0iz9v/catalog_magic_smoke.gpkg — 6 layer(s), 37 rows in 0.9s\n" + ] + }, + { + "data": { + "text/plain": [ + "wrote /tmp/catalog_magic_smoke_jpk0iz9v/catalog_magic_smoke.gpkg — 6 layer(s):\n", + " samples ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples [attributes (no geometry); 3 rows]\n", + " draft_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.stations [attributes (no geometry); 10 rows]\n", + " temps ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps [attributes (no geometry); 2 rows]\n", + " temps_ro ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro [attributes (no geometry); 2 rows]\n", + " stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.stations [attributes (no geometry); 10 rows]\n", + " versions_v2026_1_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1.stations [attributes (no geometry); 10 rows]" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "gpkg = %gpkg export(limit=100, filename=\"catalog_magic_smoke.gpkg\", output_dir=str(INGEST_DIR))\n", "gpkg" - ], - "id": "63146098" + ] }, { "cell_type": "markdown", + "id": "a64d12fb", "metadata": {}, "source": [ "### Upload the GeoPackage to DDS\n", "\n", "The export's report is the file: `%dds push` takes it as it is and stores it under the\n", "context's `deliverables` folder, replacing an earlier upload of the same name." - ], - "id": "a64d12fb" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, + "id": "7c9af9f6", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "pushed 1 file(s) to non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables:\n", + " non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables/catalog_magic_smoke.gpkg" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%dds push(DELIVERABLES, gpkg, overwrite=True)" - ], - "id": "7c9af9f6" + ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 72, + "id": "14fc8734", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "2 file(s) in non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables:\n", + " catalog_magic_smoke.gpkg\n", + " readme.txt" + ] + }, + "execution_count": 72, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "%dds list(DELIVERABLES)" - ], - "id": "14fc8734" + ] }, { "cell_type": "markdown", + "id": "b6d9f8dd", "metadata": {}, "source": [ "## Cleanup\n", @@ -660,27 +1127,69 @@ "A principal Polaris doesn't let purge files (e.g. the root client) drops tables from the catalog\n", "only; the cell after it removes whatever data files are left in the scratch folder's own\n", "storage location — nothing else." - ], - "id": "b6d9f8dd" + ] + }, + { + "cell_type": "markdown", + "id": "2db4891d", + "metadata": {}, + "source": [] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 36, + "id": "5484c544", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "context set to 'eea_lakehouse'\n", + "folder exists after cleanup: False\n" + ] + } + ], "source": [ "SCRATCH_LOCATION = verify.rest.namespace_properties(verify.parts(TEST_FOLDER)).get(\"location\")\n", "%catalog use(None)\n", "%catalog delete_folder(TEST_FOLDER, cascade=True)\n", "print(\"folder exists after cleanup:\", verify.exists(TEST_FOLDER))" - ], - "id": "5484c544" + ] }, { "cell_type": "code", "execution_count": null, + "id": "ce67120b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "PolarisSettings(uri='https://172.28.1.6:31443/api/catalog', catalog='eea_lakehouse', client_id='root', client_secret='c4059968fcf7d35986bde938b8825ff08b1e2cc3010f84c2f7179f1e79d409d1', vended_credentials=False, s3_endpoint='http://localhost:19000', s3_region='us-east-1', s3_access_key='rustfsadmin', s3_secret_key='8aaee44a1efe51eeefd74903aceb8a63ab0b317211e622bbc7bd1435e2eada9a', ingest_bucket='', ingest_prefix='_ingestion', role_arn='arn:aws:iam:::role/eea-datalakehouse', flight_host='', flight_port=8815, dds_base_url='https://172.28.1.6:31443/dds', ca_file='/home/oesparza/datahub/EEALakeHouse.python/debugger/lakehouse-ca.crt')" + ] + }, + "execution_count": 75, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "69cde9e9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "removed 32 leftover file(s) under s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/\n" + ] + } + ], "source": [ "from eea_datalakehouse.catalog.object_store import ObjectStore, s3_credentials\n", "\n", @@ -690,13 +1199,12 @@ " store.delete(left)\n", " print(f\"removed {len(left)} leftover file(s) under {SCRATCH_LOCATION}\")\n", "verify.close()" - ], - "id": "69cde9e9" + ] } ], "metadata": { "kernelspec": { - "display_name": ".venv (3.12.3)", + "display_name": "Python 3", "language": "python", "name": "python3" }, @@ -710,7 +1218,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.12.3" + "version": "3.14.10" } }, "nbformat": 4, From 9519b2bc4576cee89e29716cac6ce1d92a47f57a Mon Sep 17 00:00:00 2001 From: oesparza Date: Tue, 1 Dec 2026 10:40:19 +0100 Subject: [PATCH 25/25] Catalog test notebook: strip outputs Co-Authored-By: Claude Opus 5.5 --- debugger/test_catalog_magic.ipynb | 655 ++++-------------------------- 1 file changed, 79 insertions(+), 576 deletions(-) diff --git a/debugger/test_catalog_magic.ipynb b/debugger/test_catalog_magic.ipynb index 72b0b59..341df06 100644 --- a/debugger/test_catalog_magic.ipynb +++ b/debugger/test_catalog_magic.ipynb @@ -29,27 +29,10 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "id": "3f7af2e9", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sign in to the EEA Lakehouse: open https://172.28.1.6:31443/auth/realms/eea_datalakehouse/device?user_code=EWYT-YSAG (code EWYT-YSAG)\n", - "signed in as eea-admin\n", - "env file /home/oesparza/datahub/EEALakeHouse.python/debugger/.env\n", - "backend polaris\n", - "POLARIS_URI https://172.28.1.6:31443/api/catalog\n", - "catalog (root) eea_lakehouse\n", - "CA file /home/oesparza/datahub/EEALakeHouse.python/debugger/lakehouse-ca.crt\n", - "signed in as eea-admin\n", - "object store http://172.28.1.6:9000\n", - "DDS https://172.28.1.6:31443/dds\n" - ] - } - ], + "outputs": [], "source": [ "import os\n", "from pathlib import Path\n", @@ -100,7 +83,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "id": "bdfc96fa", "metadata": {}, "outputs": [], @@ -120,38 +103,10 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "id": "b94a800b", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "%catalog methods — usage: %catalog data_copy(\"a.b\", \"c.d\") | %catalog set_tags(\"a.b\", [\"reviewed\"]) (each call runs immediately)\n", - "Backend: Dremio or Polaris, picked by EEA_CATALOG_BACKEND (unset: Polaris when POLARIS_URI is set). On Polaris paths start with the catalog's name (POLARIS_CATALOG, 'eea_lakehouse'), a folder is a namespace, and you are signed in with your Keycloak token (KEYCLOAK_ACCESS_TOKEN; else POLARIS_CLIENT_ID/POLARIS_CLIENT_SECRET).\n", - "A new session's context starts at 'catalog' (the root source), not empty — use(None)/use('') reset back to it too; only set_context(None) clears it to no context at all.\n", - "Every path/source_path/target_path (except use's own) is either absolute or relative to the current context, once one is set:\n", - " - starts with 'catalog.' (this deployment's one real root source; 'eea_lakehouse.' on Polaris) -> always absolute, used exactly as given, never appended to the context\n", - " - '.' or './' alone -> the context itself, exactly as get_context() shows it\n", - " - '../' (or a bare '..'), optionally chained ('../../') -> walks up that many levels of the context first, then appends whatever's left, if anything\n", - " - '.name', or a bare 'name' with no leading '.' at all -> both mean relative to the context; the dot is optional sugar, not what makes it relative\n", - "Only use() ever changes the context — no other call does, even one that fully resolved an absolute path.\n" - ] - }, - { - "data": { - "text/html": [ - "
CommandParametersDescription
usepathSet the current path for every call after this one; path must be a whole, absolute path — never relative to the current context, unlike every other verb's path/source_path/target_path. None or '' resets it to the root ('catalog' on Dremio, 'eea_lakehouse' on Polaris). Raises if path doesn't exist in the catalog. See %%catalog to set it once at the top of a cell.
get_contextShow the current path. A new session starts at the root ('catalog' on Dremio, 'eea_lakehouse' on Polaris); use(None)/use('') reset back to it too — None only after an explicit set_context(None).
data_copysource_path, target_path, overwrite=False, create_target_folder=FalseCopy source_path to target_path. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. A target_path ending in / is a folder, not the table: the folder is created first if it doesn't exist (every missing level), and the table lands inside it under the source's own name — data_copy("draft.t", "archive/2027/") makes archive.2027.t; "./" is the context itself; undo removes the folders it created. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
data_movesource_path, target_path, overwrite=False, create_target_folder=FalseMove source_path to target_path, always as a TABLE (use create_view for a view). overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. A target_path ending in / is a folder, not the table: the folder is created first if it doesn't exist (every missing level), and the table lands inside it under the source's own name — data_copy("draft.t", "archive/2027/") makes archive.2027.t; "./" is the context itself; undo removes the folders it created. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
create_versionsource_path, version_name, tables=None, target_path=None, overwrite=False, create_target_folder=TrueCopy the listed tables from source_path into a new folder target_path.version_name (as CREATE TABLE snapshots, keeping each table's sub-folders). source_path and version_name must not be blank. tables omitted or empty copies everything under source_path. Each entry is a table or a folder (= every table under it), named as listed under source_path or as list() shows them. target_path omitted means the current context — use() picks where versions go; a missing target_path is created unless create_target_folder=False. Reference/vocabulary tables (a folder named reference(s)/vocabulary(ies) in the path) and views are skipped; the report's notes say which. An existing version folder is an error unless overwrite=True (replaces the listed tables, keeps the rest).
draft_to_versionversion_name, tables=None, overwrite=Falsecreate_version from the dataflow's draft folder, with no paths to type: the source is the draft folder the context is in (or the draft folder inside the context), the target is draft's parent.versions.version_name (versions is created if missing). tables as in create_version: omitted or empty copies everything in draft. Unlike create_version, views in draft are not skipped: each is copied into the version as a table (a snapshot of what it returns); the report's notes say which.
update_latest_releaseversion_name, overwrite=TrueCreate a view at the Area's root for every table in versions.version_name, keeping its sub-folders (versions.v1.a.t gets the view a.t; missing folders are created). The context must be the Area folder — one with draft and versions folders just below it, typically catalog.<domain>.<subdomain>.<area> — and versions.version_name must exist — raises at once otherwise. Views in the version are skipped. An existing view is dropped and recreated over the version (overwrite=True, the default; not undoable) — overwrite=False makes it an error instead; an existing table is always an error. Each view is tagged #public, and #public is removed from every table/view under versions, so only the latest release is public.
publishpath=None, overwrite=True, partition_by=NoneCopy every #public view of a dataflow folder (as update_latest_release leaves them) into public_s3."dh-prod-data-public", as tables at the same full catalog path (catalog.x.y.dataflow.a.t is copied to public_s3."dh-prod-data-public".catalog.x.y.dataflow.a.t). The dataflow folder is path when given (absolute, or relative to the context), else the %catalog use(...) context; with neither it raises. It must have draft, versions and reference (or references) folders just below it — raises at once otherwise. Views and tables in those three folders are ignored; views without the tag are skipped and the report's notes say which. An existing table is replaced (overwrite=True, the default; not undoable) — overwrite=False makes it an error, and then nothing is copied. Each table is checked once copied, and the report's notes give its row count. All or nothing: if any table fails, everything the publish did is rolled back (replaced tables are restored) and an error says which table failed. partition_by (optional) partitions the tables by existing fields, in order: a list for every view (partition_by=["year", "country"]), or a dict for each view's own, keyed by its path below the Area (partition_by={"eu_sdg.monitoringsites": ["year"]}; views left out are not partitioned). A field a view doesn't have raises at once, when publish is called. On Polaris each #public view goes through the Document Service into the public store at <namespace path>/<view>/ (DDS_BASE_URL; you must be a publisher): not all or nothing — an error names the views already published — and partition_by / overwrite=False are not available.
listpath=''Show every table/view under path as a JSON array of {type, name} — type TABLE or VIEW, name the full dot-separated path: its own, then every child folder's, at any depth — walked folder by folder through the catalog's own API (Dremio's or Polaris'), no SQL. path may use '.' or '/' separators. path may be omitted to list the current context itself — raises CatalogSessionError if none is set. Raises CatalogOperationError if path doesn't exist.
schemapathShow path's column schema and row count (never fetches the actual rows). path must be a table or view — raises CatalogOperationError otherwise, or if path doesn't exist at all.
delete_tablepathDelete the table at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP TABLE, this doesn't quietly no-op on a typo).
create_viewsource_path, target_path, overwrite=False, create_target_folder=FalseCreate a VIEW at target_path over source_path, leaving source_path untouched. overwrite=False (default) raises CatalogOperationError if target_path already exists; overwrite=True replaces it and is not undoable. create_target_folder=True creates every missing folder level of target_path — except the space/source itself, which must already exist (raises CatalogOperationError otherwise).
delete_viewpathDelete the view at path. Not undoable. Raises CatalogOperationError if path doesn't exist (unlike a bare DROP VIEW, this doesn't quietly no-op on a typo).
set_wikipath, text, tags=NoneSet a path's wiki text. tags: a list of {tag_name, tag_value, tag_title} dicts, e.g. [{"tag_name": "owner", "tag_value": "bw-team", "tag_title": "Owner"}]. Ignored if path is a table/view (they have set_tags/get_tags for that instead).
delete_wikipathDelete a path's wiki text.
get_wikipathShow a path's wiki text. Raises CatalogOperationError if the path doesn't exist, or exists but has no wiki at all.
set_tagspath, tagsReplace a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise. On Polaris folders take tags too, and tags are kept lower case without '#' ('#public' and 'public' are the same tag).
delete_tagspath, tagsRemove tags from a path's tag set. tags: a list of strings, e.g. ["reviewed"]. Tables/views only — raises CatalogOperationError otherwise.
get_tagspathShow the tags on a path — tables/views only. Raises CatalogOperationError if the path doesn't exist or isn't a table/view.
create_folderpath, create_parents=FalseCreate a folder. create_parents=True creates every missing level of the full path; create_parents=False (default) raises CatalogOperationError if the parent folder doesn't already exist.
delete_folderpath, cascade=FalseDelete a folder. Not undoable. cascade=True also deletes everything at path and below; cascade=False (default) raises CatalogOperationError if the folder isn't empty. A path that's already gone is not an error.
" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "outputs": [], "source": [ "%catalog help" ] @@ -170,19 +125,10 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "id": "c4c97822", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "TEST_FOLDER eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test (exists already!)\n", - "SOURCE_TABLE eea_lakehouse.biodiversity_ecosystems.protected_areas.dfl_natura2000.draft.sites.aaaa exists: True\n" - ] - } - ], + "outputs": [], "source": [ "from eea_datalakehouse.catalog.polaris import PolarisCatalog\n", "\n", @@ -209,39 +155,20 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": null, "id": "45d8ff5e", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create folder 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'\"], notes=[])" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog create_folder(TEST_FOLDER, create_parents=True)" ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": null, "id": "d90b81ed", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "folder exists right now: True | is a namespace: True\n" - ] - } - ], + "outputs": [], "source": [ "print(\"folder exists right now:\", verify.exists(TEST_FOLDER), \"| is a namespace:\", verify.is_folder(TEST_FOLDER))" ] @@ -259,28 +186,10 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": null, "id": "3721db27", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "context set to 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'\n" - ] - }, - { - "data": { - "text/plain": [ - "'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog use(TEST_FOLDER)\n", "%catalog get_context()" @@ -288,39 +197,20 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": null, "id": "bedfc770", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create folder 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.nested'\"], notes=[])" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog create_folder(\"nested\") # -> TEST_FOLDER + \".nested\"" ] }, { "cell_type": "code", - "execution_count": 9, + "execution_count": null, "id": "3bd26c7e", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "nested folder exists right now: True\n" - ] - } - ], + "outputs": [], "source": [ "print(\"nested folder exists right now:\", verify.exists(f\"{TEST_FOLDER}.nested\"))" ] @@ -339,68 +229,30 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": null, "id": "29ac62a2", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"set wiki on 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'\"], notes=[])" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog set_wiki(\".\", \"# Catalog magic smoke test\\n\\nCreated by the %catalog debugger notebook.\", tags=[{\"tag_name\": \"owner\", \"tag_value\": \"debugger\", \"tag_title\": \"Owner\"}])" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": null, "id": "f76508c9", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "# Catalog magic smoke test\n", - "\n", - "Created by the %catalog debugger notebook.\n", - "\n", - "# Meta Data\n", - "\tOwner : debugger\n", - "\n", - "\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "print(verify.getwikifrom(TEST_FOLDER, idempotency_key=\"smoke-read-wiki\"))" ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": null, "id": "2a3d9a5b", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['smoke', 'test']" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog set_tags(\".\", [\"#Smoke\", \"test\"])\n", "%catalog get_tags(\".\")" @@ -419,18 +271,10 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": null, "id": "5ca5d62e", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "catalog error: commit failed at step 1/1 (delete folder 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test'): 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test' is not empty — pass cascade=True to delete everything in it. Everything before it was rolled back.\n" - ] - } - ], + "outputs": [], "source": [ "%catalog delete_folder(TEST_FOLDER) # cascade=False (the default) — expected to fail, folder not empty" ] @@ -449,81 +293,40 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": null, "id": "a4e6d60b", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"data_copy 'eea_lakehouse.biodiversity_ecosystems.protected_areas.dfl_natura2000.draft.sites.aaaa' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.nested.copy'\"], notes=[])" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog data_copy(SOURCE_TABLE, \"nested.copy\")" ] }, { "cell_type": "code", - "execution_count": 14, + "execution_count": null, "id": "f3a7c4aa", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TableInfo(schema={'id': 'long', 'station': 'string', 'measured_at': 'timestamptz', 'value': 'double', 'is_valid': 'boolean', 'reported_on': 'date'}, row_count=10)" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog schema(\"nested.copy\")" ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": null, "id": "faec2ef2", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "copy is a: TABLE\n" - ] - } - ], + "outputs": [], "source": [ "print(\"copy is a:\", verify.entry_kind(f\"{TEST_FOLDER}.nested.copy\", idempotency_key=\"smoke\"))" ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": null, "id": "d7b20734", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TableInfo(schema={'id': 'long', 'station': 'string', 'measured_at': 'timestamptz', 'value': 'double', 'is_valid': 'boolean', 'reported_on': 'date'}, row_count=10)" - ] - }, - "execution_count": 16, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog create_view(\"nested.copy\", \"nested.copy_view\")\n", "%catalog schema(\"nested.copy_view\")" @@ -531,48 +334,20 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": null, "id": "27b35c16", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "SELECT * FROM \"eea_lakehouse\".\"non_domain_datasets.catalog_magic_smoke_test.nested\".\"copy\"\n" - ] - } - ], + "outputs": [], "source": [ "print(verify.view_sql(f\"{TEST_FOLDER}.nested.copy_view\"))" ] }, { "cell_type": "code", - "execution_count": 18, + "execution_count": null, "id": "4509ca89", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.moved.copy\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.nested.copy_view\"\n", - " }\n", - "]" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog data_copy(SOURCE_TABLE, \"nested.copy\", overwrite=True) # replaces the table\n", "%catalog data_move(\"nested.copy\", \"moved/\") # a target ending in / is a folder, created\n", @@ -593,18 +368,10 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": null, "id": "73a7e215", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "context set to 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke'\n" - ] - } - ], + "outputs": [], "source": [ "AREA = f\"{TEST_FOLDER}.dfl_smoke\"\n", "%catalog create_folder(f\"{AREA}.draft\", create_parents=True)\n", @@ -616,115 +383,50 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": null, "id": "fb1e2aec", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create version 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1' from 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft' (all tables)\"], notes=[])" - ] - }, - "execution_count": 20, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog draft_to_version(\"v2026_1\")" ] }, { "cell_type": "code", - "execution_count": 21, + "execution_count": null, "id": "3d8855a5", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "CommitReport(succeeded=[\"create views under 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke' for the tables in 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1'\"], notes=[])" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog update_latest_release(\"v2026_1\")" ] }, { "cell_type": "code", - "execution_count": 22, + "execution_count": null, "id": "65299b51", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.stations\"\n", - " },\n", - " {\n", - " \"type\": \"VIEW\",\n", - " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.stations\"\n", - " },\n", - " {\n", - " \"type\": \"TABLE\",\n", - " \"name\": \"eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1.stations\"\n", - " }\n", - "]" - ] - }, - "execution_count": 22, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog list()" ] }, { "cell_type": "code", - "execution_count": 23, + "execution_count": null, "id": "076f21a5", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "['public']" - ] - }, - "execution_count": 23, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog get_tags(\"stations\")" ] }, { "cell_type": "code", - "execution_count": 24, + "execution_count": null, "id": "32c56703", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "latest view reads the version: SELECT * FROM \"eea_lakehouse\".\"non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1\".\"stations\"\n" - ] - } - ], + "outputs": [], "source": [ "print(\"latest view reads the version:\", verify.view_sql(f\"{AREA}.stations\"))" ] @@ -743,7 +445,7 @@ }, { "cell_type": "code", - "execution_count": 62, + "execution_count": null, "id": "fd47c58f", "metadata": {}, "outputs": [], @@ -766,18 +468,10 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": null, "id": "dba0484a", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "/tmp/catalog_magic_smoke_jpk0iz9v\n" - ] - } - ], + "outputs": [], "source": [ "import tempfile\n", "\n", @@ -799,32 +493,10 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": null, "id": "b42ca6d2", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "ingest '/tmp/catalog_magic_smoke_jpk0iz9v/temps' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft' (Polaris):\n", - "✓ sign-in: Keycloak user 'eea-admin'\n", - "✓ files: 1 parquet file(s), 1002 bytes\n", - "✓ target: eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps (new)\n", - "✓ storage: s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091904Z-9e22cb/temps/ reachable (sts keys)\n", - "ingest '/tmp/catalog_magic_smoke_jpk0iz9v/samples' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft' (Polaris):\n", - "✓ sign-in: Keycloak user 'eea-admin'\n", - "✓ files: 1 csv file(s), 27 bytes\n", - "✓ target: eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples (new)\n", - "✓ storage: s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091904Z-5f48fb/samples/ reachable (sts keys)\n", - "ingest '/tmp/catalog_magic_smoke_jpk0iz9v/temps' -> 'eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference' (Polaris):\n", - "✓ sign-in: Keycloak user 'eea-admin'\n", - "✓ files: 1 parquet file(s), 1002 bytes\n", - "✓ target: eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro (new)\n", - "✓ storage: s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/reference/temps_ro/ reachable (sts keys)\n" - ] - } - ], + "outputs": [], "source": [ "%ingest ingest(folder=TEMPS, target_catalog_path=f\"{AREA}.draft\", data_format=\"parquet\", table_name=\"temps\")\n", "%ingest ingest(folder=SAMPLES, target_catalog_path=f\"{AREA}.draft\", data_format=\"csv\", csv_options={\"delimiter\": \";\"})\n", @@ -834,28 +506,10 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": null, "id": "f8b18f98", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "uploading 1 file(s) to s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091909Z-d1eec3/temps/\n", - " uploaded 1/1: part-1.parquet\n", - "loading into eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps\n", - "uploading 1 file(s) to s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/draft/_ingestion/eea_admin-20261201T091910Z-09e10f/samples/\n", - " uploaded 1/1: samples.csv\n", - "loading into eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples\n", - "uploading 1 file(s) to s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/reference/temps_ro/2026/\n", - " uploaded 1/1: part-1.parquet\n", - "created iceberg table eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps (2 rows, 1 files)\n", - "created iceberg table eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples (3 rows, 1 files)\n", - "created parquet table eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro (2 rows, 1 files) at s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/reference/temps_ro/\n" - ] - } - ], + "outputs": [], "source": [ "report = %ingest commit\n", "for outcome in report.outcomes:\n", @@ -866,84 +520,40 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": null, "id": "2d3e7b30", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TableInfo(schema={'site': 'string', 'temp': 'double', 'at': 'timestamp'}, row_count=2)" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog schema(\"draft.temps\")" ] }, { "cell_type": "code", - "execution_count": 29, + "execution_count": null, "id": "2858c4fc", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TableInfo(schema={'site': 'VARCHAR', 'temp': 'DOUBLE', 'at': 'TIMESTAMP_NS'}, row_count=2)" - ] - }, - "execution_count": 29, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog schema(\"reference.temps_ro\")" ] }, { "cell_type": "code", - "execution_count": 30, + "execution_count": null, "id": "7ca12f16", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "PolarisIngestOutcome(table='eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro', table_format='iceberg', action='promoted', rows=2, files=1, location=None, notes=[])" - ] - }, - "execution_count": 30, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%ingest promote(f\"{AREA}.reference.temps_ro\")" ] }, { "cell_type": "code", - "execution_count": 31, + "execution_count": null, "id": "be93abcd", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "TableInfo(schema={'site': 'string', 'temp': 'double', 'at': 'timestamp'}, row_count=2)" - ] - }, - "execution_count": 31, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%catalog schema(\"reference.temps_ro\")" ] @@ -962,21 +572,10 @@ }, { "cell_type": "code", - "execution_count": 32, + "execution_count": null, "id": "299b0378", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables'" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "(INGEST_DIR / \"readme.txt\").write_text(\"catalog magic smoke test\")\n", "%dds target(DELIVERABLES)" @@ -984,22 +583,10 @@ }, { "cell_type": "code", - "execution_count": 33, + "execution_count": null, "id": "959cbdc3", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "1 file(s) in non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables:\n", - " readme.txt" - ] - }, - "execution_count": 33, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%dds push(DELIVERABLES, str(INGEST_DIR / \"readme.txt\"), overwrite=True)\n", "%dds list(DELIVERABLES)" @@ -1020,41 +607,10 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": null, "id": "63146098", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "exporting 6 table(s)/view(s) from eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke to /tmp/catalog_magic_smoke_jpk0iz9v/catalog_magic_smoke.gpkg, 4 at a time\n", - "✓ 1/6 temps_ro ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro: attributes, 2 rows, 0.3s\n", - "✓ 2/6 temps ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps: attributes, 2 rows, 0.3s\n", - "✓ 3/6 draft_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.stations: attributes, 10 rows, 0.8s\n", - "✓ 4/6 samples ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples: attributes, 3 rows, 0.9s\n", - "✓ 5/6 versions_v2026_1_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1.stations: attributes, 10 rows, 0.6s\n", - "✓ 6/6 stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.stations: attributes, 10 rows, 0.6s\n", - "done: /tmp/catalog_magic_smoke_jpk0iz9v/catalog_magic_smoke.gpkg — 6 layer(s), 37 rows in 0.9s\n" - ] - }, - { - "data": { - "text/plain": [ - "wrote /tmp/catalog_magic_smoke_jpk0iz9v/catalog_magic_smoke.gpkg — 6 layer(s):\n", - " samples ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.samples [attributes (no geometry); 3 rows]\n", - " draft_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.stations [attributes (no geometry); 10 rows]\n", - " temps ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.draft.temps [attributes (no geometry); 2 rows]\n", - " temps_ro ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.reference.temps_ro [attributes (no geometry); 2 rows]\n", - " stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.stations [attributes (no geometry); 10 rows]\n", - " versions_v2026_1_stations ← eea_lakehouse.non_domain_datasets.catalog_magic_smoke_test.dfl_smoke.versions.v2026_1.stations [attributes (no geometry); 10 rows]" - ] - }, - "execution_count": 34, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "gpkg = %gpkg export(limit=100, filename=\"catalog_magic_smoke.gpkg\", output_dir=str(INGEST_DIR))\n", "gpkg" @@ -1073,45 +629,20 @@ }, { "cell_type": "code", - "execution_count": 35, + "execution_count": null, "id": "7c9af9f6", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "pushed 1 file(s) to non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables:\n", - " non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables/catalog_magic_smoke.gpkg" - ] - }, - "execution_count": 35, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%dds push(DELIVERABLES, gpkg, overwrite=True)" ] }, { "cell_type": "code", - "execution_count": 72, + "execution_count": null, "id": "14fc8734", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "2 file(s) in non_domain_datasets/catalog_magic_smoke_test/dfl_smoke/deliverables:\n", - " catalog_magic_smoke.gpkg\n", - " readme.txt" - ] - }, - "execution_count": 72, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "%dds list(DELIVERABLES)" ] @@ -1137,19 +668,10 @@ }, { "cell_type": "code", - "execution_count": 36, + "execution_count": null, "id": "5484c544", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "context set to 'eea_lakehouse'\n", - "folder exists after cleanup: False\n" - ] - } - ], + "outputs": [], "source": [ "SCRATCH_LOCATION = verify.rest.namespace_properties(verify.parts(TEST_FOLDER)).get(\"location\")\n", "%catalog use(None)\n", @@ -1162,34 +684,15 @@ "execution_count": null, "id": "ce67120b", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "PolarisSettings(uri='https://172.28.1.6:31443/api/catalog', catalog='eea_lakehouse', client_id='root', client_secret='c4059968fcf7d35986bde938b8825ff08b1e2cc3010f84c2f7179f1e79d409d1', vended_credentials=False, s3_endpoint='http://localhost:19000', s3_region='us-east-1', s3_access_key='rustfsadmin', s3_secret_key='8aaee44a1efe51eeefd74903aceb8a63ab0b317211e622bbc7bd1435e2eada9a', ingest_bucket='', ingest_prefix='_ingestion', role_arn='arn:aws:iam:::role/eea-datalakehouse', flight_host='', flight_port=8815, dds_base_url='https://172.28.1.6:31443/dds', ca_file='/home/oesparza/datahub/EEALakeHouse.python/debugger/lakehouse-ca.crt')" - ] - }, - "execution_count": 75, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [] }, { "cell_type": "code", - "execution_count": 37, + "execution_count": null, "id": "69cde9e9", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "removed 32 leftover file(s) under s3://lakehouse/catalog/non_domain_datasets/catalog_magic_smoke_test/\n" - ] - } - ], + "outputs": [], "source": [ "from eea_datalakehouse.catalog.object_store import ObjectStore, s3_credentials\n", "\n",