diff --git a/debugger/test_magics_jupyterlab.ipynb b/debugger/test_magics_jupyterlab.ipynb new file mode 100644 index 0000000..d716cfa --- /dev/null +++ b/debugger/test_magics_jupyterlab.ipynb @@ -0,0 +1,667 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cell-00", + "metadata": {}, + "source": [ + "# `eea_datalakehouse` magics — test on the Polaris stack\n", + "\n", + "Runs `%catalog`, `%ingest`, `%dds` and `%gpkg` against this JupyterLab's own stack, with **your** Keycloak\n", + "sign-in (nothing to configure: the settings come from the pod's environment). Each step is followed by an\n", + "independent check through a separate `PolarisCatalog` client the magics never touch.\n", + "\n", + "Everything is written under one scratch folder (`TEST_FOLDER`) and removed in **Cleanup**. The only existing\n", + "table touched is `SOURCE_TABLE`, and only read. Run the cells in order; **Restart kernel and run all** works too.\n", + "\n", + "The in-cluster counterpart of `debugger/test_catalog_magic.ipynb`: open it in the stack's own JupyterLab (copy it into your work folder), where the kernel already has the settings and your token, instead of a `debugger/.env` and a device-code sign-in." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-01", + "metadata": {}, + "outputs": [], + "source": [ + "import importlib.metadata\n", + "import os\n", + "\n", + "import eea_datalakehouse.notebook # registers %catalog/%ingest/%dds/%gpkg/%sdi — no %load_ext needed\n", + "from eea_datalakehouse.catalog.object_store import token_username\n", + "from eea_datalakehouse.catalog.settings import PolarisSettings, backend_name, user_token\n", + "\n", + "SETTINGS = PolarisSettings.from_env()\n", + "print(f\"library EEADataLakehouse {importlib.metadata.version('EEADataLakehouse')}\")\n", + "print(f\"backend {backend_name()}\")\n", + "print(f\"POLARIS_URI {SETTINGS.uri}\")\n", + "print(f\"catalog (root) {SETTINGS.catalog}\")\n", + "print(f\"object store {SETTINGS.s3_endpoint}\")\n", + "print(f\"CA file {SETTINGS.ca_file or ''}\")\n", + "print(f\"DDS {SETTINGS.dds_base_url or ''}\")\n", + "print(f\"signed in as {token_username(user_token()) if user_token() else ''}\")\n", + "assert backend_name() == \"polaris\", \"this notebook tests the Polaris backend (POLARIS_URI must be set)\"\n", + "assert user_token(), \"no Keycloak token in the kernel: reload JupyterLab, then restart the kernel\"" + ] + }, + { + "cell_type": "markdown", + "id": "cell-02", + "metadata": {}, + "source": [ + "## Help\n", + "\n", + "`help` prints each magic's command table without connecting to anything." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-03", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog help" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-04", + "metadata": {}, + "outputs": [], + "source": [ + "%ingest help" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-05", + "metadata": {}, + "outputs": [], + "source": [ + "%dds help" + ] + }, + { + "cell_type": "markdown", + "id": "cell-06", + "metadata": {}, + "source": [ + "## Scratch space\n", + "\n", + "`TEST_FOLDER` is the one folder this notebook writes to; **Cleanup** deletes it with everything inside.\n", + "If it is left over from an earlier run, the next cell says so: run **Cleanup** first." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-07", + "metadata": {}, + "outputs": [], + "source": [ + "from eea_datalakehouse.catalog.polaris import PolarisCatalog\n", + "\n", + "ROOT = SETTINGS.catalog\n", + "TEST_FOLDER = f\"{ROOT}.non_domain_datasets.eea_datalakehouse_magics_test\"\n", + "SOURCE_TABLE = f\"{ROOT}.biodiversity_ecosystems.protected_areas.dfl_natura2000.draft.sites.aaaa\"\n", + "AREA = f\"{TEST_FOLDER}.dfl_test\"\n", + "\n", + "verify = PolarisCatalog(SETTINGS) # independent client: the magics never touch it\n", + "print(\"TEST_FOLDER \", TEST_FOLDER, \"(exists already: run Cleanup first)\" if verify.exists(TEST_FOLDER) else \"\")\n", + "print(\"SOURCE_TABLE \", SOURCE_TABLE, \"exists:\", verify.exists(SOURCE_TABLE))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-08", + "metadata": {}, + "source": [ + "## 1. `%catalog`: a call runs immediately\n", + "\n", + "No `%catalog commit` anywhere. On Polaris a folder is a namespace." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-09", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog create_folder(TEST_FOLDER, create_parents=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-10", + "metadata": {}, + "outputs": [], + "source": [ + "print(\"folder exists:\", verify.exists(TEST_FOLDER), \"| is a namespace:\", verify.is_folder(TEST_FOLDER))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-11", + "metadata": {}, + "source": [ + "## 2. Context and relative paths\n", + "\n", + "`use` sets the context; a bare name (or `.name`) is relative to it. Absolute paths start with the catalog's name." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-12", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog use(TEST_FOLDER)\n", + "%catalog get_context()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-13", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog create_folder(\"nested\") # -> TEST_FOLDER + \".nested\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-14", + "metadata": {}, + "outputs": [], + "source": [ + "print(\"nested exists:\", verify.exists(f\"{TEST_FOLDER}.nested\"))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-15", + "metadata": {}, + "source": [ + "## 3. Wiki and tags\n", + "\n", + "The wiki is the namespace's `wiki` property; tags are lower case, without `#`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-16", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog set_wiki(\".\", \"# eea_datalakehouse magics test\\n\\nCreated by the magics test notebook.\", tags=[{\"tag_name\": \"owner\", \"tag_value\": \"magics-test\", \"tag_title\": \"Owner\"}])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-17", + "metadata": {}, + "outputs": [], + "source": [ + "print(verify.getwikifrom(TEST_FOLDER, idempotency_key=\"magics-test-read-wiki\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-18", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog set_tags(\".\", [\"#Smoke\", \"test\"])\n", + "%catalog get_tags(\".\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-19", + "metadata": {}, + "source": [ + "## 4. What a failed call looks like\n", + "\n", + "`TEST_FOLDER` holds `nested`, so deleting it without `cascade=True` fails with a short message, not a traceback." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-20", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog delete_folder(TEST_FOLDER) # expected to fail: the folder is not empty" + ] + }, + { + "cell_type": "markdown", + "id": "cell-21", + "metadata": {}, + "source": [ + "## 5. Data: copy, schema, views, move\n", + "\n", + "`data_copy` runs `CREATE TABLE … AS SELECT` in this kernel's DuckDB and writes an Iceberg table through Polaris." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-22", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog data_copy(SOURCE_TABLE, \"nested.copy\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-23", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog schema(\"nested.copy\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-24", + "metadata": {}, + "outputs": [], + "source": [ + "print(\"copy is a:\", verify.entry_kind(f\"{TEST_FOLDER}.nested.copy\", idempotency_key=\"magics-test\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-25", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog create_view(\"nested.copy\", \"nested.copy_view\")\n", + "%catalog schema(\"nested.copy_view\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-26", + "metadata": {}, + "outputs": [], + "source": [ + "print(verify.view_sql(f\"{TEST_FOLDER}.nested.copy_view\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-27", + "metadata": {}, + "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", + "%catalog list()" + ] + }, + { + "cell_type": "markdown", + "id": "cell-28", + "metadata": {}, + "source": [ + "## 6. A dataflow release: draft → version → latest views" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-29", + "metadata": {}, + "outputs": [], + "source": [ + "%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)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-30", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog draft_to_version(\"v2026_1\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-31", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog update_latest_release(\"v2026_1\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-32", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog list()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-33", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog get_tags(\"stations\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-34", + "metadata": {}, + "outputs": [], + "source": [ + "print(\"latest view reads the version:\", verify.view_sql(f\"{AREA}.stations\"))" + ] + }, + { + "cell_type": "markdown", + "id": "cell-35", + "metadata": {}, + "source": [ + "## 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 Iceberg table\n", + "and **removes the staging folder**; `\"parquet\"` keeps Parquet files as they are, as a read-only table, and\n", + "`promote` turns that into Iceberg later. Small local files are generated first." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-36", + "metadata": {}, + "outputs": [], + "source": [ + "import tempfile\n", + "from pathlib import Path\n", + "\n", + "import pyarrow as pa\n", + "import pyarrow.parquet as pq\n", + "\n", + "INGEST_DIR = Path(tempfile.mkdtemp(prefix=\"magics_test_\"))\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)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-37", + "metadata": {}, + "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", + "%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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-38", + "metadata": {}, + "outputs": [], + "source": [ + "report = %ingest commit\n", + "for outcome in report.outcomes:\n", + " print(outcome)\n", + " for note in outcome.notes:\n", + " print(\" note:\", note)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-39", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog schema(\"draft.temps\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-40", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog schema(\"draft.samples\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-41", + "metadata": {}, + "source": [ + "Nothing staged should be left behind: no `_ingestion/` objects under the test folder's storage location." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-42", + "metadata": {}, + "outputs": [], + "source": [ + "from eea_datalakehouse.catalog.object_store import ObjectStore, s3_credentials\n", + "\n", + "SCRATCH_LOCATION = verify.rest.namespace_properties(verify.parts(TEST_FOLDER)).get(\"location\")\n", + "store = ObjectStore(SETTINGS, s3_credentials(SETTINGS))\n", + "staged = [f.url for f in store.list(SCRATCH_LOCATION) if \"/_ingestion/\" in f.url]\n", + "print(\"storage location:\", SCRATCH_LOCATION)\n", + "print(\"staged files left:\", len(staged))\n", + "for url in staged[:10]:\n", + " print(\" \", url)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-43", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog schema(\"reference.temps_ro\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-44", + "metadata": {}, + "outputs": [], + "source": [ + "%ingest promote(f\"{AREA}.reference.temps_ro\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-45", + "metadata": {}, + "outputs": [], + "source": [ + "%catalog schema(\"reference.temps_ro\")" + ] + }, + { + "cell_type": "markdown", + "id": "cell-46", + "metadata": {}, + "source": [ + "## 8. `%dds`: the context's document folders\n", + "\n", + "`%dds` signs in with your Keycloak token and stores under the namespace's path. The folder (`DELIVERABLES`,\n", + "`METADATA`, …) is typed bare on the line." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-47", + "metadata": {}, + "outputs": [], + "source": [ + "(INGEST_DIR / \"readme.txt\").write_text(\"eea_datalakehouse magics test\")\n", + "%dds target(DELIVERABLES)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-48", + "metadata": {}, + "outputs": [], + "source": [ + "%dds push(DELIVERABLES, str(INGEST_DIR / \"readme.txt\"), overwrite=True)\n", + "%dds list(DELIVERABLES)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-49", + "metadata": {}, + "outputs": [], + "source": [ + "f = %dds get(DELIVERABLES, \"readme.txt\", output_dir=str(INGEST_DIR / \"back\"))\n", + "print(f, \"->\", Path(f).read_text())" + ] + }, + { + "cell_type": "markdown", + "id": "cell-50", + "metadata": {}, + "source": [ + "## 9. `%gpkg`: GeoPackage export\n", + "\n", + "No Flight gateway in this stack, so `%gpkg` reads the rows through this kernel's DuckDB, signed in as\n", + "`%catalog` is. Spatial tables become feature layers, the rest attribute tables." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-51", + "metadata": {}, + "outputs": [], + "source": [ + "gpkg = %gpkg export(limit=100, filename=\"magics_test.gpkg\", output_dir=str(INGEST_DIR))\n", + "gpkg" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-52", + "metadata": {}, + "outputs": [], + "source": [ + "%dds push(DELIVERABLES, gpkg, overwrite=True)\n", + "%dds list(DELIVERABLES)" + ] + }, + { + "cell_type": "markdown", + "id": "cell-53", + "metadata": {}, + "source": [ + "## Cleanup\n", + "\n", + "`delete_folder(cascade=True)` removes `TEST_FOLDER` with every table, view and folder inside; the cell after\n", + "it removes any data files left in the folder's own storage location, nothing else. The documents pushed to\n", + "DDS stay in the Document Service (delete them from its panel if you want)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-54", + "metadata": {}, + "outputs": [], + "source": [ + "SCRATCH_LOCATION = verify.rest.namespace_properties(verify.parts(TEST_FOLDER)).get(\"location\") if verify.exists(TEST_FOLDER) else None\n", + "%catalog use(None)\n", + "%catalog delete_folder(TEST_FOLDER, cascade=True)\n", + "print(\"folder exists after cleanup:\", verify.exists(TEST_FOLDER))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cell-55", + "metadata": {}, + "outputs": [], + "source": [ + "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()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyproject.toml b/pyproject.toml index 404ee22..e33d1b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,7 +68,7 @@ strict = true warn_return_any = false [[tool.mypy.overrides]] -module = ["respx.*", "pyarrow.*", "shapely.*", "lxml.*"] # none ships type stubs +module = ["respx.*", "pyarrow.*", "shapely.*", "lxml.*", "pandas.*"] # none ships type stubs ignore_missing_imports = true [tool.pytest.ini_options] diff --git a/src/eea_datalakehouse/catalog/backend.py b/src/eea_datalakehouse/catalog/backend.py index 1c48054..bd09e14 100644 --- a/src/eea_datalakehouse/catalog/backend.py +++ b/src/eea_datalakehouse/catalog/backend.py @@ -43,6 +43,12 @@ def root(self) -> str: def close(self) -> None: ... + def search(self, query: str, *, kind: str | None, limit: int) -> list[dict[str, Any]]: + """Ranked hits for `query` across the catalog's names, tags, descriptions, columns + and wiki pages, as far as the caller may read them: ``{"path": full path, "kind", + "display_name", "description", "tags", "matched", "snippet", "restricted"}``.""" + ... + # -- what is where -------------------------------------------------------- def exists(self, path: str) -> bool: diff --git a/src/eea_datalakehouse/catalog/client.py b/src/eea_datalakehouse/catalog/client.py index 095ae39..f705d4b 100644 --- a/src/eea_datalakehouse/catalog/client.py +++ b/src/eea_datalakehouse/catalog/client.py @@ -39,6 +39,7 @@ from . import dremio_publish, foldertree, operations, retry_state from .backend import Partitions, PublishOutcome +from .errors import CatalogOperationError from .foldertree import FolderTransferReport, FolderTree, ProgressCallback from .operations import CatalogEntry, TableInfo, VersionResult, ViewDefinition from .rest import CatalogRestClient @@ -260,6 +261,15 @@ def __enter__(self) -> Catalog: def __exit__(self, *exc_info: object) -> None: self.close() + def search( + self, query: str, *, kind: str | None = None, limit: int = 50 + ) -> list[dict[str, Any]]: + """Not on Dremio: catalog search is the Polaris stack's (the Document Service's index).""" + raise CatalogOperationError( + "search is available on the Polaris catalog only (the Document Service's index); " + "on Dremio, use the Dremio catalog panel's search" + ) + def close(self) -> None: """Dispose the underlying Flight/REST session(s). Idempotent.""" if self._closed: diff --git a/src/eea_datalakehouse/catalog/dds_search.py b/src/eea_datalakehouse/catalog/dds_search.py new file mode 100644 index 0000000..6dc8c41 --- /dev/null +++ b/src/eea_datalakehouse/catalog/dds_search.py @@ -0,0 +1,90 @@ +"""`CatalogSearchClient` — the Document Service's catalog search, for `search` on Polaris. + +DDS (``/api/v1/catalog-search``, EEA Lakehouse ``Components/DremioDocumentService``) keeps +one index of the Polaris catalog's metadata: names, tags, display names, descriptions, +columns and wiki pages. It answers with the signed-in user's Keycloak token +(``X-Keycloak-Token``) and only with what their grants let them read:: + + GET /api/v1/catalog-search?q=…&kind=…&limit=… — ranked hits + +A hit's ``path`` is the list of its parts below the catalog (``["water", "bathing", +"sites"]``); ``match`` says where it matched when not by its name (``tag``, ``column``, or +a ``wiki`` sentence); ``restricted`` marks a namespace the user may see exists but not open. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import httpx + +from .dds_public import _message +from .errors import CatalogAuthError, CatalogOperationError +from .settings import user_token + +DEFAULT_TIMEOUT = 60.0 + + +class CatalogSearchClient: + """`search` 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, + verify: str | bool = True, + ) -> None: + if not base_url: + raise CatalogOperationError( + "search 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, verify=verify) + + def __repr__(self) -> str: + return f"CatalogSearchClient(base_url={self._base_url!r})" + + def close(self) -> None: + if self._owns_http: + self._http.close() + + def search( + self, query: str, *, kind: str | None = None, limit: int = 50 + ) -> list[dict[str, Any]]: + """The hits for `query`, best first (see the module docstring for their shape).""" + token = self._token_provider() + if not token: + raise CatalogAuthError( + "search needs your own sign-in (KEYCLOAK_ACCESS_TOKEN is not set)" + ) + params: dict[str, str | int] = {"q": query, "limit": limit} + if kind: + params["kind"] = kind + try: + response = self._http.get( + f"{self._base_url}/api/v1/catalog-search", + params=params, + headers={"X-Keycloak-Token": token}, + ) + 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 == 401: + raise CatalogAuthError(f"the Document Service refused the search: {_message(response)}") + if response.status_code == 503: + raise CatalogOperationError( + f"catalog search is not available on the Document Service: {_message(response)}" + ) + if response.status_code >= 400: + raise CatalogOperationError( + f"the search failed (HTTP {response.status_code}): {_message(response)}" + ) + hits = response.json().get("hits") + return hits if isinstance(hits, list) else [] diff --git a/src/eea_datalakehouse/catalog/polaris.py b/src/eea_datalakehouse/catalog/polaris.py index ecc49e8..28a8279 100644 --- a/src/eea_datalakehouse/catalog/polaris.py +++ b/src/eea_datalakehouse/catalog/polaris.py @@ -22,9 +22,11 @@ from . import operations from .backend import Partitions, PublishOutcome from .dds_public import PublicDataClient +from .dds_search import CatalogSearchClient from .duckdb_engine import DuckDbEngine, quote_identifier, quote_literal from .errors import CatalogAuthError, CatalogOperationError from .layout import NOT_PUBLISHED, PUBLIC_TAG +from .object_store import ObjectStore, s3_credentials from .operations import TableInfo, VersionResult from .polaris_rest import PARQUET_FORMAT, PolarisHttpError, PolarisRestClient from .settings import PolarisSettings, tls_verify @@ -211,11 +213,15 @@ def __init__( rest: PolarisRestClient | None = None, engine: DuckDbEngine | None = None, public: PublicDataClient | None = None, + searcher: CatalogSearchClient | None = None, + store: ObjectStore | None = None, ) -> None: self._settings = settings self.rest = rest or PolarisRestClient(settings) self.engine = engine or DuckDbEngine(settings) self._public = public + self._searcher = searcher + self._store = store # made on first use: only dropping a table needs it def __repr__(self) -> str: return f"PolarisCatalog(uri={self._settings.uri!r}, catalog={self.root!r})" @@ -233,6 +239,34 @@ def close(self) -> None: self.rest.close() if self._public is not None: self._public.close() + if self._searcher is not None: + self._searcher.close() + + # -- search ----------------------------------------------------------------- + # Through the Document Service's catalog index, which holds every namespace's and + # table's names, tags, descriptions, columns and wiki pages, and answers as the user. + + def search( + self, query: str, *, kind: str | None = None, limit: int = 50 + ) -> list[dict[str, Any]]: + if self._searcher is None: + self._searcher = CatalogSearchClient( + self._settings.dds_base_url, verify=tls_verify(self._settings.ca_file) + ) + out = [] + for hit in self._searcher.search(query, kind=kind, limit=limit): + match = hit.get("match") or {} + out.append({ + "path": ".".join([self.root, *hit.get("path", [])]), + "kind": hit.get("kind"), + "display_name": hit.get("display_name") or "", + "description": hit.get("comment") or "", + "tags": list(hit.get("tags") or []), + "matched": match.get("field") or "", + "snippet": match.get("snippet") or "", + "restricted": bool(hit.get("restricted")), + }) + return out # -- paths ---------------------------------------------------------------- @@ -461,9 +495,12 @@ def createfolder( def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str) -> None: """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.""" + Without `cascade` it must be empty. With it, everything inside is purged, + deepest first: every view, table and read-only Parquet table (each with its + folder of files), registered database and sub-namespace, and then each + namespace's own folder in the object store with whatever else is in it (plain + files, leftovers). A folder is only deleted when it lies inside its parent + namespace's folder — a top-level namespace's never is, nor anything outside.""" parts = self.parts(path) if not parts: raise CatalogOperationError(f"{path!r} is the catalog itself and can't be deleted") @@ -479,11 +516,17 @@ def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str ) from exc raise return + # Every namespace's folder, read before anything goes (a child's guard is its + # parent's folder, and the parent is dropped after it). + locations: dict[tuple[str, ...], str] = {} + if len(parts) > 1: + locations[tuple(parts[:-1])] = self._namespace_location(parts[:-1]) order: list[list[str]] = [] pending = [parts] while pending: namespace = pending.pop() order.append(namespace) + locations[tuple(namespace)] = self._namespace_location(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): @@ -491,8 +534,16 @@ def deletefolder(self, path: str, *, cascade: bool = False, idempotency_key: str for name in self.rest.list_tables(namespace): self._drop_table(namespace, name) for name in self.rest.list_generic(namespace): - self.rest.drop_generic(namespace, name) + self._drop_generic(namespace, name) self.rest.drop_namespace(namespace) + self._remove_folder( + locations[tuple(namespace)], + locations.get(tuple(namespace[:-1]), ""), + what=self.path_of(namespace), + ) + + def _namespace_location(self, namespace: Sequence[str]) -> str: + return str(self.rest.namespace_properties(list(namespace)).get("location") or "") # -- wiki ------------------------------------------------------------------------ @@ -658,26 +709,67 @@ def iceberg_select_from(self, source: str) -> str: 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).""" + """Drop `name` in `namespace`, which is a `kind`, purged: a table or a read-only + Parquet table with its folder of files, or a view.""" if kind == "table": self._drop_table(namespace, name) elif kind == "view": self.rest.drop_view(namespace, name) else: - self.rest.drop_generic(namespace, name) + self._drop_generic(namespace, name) + + def _drop_generic(self, namespace: list[str], name: str) -> None: + """Drop a generic table: a read-only Parquet table goes with its folder of + files (see `_purge`); a registered database has none.""" + entry = self.rest.load_generic(namespace, name) + self.rest.drop_generic(namespace, name) + if entry.get("format") == PARQUET_FORMAT: + self._purge(namespace, name, str(entry.get("base-location") or "")) 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.""" + """Drop an Iceberg table from the catalog, then delete its folder (data and + metadata files) from the object store. + + Polaris is asked to purge the files too, but that is only a cleanup task it runs + later, and a caller it doesn't let purge (``DROP_TABLE_WITH_PURGE`` — e.g. a + principal with catalog_admin only) gets a plain drop that leaves them all. So + the folder is removed here either way, with the caller's own object-store keys — + only when it lies inside the namespace's own folder, so a table registered on + some shared location never takes other files with it.""" + location = str(self.rest.load_table(namespace, name).get("location") or "") 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) + self._purge(namespace, name, location) + + def _purge(self, namespace: list[str], name: str, location: str) -> None: + """Delete the folder `location` of the dropped `name` from the object store, + when it lies strictly inside `namespace`'s own folder.""" + base = str(self.rest.namespace_properties(namespace).get("location") or "") + self._remove_folder(location, base, what=self.path_of([*namespace, name])) + + def _remove_folder(self, folder: str, parent: str, *, what: str) -> None: + """Delete `folder` with everything in it, but only when it is strictly inside + `parent` (so never a bucket, the catalog's root or someone else's location); + `what` (just dropped from the catalog) names it in the error.""" + folder, parent = folder.rstrip("/"), parent.rstrip("/") + if not folder or not parent or not folder.startswith(f"{parent}/"): + return + try: + self._object_store().remove_folder(f"{folder}/") + except (CatalogAuthError, CatalogOperationError) as exc: + raise CatalogOperationError( + f"{what!r} was dropped from the catalog, but its files in {folder}/ could " + f"not be deleted: {exc}" + ) from exc + + def _object_store(self) -> ObjectStore: + if self._store is None: + self._store = ObjectStore(self._settings, s3_credentials(self._settings)) + return self._store def _prepare_target( self, diff --git a/src/eea_datalakehouse/catalog/session.py b/src/eea_datalakehouse/catalog/session.py index af8ace3..e5f3996 100644 --- a/src/eea_datalakehouse/catalog/session.py +++ b/src/eea_datalakehouse/catalog/session.py @@ -37,6 +37,8 @@ from dataclasses import dataclass, field from typing import Any +import pandas as pd + from . import operations from .backend import CatalogBackend from .dremio_publish import PUBLIC_ROOT @@ -1355,6 +1357,24 @@ def list(self, path: str = "") -> CatalogListing: self._catalog.list_dataset_kinds(path) ) + def search(self, query: str, *, kind: str | None = None, limit: int = 50) -> pd.DataFrame: + """Find tables, views, folders, databases and Parquet tables by their names, tags, + display names, descriptions, columns and wiki pages: one row per hit, best first, + as far as you may read them. Answered immediately — not queued. + + `query`: words (each matching by prefix, all of them somewhere), ``"exact phrase"``, + ``#tag`` (exactly that tag), ``in:path`` (under that path), ``kind:table`` (view, + namespace, database, parquet) and ``col:name`` (a column). `kind` and `limit` + narrow it further. Columns: ``path`` (full, to pass on to other calls), ``kind``, + ``display_name``, ``description``, ``tags``, ``matched`` (``tag``, ``column`` or + ``wiki`` when not by its name) with its ``snippet``, and ``restricted`` (a folder + you may see exists but not open). Polaris only.""" + hits = self._catalog.search(query, kind=kind, limit=limit) + return pd.DataFrame(hits, columns=[ + "path", "kind", "display_name", "description", "tags", "matched", "snippet", + "restricted", + ]) + def schema(self, path: str) -> TableInfo: """The column schema and row count of `path` (see `gettableitemsfrom`) — never fetches the actual rows. Answered diff --git a/src/eea_datalakehouse/notebook/magics.py b/src/eea_datalakehouse/notebook/magics.py index 2ded8b7..5383a3e 100644 --- a/src/eea_datalakehouse/notebook/magics.py +++ b/src/eea_datalakehouse/notebook/magics.py @@ -279,6 +279,14 @@ "CatalogSessionError if none is set. Raises CatalogOperationError if path " "doesn't exist.", ), + ( + "search", + "Find tables, views, folders, databases and Parquet tables by name, tags, display " + "name, description, columns and wiki: a DataFrame, best first, with what matched. " + 'query: words (by prefix, all must match), "exact phrase", #tag, in:path, ' + "kind:table|view|namespace|database|parquet, col:name; kind= and limit= (50) too. " + "Only what you may read. Polaris only (the Document Service's index, DDS_BASE_URL).", + ), ( "schema", "Show path's column schema and row count (never fetches the actual rows). path " diff --git a/tests/catalog/test_polaris_data.py b/tests/catalog/test_polaris_data.py index e88df4a..e4cd149 100644 --- a/tests/catalog/test_polaris_data.py +++ b/tests/catalog/test_polaris_data.py @@ -414,6 +414,134 @@ def test_a_refused_purge_drops_the_table_without_it() -> None: assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "latest") +class FakeStore: + """Records the folders removed; `fail` makes removing one raise.""" + + def __init__(self, fail: str | None = None) -> None: + self.removed: list[str] = [] + self.fail = fail + + def remove_folder(self, folder_url: str, *, up_to: str | None = None) -> None: + if self.fail: + raise CatalogOperationError(self.fail) + self.removed.append(folder_url) + + +DRAFT_LOCATION = "s3://lakehouse/catalog/water/bathing/bwd/draft" + + +def _located(store: FakeStore, table_location: str) -> tuple[PolarisCatalog, FakePolarisRest]: + rest = _bwd() + rest.namespaces[("water", "bathing", "bwd", "draft")]["location"] = DRAFT_LOCATION + rest.tables[(("water", "bathing", "bwd", "draft"), "stations")].metadata["location"] = ( + table_location + ) + engine = CatalogEngine(rest) + catalog = PolarisCatalog( + SETTINGS, rest=cast(PolarisRestClient, rest), engine=engine, store=cast(Any, store) + ) + return catalog, rest + + +@pytest.mark.parametrize("refuse_purge", [False, True]) +def test_a_dropped_table_takes_its_folder_with_it(refuse_purge: bool) -> None: + """Purged or not by Polaris, the table's own folder goes from the object store.""" + store = FakeStore() + catalog, rest = _located(store, f"{DRAFT_LOCATION}/stations") + rest.refuse_purge = refuse_purge + + catalog.deletetable(f"{AREA}.draft.stations", idempotency_key=K) + + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + assert store.removed == [f"{DRAFT_LOCATION}/stations/"] + + +@pytest.mark.parametrize( + "location", + [DRAFT_LOCATION, "s3://lakehouse/catalog/water/bathing/elsewhere/stations", ""], +) +def test_files_outside_the_namespace_folder_are_left_alone(location: str) -> None: + """A table on its namespace's folder itself, somewhere else, or with no location.""" + store = FakeStore() + catalog, rest = _located(store, location) + + catalog.deletetable(f"{AREA}.draft.stations", idempotency_key=K) + + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + assert store.removed == [] + + +def test_a_dropped_parquet_table_takes_its_folder_with_it() -> None: + store = FakeStore() + catalog, rest = _located(store, f"{DRAFT_LOCATION}/stations") + rest.add_parquet("water.bathing.bwd.draft.raw", location=f"{DRAFT_LOCATION}/raw/") + + catalog.deletetable(f"{AREA}.draft.raw", idempotency_key=K) + + assert (("water", "bathing", "bwd", "draft"), "raw") not in rest.generic + assert store.removed == [f"{DRAFT_LOCATION}/raw/"] + + +def test_a_cascade_purges_every_folder_inside() -> None: + """Tables, Parquet tables and each namespace's own folder (plain files included), + deepest first; never the folder above the one deleted.""" + base = "s3://lakehouse/catalog/water/bathing/bwd" + rest = ( + FakePolarisRest() + .add_namespace("water", "bathing", "bwd", location=base) + .add_namespace("water", "bathing", "bwd", "draft", location=f"{base}/draft") + .add_namespace("water", "bathing", "bwd", "draft", "sub", location=f"{base}/draft/sub") + .add_table("water.bathing.bwd.draft.stations", {"location": f"{base}/draft/stations"}) + .add_table("water.bathing.bwd.draft.sub.t", {"location": f"{base}/draft/sub/t"}) + .add_parquet("water.bathing.bwd.draft.raw", location=f"{base}/draft/raw/") + .add_view("water.bathing.bwd.draft.latest") + ) + store = FakeStore() + catalog = PolarisCatalog( + SETTINGS, + rest=cast(PolarisRestClient, rest), + engine=CatalogEngine(rest), + store=cast(Any, store), + ) + + catalog.deletefolder(f"{AREA}.draft", cascade=True, idempotency_key=K) + + assert not rest.namespace_exists(["water", "bathing", "bwd", "draft"]) + assert rest.namespace_exists(["water", "bathing", "bwd"]) + assert store.removed == [ + f"{base}/draft/sub/t/", + f"{base}/draft/sub/", + f"{base}/draft/stations/", + f"{base}/draft/raw/", + f"{base}/draft/", + ] + + +def test_a_cascade_never_removes_a_top_level_folder() -> None: + rest = FakePolarisRest().add_namespace("water", location="s3://lakehouse/catalog/water") + store = FakeStore() + catalog = PolarisCatalog( + SETTINGS, + rest=cast(PolarisRestClient, rest), + engine=CatalogEngine(rest), + store=cast(Any, store), + ) + + catalog.deletefolder("eea_lakehouse.water", cascade=True, idempotency_key=K) + + assert not rest.namespace_exists(["water"]) + assert store.removed == [] + + +def test_files_that_cannot_be_deleted_are_reported() -> None: + store = FakeStore(fail="access denied") + catalog, rest = _located(store, f"{DRAFT_LOCATION}/stations") + + with pytest.raises(CatalogOperationError, match="dropped from the catalog, but its files"): + catalog.deletetable(f"{AREA}.draft.stations", idempotency_key=K) + assert not rest.table_exists(["water", "bathing", "bwd", "draft"], "stations") + + def test_other_refusals_are_not_retried_without_purge() -> None: catalog, rest, _ = _setup() rest.undroppable.add("stations") diff --git a/tests/catalog/test_search.py b/tests/catalog/test_search.py new file mode 100644 index 0000000..f845b04 --- /dev/null +++ b/tests/catalog/test_search.py @@ -0,0 +1,83 @@ +"""`search`: the Document Service's catalog index, through PolarisCatalog and CatalogSession.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, cast + +import httpx +import pytest +import respx + +from eea_datalakehouse.catalog.client import Catalog +from eea_datalakehouse.catalog.dds_search import CatalogSearchClient +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 CatalogSession +from eea_datalakehouse.catalog.settings import PolarisSettings + +from .polaris_fakes import FakePolarisRest + +DDS = "http://dds.test" +SETTINGS = PolarisSettings(uri="http://polaris.test/api/catalog", catalog="eea_lakehouse", + dds_base_url=DDS) +HITS: list[dict[str, Any]] = [ + {"path": ["water", "bathing", "sites"], "ns": ["water", "bathing"], "name": "sites", + "kind": "table", "display_name": "", "comment": "Bathing sites", "tags": ["public"], + "match": {"field": "column", "snippet": "country_code"}}, + {"path": ["secret"], "ns": ["secret"], "name": None, "kind": "namespace", "restricted": True}, +] + + +def _catalog(token: str | None = "user-jwt") -> PolarisCatalog: + searcher = CatalogSearchClient(DDS, token_provider=lambda: token) + engine = cast(DuckDbEngine, SimpleNamespace(close=lambda: None)) + return PolarisCatalog(SETTINGS, rest=cast(PolarisRestClient, FakePolarisRest()), + engine=engine, searcher=searcher) + + +@respx.mock +def test_search_asks_dds_as_the_user_and_returns_full_paths() -> None: + route = respx.get(f"{DDS}/api/v1/catalog-search").mock( + return_value=httpx.Response(200, json={"hits": HITS, "truncated": False})) + hits = _catalog().search("country", kind="table", limit=5) + request = route.calls.last.request + assert request.headers["X-Keycloak-Token"] == "user-jwt" + assert dict(request.url.params) == {"q": "country", "limit": "5", "kind": "table"} + assert hits[0] == {"path": "eea_lakehouse.water.bathing.sites", "kind": "table", + "display_name": "", "description": "Bathing sites", "tags": ["public"], + "matched": "column", "snippet": "country_code", "restricted": False} + assert hits[1]["path"] == "eea_lakehouse.secret" + assert hits[1]["restricted"] is True + + +@respx.mock +def test_search_errors_are_said_plainly() -> None: + respx.get(f"{DDS}/api/v1/catalog-search").mock( + return_value=httpx.Response(503, json={"message": "catalog search is not configured"})) + with pytest.raises(CatalogOperationError, match="not configured"): + _catalog().search("x") + respx.get(f"{DDS}/api/v1/catalog-search").mock( + return_value=httpx.Response(401, json={"message": "expired"})) + with pytest.raises(CatalogAuthError, match="expired"): + _catalog().search("x") + with pytest.raises(CatalogAuthError, match="sign-in"): + _catalog(token=None).search("x") + + +@respx.mock +def test_session_search_is_a_dataframe() -> None: + respx.get(f"{DDS}/api/v1/catalog-search").mock( + return_value=httpx.Response(200, json={"hits": HITS, "truncated": False})) + frame = CatalogSession(_catalog()).search("country") + assert list(frame.columns) == ["path", "kind", "display_name", "description", "tags", + "matched", "snippet", "restricted"] + assert frame["path"].tolist() == ["eea_lakehouse.water.bathing.sites", "eea_lakehouse.secret"] + + +def test_search_on_dremio_says_it_is_polaris_only() -> None: + catalog = Catalog.__new__(Catalog) # no connection needed to refuse + with pytest.raises(CatalogOperationError, match="Polaris catalog only"): + catalog.search("x")