From 0151f67d82ccd2bea987b7b288b1e7becbf1c800 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:59:59 -0800 Subject: [PATCH 01/10] fix(databases): refuse Delta table folders with data and no log --- changelog.d/ITL-916.md | 5 + docs/dev/design_issues/ITL-916-DR2.md | 15 +++ src/orcapod/databases/delta_lake_databases.py | 120 ++++++++++++------ .../test_delta_read_failures.py | 89 +++++++++++++ .../test_delta_table_database_s3.py | 34 +++++ 5 files changed, 223 insertions(+), 40 deletions(-) create mode 100644 changelog.d/ITL-916.md create mode 100644 docs/dev/design_issues/ITL-916-DR2.md diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md new file mode 100644 index 000000000..3309b4125 --- /dev/null +++ b/changelog.d/ITL-916.md @@ -0,0 +1,5 @@ +### Fixed + +- Delta database reads and writes now raise `OrcapodDatabaseReadError` if a + table folder contains Parquet data files but its transaction log is missing. + The error names the table, and a flush leaves the existing files intact. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md new file mode 100644 index 000000000..9fb8a3cb5 --- /dev/null +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -0,0 +1,15 @@ +## `src/orcapod/databases/delta_lake_databases.py` — read failures + +### DR2 — A missing Delta log hid stored rows and allowed a new table at the same path +**Status:** resolved +**Severity:** critical +**Issue:** ITL-916 + +Removing `_delta_log` from a table with stored rows made reads report an absent +table. A later flush could create a new log that did not reference the original +Parquet files, silently leaving their rows out of the table. + +**Fix:** On a Delta table miss, check the table folder for Parquet files using +the local filesystem or the Delta storage backend. When files exist, briefly +retry opening the log to give a concurrent first writer time to publish it, +then raise `OrcapodDatabaseReadError` if the log still cannot be opened. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..10bf6b2fa 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -5,13 +5,13 @@ import random import re import sys -import time import uuid from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from dataclasses import dataclass from pathlib import Path +from time import sleep from typing import TYPE_CHECKING, Any, Literal, cast import polars as pl @@ -86,6 +86,9 @@ # Directory that marks its parent directory as a Delta table. _DELTA_LOG_DIRECTORY = "_delta_log" +# A first writer can put its Parquet files in place before publishing version zero. +_MISSING_LOG_RETRY_DELAYS = (0.02, 0.08, 0.2, 0.5) + # How many times a flush tries to commit a table's pending rows when other writers # keep committing first; after the last attempt it raises the last conflict # (ITL-1377). A writer that lost waits until the others pause: measured with 4 @@ -115,7 +118,7 @@ def _sleep_before_retry(attempt: int) -> None: not keep colliding. The wait only spaces attempts: what is committed is decided against the table each attempt loads. """ - time.sleep(random.uniform(0, min(0.5, 0.005 * 2**attempt))) + sleep(random.uniform(0, min(0.5, 0.005 * 2**attempt))) # deltalake storage option -> where s3fs takes the same setting. @@ -1920,30 +1923,81 @@ def _get_delta_table( deltalake.DeltaTable instance or None if table doesn't exist """ record_key = self._get_record_key(record_path) - table_uri = self._get_table_uri(record_path) - # Check cache first if dt := self._delta_table_cache.get(record_key): return dt if record_key in self._absent_tables: return None - try: - # Try to load existing table - delta_table = deltalake.DeltaTable( - table_uri, storage_options=self._storage_options or None - ) - self._delta_table_cache[record_key] = delta_table - logger.debug(f"Loaded existing Delta table for {record_key}") - return delta_table - except deltalake.exceptions.TableNotFoundError: + delta_table = self._load_delta_table( + self._get_table_uri(record_path), self._path_prefix + record_path + ) + if delta_table is None: # Table doesn't exist: remembered until the next flush (ITL-1173). self._absent_tables.add(record_key) - return None - except Exception as e: - # The table exists but could not be loaded: never report it as absent. - self._delta_table_cache.pop(record_key, None) - raise self._read_failed(record_path) from e + else: + self._delta_table_cache[record_key] = delta_table + logger.debug(f"Loaded existing Delta table for {record_key}") + return delta_table + + def _load_delta_table( + self, table_uri: str, record_path: tuple[str, ...] + ) -> deltalake.DeltaTable | None: + """Open the current Delta log, checking a missing log for existing data. + + Args: + table_uri: The table's storage location. + record_path: Full path including the database view's prefix. + + Returns: + The loaded table, or ``None`` when neither a log nor data files exist. + + Raises: + OrcapodDatabaseReadError: If the log cannot be opened or the location + cannot be checked for data files. + """ + from deltalake.exceptions import TableNotFoundError + + options = self._storage_options or None + try: + try: + return deltalake.DeltaTable(table_uri, storage_options=options) + except TableNotFoundError as missing_log: + if not self._has_delta_data_files(table_uri): + return None + for delay in _MISSING_LOG_RETRY_DELAYS: + sleep(delay) + try: + return deltalake.DeltaTable(table_uri, storage_options=options) + except TableNotFoundError: + continue + raise FileNotFoundError( + f"Found Parquet data files without a readable {_DELTA_LOG_DIRECTORY}" + ) from missing_log + except Exception as load_error: + raise OrcapodDatabaseReadError(table_uri, record_path) from load_error + + def _has_delta_data_files(self, table_uri: str) -> bool: + """Check for Parquet files in the table folder without visiting child tables.""" + if not self._is_cloud: + try: + with os.scandir(table_uri) as entries: + return any( + entry.name.endswith(".parquet") and entry.is_file() + for entry in entries + ) + except FileNotFoundError: + return False + + from deltalake.fs import DeltaStorageHandler + from pyarrow.fs import FileSelector, FileType + + handler = DeltaStorageHandler(table_uri, self._storage_options or None) + entries = handler.get_file_info_selector(FileSelector("", allow_not_found=True)) + return any( + entry.type == FileType.File and entry.path.endswith(".parquet") + for entry in entries + ) def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError: """Build the error for a table at ``record_path`` that exists but cannot be read. @@ -2099,17 +2153,14 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the latest Delta schema from the log or the table's first batch.""" - from deltalake.exceptions import TableNotFoundError - - try: - table = deltalake.DeltaTable( - self._get_table_uri(record_path), - storage_options=self._storage_options or None, - ) - return pa.schema(_held_columns(table).values()) - except TableNotFoundError: + table = self._load_delta_table( + self._get_table_uri(record_path), self._path_prefix + record_path + ) + if table is None: pending = self._pending_batches.get(self._get_record_key(record_path)) return None if pending is None else pending.schema + try: + return pa.schema(_held_columns(table).values()) except Exception as exc: raise self._read_failed(record_path) from exc @@ -3789,23 +3840,12 @@ def _commit_once( InputValidationError: If the stored table refuses the rows. StoredTableSchemaError: If the table does not satisfy the queued schema guard. """ - from deltalake.exceptions import CommitFailedError, TableNotFoundError + from deltalake.exceptions import CommitFailedError # A column whose type Delta would not give back is written in its integer # form with its type recorded (ITL-928). combined_table = to_delta_layout(original_table) - # Only TableNotFoundError means "absent": a table that exists but cannot be - # loaded is never created over (ITL-884). - try: - delta_table = deltalake.DeltaTable( - table_uri, storage_options=self._storage_options or None - ) - except TableNotFoundError: - delta_table = None - except Exception as load_error: - raise OrcapodDatabaseReadError( - table_uri, abs_path_components - ) from load_error + delta_table = self._load_delta_table(table_uri, abs_path_components) check = self._pending_commits.schema_check(record_key) if check is not None: diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 4af6e7292..e977b2de9 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -20,6 +20,7 @@ import dataclasses import datetime import json +import shutil from collections.abc import Callable from pathlib import Path from typing import Any @@ -30,6 +31,7 @@ from deltalake.exceptions import DeltaProtocolError from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -148,6 +150,93 @@ def assert_names_table(exc: OrcapodDatabaseReadError, base: Path) -> None: } +@pytest.fixture +def missing_log( + base: Path, stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch +) -> DeltaTableDatabase: + """Open a fresh handle after removing the log from a table with stored rows.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + directory = table_dir(base) + assert any(directory.glob("*.parquet")) + shutil.rmtree(directory / "_delta_log") + return DeltaTableDatabase(base_path=base) + + +@pytest.mark.parametrize( + "read", + [ + *READS.values(), + lambda db: db.get_table_schema(PATH), + lambda db: db.table_exists(PATH), + ], + ids=[*READS, "get_table_schema", "table_exists"], +) +def test_missing_log_is_a_read_error( + base: Path, + missing_log: DeltaTableDatabase, + read: Callable[[DeltaTableDatabase], object], +) -> None: + """Every read refuses to treat a folder with orphaned data as absent.""" + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + read(missing_log) + assert_names_table(info.value, base) + + +def test_flush_refuses_a_missing_log( + base: Path, missing_log: DeltaTableDatabase +) -> None: + """Flushing to a folder with orphaned data writes no files or log.""" + directory = table_dir(base) + before = {path.name: path.read_bytes() for path in directory.iterdir()} + missing_log.add_records( + PATH, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" + ) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + missing_log.flush() + + assert_names_table(info.value, base) + assert {path.name: path.read_bytes() for path in directory.iterdir()} == before + + +def test_flush_can_load_a_log_published_during_the_retry( + base: Path, stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch +) -> None: + """A concurrent first commit can publish its log after its data is visible.""" + log = table_dir(base) / "_delta_log" + unpublished = base / "unpublished" + db = DeltaTableDatabase(base_path=base) + db.add_records( + PATH, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" + ) + log.rename(unpublished) + monkeypatch.setattr( + delta_lake_databases, "sleep", lambda _delay: unpublished.rename(log) + ) + + db.flush() + + result = db.get_all_records(PATH) + assert result is not None + assert result.sort_by("x").column("x").to_pylist() == [1, 2, 3] + + +def test_empty_table_folder_can_be_created(base: Path) -> None: + """An empty folder still accepts its first commit.""" + table_dir(base).mkdir(parents=True) + db = DeltaTableDatabase(base_path=base) + assert db.get_all_records(PATH) is None + db.add_records( + PATH, + rows([b"a"], pa.array([1], pa.int64())), + record_id_column="rid", + flush=True, + ) + result = db.get_all_records(PATH) + assert result is not None + assert result.column("x").to_pylist() == [1] + + class TestUnreadableTable: """A table that exists but cannot be read raises on every read path.""" diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index 1bf7e16ce..efdd991eb 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -15,9 +15,12 @@ import pyarrow as pa import pytest +import s3fs from upath import UPath from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases +from orcapod.errors import OrcapodDatabaseReadError pytestmark = pytest.mark.s3 @@ -58,6 +61,37 @@ def test_s3_flush_and_read(s3_base_uri, s3_storage_options): assert result.num_rows == 3 +def test_s3_table_with_missing_log_is_refused( + s3_base_uri: str, + s3_storage_options: dict[str, str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A cloud read or flush refuses a missing log and preserves the data objects.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + path = ("table",) + uri = f"{s3_base_uri}/table" + db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + db.add_record(path, b"a", pa.table({"v": [1]}), flush=True) + + fs = s3fs.S3FileSystem( + key=s3_storage_options["AWS_ACCESS_KEY_ID"], + secret=s3_storage_options["AWS_SECRET_ACCESS_KEY"], + client_kwargs={"endpoint_url": s3_storage_options["AWS_ENDPOINT_URL"]}, + use_listings_cache=False, + ) + fs.rm(f"{uri}/_delta_log", recursive=True) + before = fs.find(uri) + assert len(before) == 1 and before[0].endswith(".parquet") + + recovered = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + recovered.get_all_records(path) + assert info.value.table == uri + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): + recovered.add_record(path, b"b", pa.table({"v": [2]}), flush=True) + assert fs.find(uri) == before + + def test_s3_skip_duplicates(s3_base_uri, s3_storage_options): db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) record = pa.table({"v": [1]}) From 294af5b40a44b3755db184f47b43680b8f6898c5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:01:21 -0800 Subject: [PATCH 02/10] refactor(databases): attach missing log context at load sites --- src/orcapod/databases/delta_lake_databases.py | 63 +++++++++---------- 1 file changed, 30 insertions(+), 33 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 10bf6b2fa..3d52b28ab 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1929,9 +1929,10 @@ def _get_delta_table( if record_key in self._absent_tables: return None - delta_table = self._load_delta_table( - self._get_table_uri(record_path), self._path_prefix + record_path - ) + try: + delta_table = self._load_delta_table(self._get_table_uri(record_path)) + except Exception as load_error: + raise self._read_failed(record_path) from load_error if delta_table is None: # Table doesn't exist: remembered until the next flush (ITL-1173). self._absent_tables.add(record_key) @@ -1940,42 +1941,35 @@ def _get_delta_table( logger.debug(f"Loaded existing Delta table for {record_key}") return delta_table - def _load_delta_table( - self, table_uri: str, record_path: tuple[str, ...] - ) -> deltalake.DeltaTable | None: + def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: """Open the current Delta log, checking a missing log for existing data. Args: table_uri: The table's storage location. - record_path: Full path including the database view's prefix. Returns: The loaded table, or ``None`` when neither a log nor data files exist. Raises: - OrcapodDatabaseReadError: If the log cannot be opened or the location - cannot be checked for data files. + FileNotFoundError: If the folder holds data files and the log is missing. """ from deltalake.exceptions import TableNotFoundError options = self._storage_options or None try: - try: - return deltalake.DeltaTable(table_uri, storage_options=options) - except TableNotFoundError as missing_log: - if not self._has_delta_data_files(table_uri): - return None - for delay in _MISSING_LOG_RETRY_DELAYS: - sleep(delay) - try: - return deltalake.DeltaTable(table_uri, storage_options=options) - except TableNotFoundError: - continue - raise FileNotFoundError( - f"Found Parquet data files without a readable {_DELTA_LOG_DIRECTORY}" - ) from missing_log - except Exception as load_error: - raise OrcapodDatabaseReadError(table_uri, record_path) from load_error + return deltalake.DeltaTable(table_uri, storage_options=options) + except TableNotFoundError as missing_log: + if not self._has_delta_data_files(table_uri): + return None + for delay in _MISSING_LOG_RETRY_DELAYS: + sleep(delay) + try: + return deltalake.DeltaTable(table_uri, storage_options=options) + except TableNotFoundError: + continue + raise FileNotFoundError( + f"Found Parquet data files without a readable {_DELTA_LOG_DIRECTORY}" + ) from missing_log def _has_delta_data_files(self, table_uri: str) -> bool: """Check for Parquet files in the table folder without visiting child tables.""" @@ -2153,16 +2147,14 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the latest Delta schema from the log or the table's first batch.""" - table = self._load_delta_table( - self._get_table_uri(record_path), self._path_prefix + record_path - ) - if table is None: - pending = self._pending_batches.get(self._get_record_key(record_path)) - return None if pending is None else pending.schema try: - return pa.schema(_held_columns(table).values()) + table = self._load_delta_table(self._get_table_uri(record_path)) + if table is not None: + return pa.schema(_held_columns(table).values()) except Exception as exc: raise self._read_failed(record_path) from exc + pending = self._pending_batches.get(self._get_record_key(record_path)) + return None if pending is None else pending.schema def _ensure_record_id_column( self, arrow_data: pa.Table, record_id: str | bytes @@ -3845,7 +3837,12 @@ def _commit_once( # A column whose type Delta would not give back is written in its integer # form with its type recorded (ITL-928). combined_table = to_delta_layout(original_table) - delta_table = self._load_delta_table(table_uri, abs_path_components) + try: + delta_table = self._load_delta_table(table_uri) + except Exception as load_error: + raise OrcapodDatabaseReadError( + table_uri, abs_path_components + ) from load_error check = self._pending_commits.schema_check(record_key) if check is not None: From 0dad2b73cced9c9bb8d687f3f94a9ac5686a9cf4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:34:46 -0800 Subject: [PATCH 03/10] fix(databases): guard partitioned Delta tables and discovery --- changelog.d/ITL-916.md | 7 +- docs/dev/design_issues/ITL-916-DR2.md | 10 +- src/orcapod/databases/delta_lake_databases.py | 171 ++++++++++++------ .../test_delta_read_failures.py | 126 ++++++++++--- .../test_delta_table_database_s3.py | 58 ++++-- 5 files changed, 270 insertions(+), 102 deletions(-) diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md index 3309b4125..9c03abcfe 100644 --- a/changelog.d/ITL-916.md +++ b/changelog.d/ITL-916.md @@ -1,5 +1,6 @@ ### Fixed -- Delta database reads and writes now raise `OrcapodDatabaseReadError` if a - table folder contains Parquet data files but its transaction log is missing. - The error names the table, and a flush leaves the existing files intact. +- Delta database reads, table discovery, existence checks, and writes now raise + `OrcapodDatabaseReadError` when a table has Parquet files and its transaction + log is missing. This covers both flat and partitioned tables. The error names + the table, and a flush leaves the existing files intact. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index 9fb8a3cb5..82a8ccf50 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -9,7 +9,9 @@ Removing `_delta_log` from a table with stored rows made reads report an absent table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. -**Fix:** On a Delta table miss, check the table folder for Parquet files using -the local filesystem or the Delta storage backend. When files exist, briefly -retry opening the log to give a concurrent first writer time to publish it, -then raise `OrcapodDatabaseReadError` if the log still cannot be opened. +**Fix:** On a Delta table miss, use the local filesystem or the Delta storage +backend to find Parquet files at the table root and in Hive-style partitions. +When files exist, briefly retry opening the log to give a concurrent first +writer time to publish it, then raise `OrcapodDatabaseReadError` if the log +still cannot be opened. Discovery checks for missing logs and existence checks +open the current log even if the handle already holds a row snapshot. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 3d52b28ab..c1650e078 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -157,14 +157,26 @@ def _s3fs_options(storage_options: Mapping[str, str]) -> dict[str, Any]: return options -def _list_local_directory(directory: str) -> list[str]: - """Return the names of the subdirectories of a local directory. +def _is_delta_partition_directory(name: str) -> bool: + """Recognize Delta's Hive-style ``column=value`` directory names.""" + return name.find("=") > 0 + + +def _list_local_directory(directory: str) -> tuple[list[str], bool]: + """Return subdirectory names and whether the directory contains Parquet files. A symbolic link to a directory is not a subdirectory here: following one that points at an ancestor would send the table walk in circles. """ + children: list[str] = [] + has_parquet = False with os.scandir(directory) as entries: - return [entry.name for entry in entries if entry.is_dir(follow_symlinks=False)] + for entry in entries: + if entry.is_dir(follow_symlinks=False): + children.append(entry.name) + elif entry.name.endswith(".parquet") and entry.is_file(): + has_parquet = True + return children, has_parquet def _join_local_path(directory: str, name: str) -> str: @@ -1911,23 +1923,26 @@ def _validate_record_path(self, record_path: tuple[str, ...]) -> None: ) def _get_delta_table( - self, record_path: tuple[str, ...] + self, record_path: tuple[str, ...], *, check_current: bool = False ) -> deltalake.DeltaTable | None: """ Get an existing Delta table, either from cache or by loading it. Args: record_path: Tuple of path components + check_current: Open the current log even when a row snapshot is cached. Returns: deltalake.DeltaTable instance or None if table doesn't exist """ record_key = self._get_record_key(record_path) - # Check cache first - if dt := self._delta_table_cache.get(record_key): - return dt - if record_key in self._absent_tables: - return None + if check_current: + self._absent_tables.discard(record_key) + else: + if dt := self._delta_table_cache.get(record_key): + return dt + if record_key in self._absent_tables: + return None try: delta_table = self._load_delta_table(self._get_table_uri(record_path)) @@ -1937,7 +1952,7 @@ def _get_delta_table( # Table doesn't exist: remembered until the next flush (ITL-1173). self._absent_tables.add(record_key) else: - self._delta_table_cache[record_key] = delta_table + self._delta_table_cache.setdefault(record_key, delta_table) logger.debug(f"Loaded existing Delta table for {record_key}") return delta_table @@ -1972,26 +1987,51 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: ) from missing_log def _has_delta_data_files(self, table_uri: str) -> bool: - """Check for Parquet files in the table folder without visiting child tables.""" + """Check for Parquet files at the table root or in its Hive partitions.""" if not self._is_cloud: - try: - with os.scandir(table_uri) as entries: - return any( - entry.name.endswith(".parquet") and entry.is_file() - for entry in entries - ) - except FileNotFoundError: - return False + pending = [table_uri] + while pending: + directory = pending.pop() + try: + children, has_parquet = _list_local_directory(directory) + except FileNotFoundError: + continue + if directory != table_uri and _DELTA_LOG_DIRECTORY in children: + continue # A child table owns its own data files. + if has_parquet: + return True + pending.extend( + _join_local_path(directory, name) + for name in children + if _is_delta_partition_directory(name) + ) + return False from deltalake.fs import DeltaStorageHandler from pyarrow.fs import FileSelector, FileType handler = DeltaStorageHandler(table_uri, self._storage_options or None) - entries = handler.get_file_info_selector(FileSelector("", allow_not_found=True)) - return any( - entry.type == FileType.File and entry.path.endswith(".parquet") - for entry in entries + entries = handler.get_file_info_selector( + FileSelector("", recursive=True, allow_not_found=True) ) + paths = [(entry.path.split("/"), entry.type) for entry in entries] + # The log files also mark the boundary when the object store only lists files. + child_tables = { + tuple(parts[:index]) + for parts, _ in paths + for index, name in enumerate(parts) + if index > 0 and name == _DELTA_LOG_DIRECTORY + } + for parts, kind in paths: + if kind != FileType.File or not parts[-1].endswith(".parquet"): + continue + if all( + _is_delta_partition_directory(name) + and tuple(parts[:depth]) not in child_tables + for depth, name in enumerate(parts[:-1], start=1) + ): + return True + return False def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError: """Build the error for a table at ``record_path`` that exists but cannot be read. @@ -2013,8 +2053,10 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] Walks the directories below ``prefix``: a directory that holds a ``_delta_log`` directory is a table. The walk goes on below a table, because tables can be nested (Orcapod v0.3 stores a table one level below where - v0.2 stored it), and never enters ``_delta_log``. No table is opened. Only - flushed tables are listed, as with ``table_exists``. + v0.2 stored it), and never enters ``_delta_log``. Parquet files at a table + root or in its partitions without a log directory trigger a log-open + retry, then an error if the log remains missing. Only flushed tables are + listed, as with ``table_exists``. A local database is listed exactly. A cloud database is listed through ``fsspec`` with one list request per directory: ``s3://`` and ``s3a://`` through @@ -2032,7 +2074,8 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] Raises: TableListingNotSupportedError: If the database is on cloud storage and could not be listed; the reason is chained. - OrcapodDatabaseReadError: If a local directory could not be listed. + OrcapodDatabaseReadError: If a local directory could not be listed or + data files have no readable transaction log. """ full_prefix = self._path_prefix + prefix if self._is_cloud: @@ -2051,13 +2094,17 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] join = _join_local_path component = _stored_component - found: list[tuple[str, ...]] = [] - # Directories still to visit, each with its path below ``prefix``. - to_visit: list[tuple[str, tuple[str, ...]]] = [(start, ())] + found: set[tuple[str, ...]] = set() + suspected: set[tuple[str, ...]] = set() + owner = prefix + while owner and _is_delta_partition_directory(owner[-1]): + owner = owner[:-1] + # Each directory carries its path and the table path owning its data. + to_visit = [(start, prefix, owner)] while to_visit: - directory, below = to_visit.pop() + directory, path, owner = to_visit.pop() try: - children = list_directory(directory) + children, has_parquet = list_directory(directory) except FileNotFoundError: continue except Exception as exc: @@ -2066,20 +2113,31 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] f"Could not list the tables of the Delta database at " f"{self._root_uri!r}: {type(exc).__name__}: {exc}" ) from exc - raise OrcapodDatabaseReadError(directory, full_prefix + below) from exc + raise OrcapodDatabaseReadError( + directory, self._path_prefix + path + ) from exc + if _DELTA_LOG_DIRECTORY in children: + found.add(path) + owner = path + elif has_parquet: + suspected.add(owner) for name in children: - if name == _DELTA_LOG_DIRECTORY: - found.append(prefix + below) - else: - to_visit.append((join(directory, name), below + (component(name),))) + if name != _DELTA_LOG_DIRECTORY: + child = path + (component(name),) + child_owner = ( + owner if _is_delta_partition_directory(name) else child + ) + to_visit.append((join(directory, name), child, child_owner)) + for path in sorted(suspected - found): + if self.table_exists(path) and len(path) >= len(prefix): + found.add(path) return sorted(found) - def _cloud_directory_lister(self) -> "Callable[[str], list[str]]": + def _cloud_directory_lister(self) -> "Callable[[str], tuple[list[str], bool]]": """Return a function listing the subdirectories of a cloud directory. Returns: - A function from a directory (bucket and key, no scheme) to the names of - its subdirectories. + A function returning subdirectory names and whether there are Parquet files. Raises: TableListingNotSupportedError: If no ``fsspec`` file system is available @@ -2118,21 +2176,26 @@ def _cloud_directory_lister(self) -> "Callable[[str], list[str]]": f"({type(exc).__name__}: {exc})." ) from exc - def list_directory(directory: str) -> list[str]: - """Return the names of the subdirectories of a cloud directory.""" + def list_directory(directory: str) -> tuple[list[str], bool]: + """Return cloud subdirectory names and whether there are Parquet files.""" entries = file_system.ls(directory, detail=True) - return [ + children = [ str(entry["name"]).rstrip("/").rsplit("/", 1)[-1] for entry in entries if entry["type"] == "directory" ] + return children, any( + entry["type"] == "file" and str(entry["name"]).endswith(".parquet") + for entry in entries + ) return list_directory def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a Delta table exists at ``record_path``. - This is a cheap existence check that does NOT load any records. + Check the current log without loading records or replacing a cached + row snapshot. Args: record_path: Path components identifying the table, relative to @@ -2140,10 +2203,12 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: Returns: ``True`` if a table exists at the given path, ``False`` otherwise. + + Raises: + OrcapodDatabaseReadError: If the current log cannot be opened for a + table with data files. """ - # Checks again even when the table was found absent before (ITL-1173). - self._absent_tables.discard(self._get_record_key(record_path)) - return self._get_delta_table(record_path) is not None + return self._get_delta_table(record_path, check_current=True) is not None def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the latest Delta schema from the log or the table's first batch.""" @@ -4341,6 +4406,7 @@ def list_sources(self) -> list[tuple[str, ...]]: Raises: NotImplementedError: For cloud base paths (filesystem walk not supported). + OrcapodDatabaseReadError: If a table has data files but no readable log. """ if self._is_cloud: raise NotImplementedError( @@ -4366,12 +4432,15 @@ def _scan(current_path: Path, path_components: tuple[str, ...]) -> None: continue components = path_components + (item.name,) try: - deltalake.DeltaTable( - str(item), storage_options=self._storage_options or None - ) - sources.append(components) - except deltalake.exceptions.TableNotFoundError: + table = self._load_delta_table(str(item)) + except Exception as exc: + raise OrcapodDatabaseReadError( + str(item), self._path_prefix + components + ) from exc + if table is None: _scan(item, components) + else: + sources.append(components) # Build the effective scoped root directory scoped_root = self._local_root diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index e977b2de9..f0d50b8c5 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -150,53 +150,121 @@ def assert_names_table(exc: OrcapodDatabaseReadError, base: Path) -> None: } -@pytest.fixture -def missing_log( - base: Path, stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch -) -> DeltaTableDatabase: - """Open a fresh handle after removing the log from a table with stored rows.""" +@pytest.fixture(params=[("table",), PATH], ids=["top-level", "nested"]) +def damaged_path(request: pytest.FixtureRequest) -> tuple[str, ...]: + """Return the record path of the table whose log will be removed.""" + return request.param + + +@pytest.fixture( + params=[None, ["tag1", "tag2"], ["tag2", "tag1"]], + ids=["flat", "partitioned", "reordered-partitions"], +) +def damaged_stores( + base: Path, + damaged_path: tuple[str, ...], + request: pytest.FixtureRequest, + monkeypatch: pytest.MonkeyPatch, +) -> tuple[DeltaTableDatabase, DeltaTableDatabase]: + """Return fresh and warm handles after dropping the log from a populated table.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) - directory = table_dir(base) - assert any(directory.glob("*.parquet")) + directory = base.joinpath(*damaged_path) + data = pa.table( + { + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag1": ["a"], + "tag2": ["b"], + "x": [1], + "y": [2], + } + ) + partitions = request.param + if partitions == ["tag2", "tag1"]: + data = data.select( + ["y", "tag2", DeltaTableDatabase.RECORD_ID_COLUMN, "x", "tag1"] + ) + deltalake.write_deltalake(directory, data, partition_by=partitions) + warm = DeltaTableDatabase(base_path=base) + assert warm.get_all_records(damaged_path) is not None + assert any(directory.rglob("*.parquet")) shutil.rmtree(directory / "_delta_log") - return DeltaTableDatabase(base_path=base) + return DeltaTableDatabase(base_path=base), warm + + +MISSING_LOG_READS: dict[ + str, Callable[[DeltaTableDatabase, tuple[str, ...]], object] +] = { + "get_all_records": lambda db, path: db.get_all_records(path), + "get_records_by_ids": lambda db, path: db.get_records_by_ids(path, [b"a", b"b"]), + "get_record_by_id": lambda db, path: db.get_record_by_id(path, b"a"), + "get_records_with_column_value": lambda db, path: db.get_records_with_column_value( + path, {"y": 2, "x": 1} + ), + "get_table_schema": lambda db, path: db.get_table_schema(path), + "table_exists": lambda db, path: db.table_exists(path), + "list_sources": lambda db, _path: db.list_sources(), + "list_table_paths": lambda db, _path: db.list_table_paths(), + "list_table_paths_with_prefix": lambda db, path: db.list_table_paths(path), +} @pytest.mark.parametrize( - "read", - [ - *READS.values(), - lambda db: db.get_table_schema(PATH), - lambda db: db.table_exists(PATH), - ], - ids=[*READS, "get_table_schema", "table_exists"], + "read", MISSING_LOG_READS.values(), ids=list(MISSING_LOG_READS) ) def test_missing_log_is_a_read_error( - base: Path, - missing_log: DeltaTableDatabase, - read: Callable[[DeltaTableDatabase], object], + damaged_path: tuple[str, ...], + damaged_stores: tuple[DeltaTableDatabase, DeltaTableDatabase], + read: Callable[[DeltaTableDatabase, tuple[str, ...]], object], ) -> None: - """Every read refuses to treat a folder with orphaned data as absent.""" + """Row reads and metadata discovery name the table with orphaned data.""" + fresh, _ = damaged_stores with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - read(missing_log) - assert_names_table(info.value, base) + read(fresh, damaged_path) + assert info.value.record_path == damaged_path + + +def test_table_exists_refuses_a_missing_log_on_a_warm_handle( + damaged_path: tuple[str, ...], + damaged_stores: tuple[DeltaTableDatabase, DeltaTableDatabase], +) -> None: + """An existence check sees the missing log while row reads keep their snapshot.""" + _, warm = damaged_stores + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + warm.table_exists(damaged_path) + assert info.value.record_path == damaged_path + assert warm.get_all_records(damaged_path) is not None def test_flush_refuses_a_missing_log( - base: Path, missing_log: DeltaTableDatabase + base: Path, + damaged_path: tuple[str, ...], + damaged_stores: tuple[DeltaTableDatabase, DeltaTableDatabase], ) -> None: """Flushing to a folder with orphaned data writes no files or log.""" - directory = table_dir(base) - before = {path.name: path.read_bytes() for path in directory.iterdir()} - missing_log.add_records( - PATH, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" + fresh, _ = damaged_stores + directory = base.joinpath(*damaged_path) + before = snapshot(directory) + fresh.add_records( + damaged_path, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" ) with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - missing_log.flush() + fresh.flush() - assert_names_table(info.value, base) - assert {path.name: path.read_bytes() for path in directory.iterdir()} == before + assert info.value.record_path == damaged_path + assert snapshot(directory) == before + + +@pytest.mark.parametrize("name", ["table", "tag=child"]) +def test_partition_paths_do_not_count_as_separate_tables(base: Path, name: str) -> None: + """A healthy table owns its partitions, even when listing starts in one.""" + path = ("group", name) + data = pa.table({"tag1": ["a"], "tag2": ["b"], "x": [1], "y": [2]}) + deltalake.write_deltalake(base.joinpath(*path), data, partition_by=["tag1", "tag2"]) + db = DeltaTableDatabase(base_path=base) + assert not db.table_exists(("group",)) + assert db.list_table_paths() == [path] + assert db.list_table_paths((*path, "tag1=a")) == [] def test_flush_can_load_a_log_published_during_the_retry( diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index efdd991eb..b56ce8300 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -13,6 +13,7 @@ Run with: uv run pytest tests/test_databases/test_delta_table_database_s3.py -v """ +import deltalake import pyarrow as pa import pytest import s3fs @@ -61,17 +62,36 @@ def test_s3_flush_and_read(s3_base_uri, s3_storage_options): assert result.num_rows == 3 +@pytest.mark.parametrize( + "path", [("table",), ("group", "table")], ids=["top-level", "nested"] +) +@pytest.mark.parametrize( + "partitions", [None, ["tag1", "tag2"]], ids=["flat", "partitioned"] +) def test_s3_table_with_missing_log_is_refused( s3_base_uri: str, s3_storage_options: dict[str, str], monkeypatch: pytest.MonkeyPatch, + path: tuple[str, ...], + partitions: list[str] | None, ) -> None: - """A cloud read or flush refuses a missing log and preserves the data objects.""" + """Cloud reads, metadata and flushes refuse a missing log and preserve the objects.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) - path = ("table",) - uri = f"{s3_base_uri}/table" - db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) - db.add_record(path, b"a", pa.table({"v": [1]}), flush=True) + uri = "/".join((s3_base_uri,) + path) + data = pa.table( + { + "y": [2], + "tag1": ["a"], + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag2": ["b"], + "x": [1], + } + ) + deltalake.write_deltalake( + uri, data, partition_by=partitions, storage_options=s3_storage_options + ) + warm = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + assert warm.get_all_records(path) is not None fs = s3fs.S3FileSystem( key=s3_storage_options["AWS_ACCESS_KEY_ID"], @@ -80,16 +100,24 @@ def test_s3_table_with_missing_log_is_refused( use_listings_cache=False, ) fs.rm(f"{uri}/_delta_log", recursive=True) - before = fs.find(uri) - assert len(before) == 1 and before[0].endswith(".parquet") - - recovered = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - recovered.get_all_records(path) - assert info.value.table == uri - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): - recovered.add_record(path, b"b", pa.table({"v": [2]}), flush=True) - assert fs.find(uri) == before + before = {name: fs.cat_file(name) for name in fs.find(uri)} + assert len(before) == 1 and next(iter(before)).endswith(".parquet") + + fresh = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + for operation in ( + lambda: fresh.get_all_records(path), + lambda: fresh.get_table_schema(path), + lambda: fresh.table_exists(path), + lambda: warm.table_exists(path), + lambda: fresh.list_table_paths(), + lambda: fresh.list_table_paths(path), + lambda: fresh.add_record(path, b"b", pa.table({"v": [2]}), flush=True), + ): + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + _ = operation() + assert info.value.table == uri + assert info.value.record_path == path + assert {name: fs.cat_file(name) for name in fs.find(uri)} == before def test_s3_skip_duplicates(s3_base_uri, s3_storage_options): From e821128114143c34345a64bd5378705e52a0f1b5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:57:36 -0800 Subject: [PATCH 04/10] fix(delta): refuse orphaned data beyond Hive partitions --- changelog.d/ITL-916.md | 5 +- docs/dev/design_issues/ITL-916-DR2.md | 12 +- src/orcapod/databases/delta_lake_databases.py | 293 ++++++++++++------ .../test_delta_absent_tables.py | 29 +- .../test_delta_read_failures.py | 110 +++++++ .../test_delta_table_database_s3.py | 49 +++ 6 files changed, 384 insertions(+), 114 deletions(-) diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md index 9c03abcfe..1b0b01e3c 100644 --- a/changelog.d/ITL-916.md +++ b/changelog.d/ITL-916.md @@ -2,5 +2,6 @@ - Delta database reads, table discovery, existence checks, and writes now raise `OrcapodDatabaseReadError` when a table has Parquet files and its transaction - log is missing. This covers both flat and partitioned tables. The error names - the table, and a flush leaves the existing files intact. + log is missing or unpublished. This covers flat, partitioned, and arbitrary + nested data paths. The error names the table, and a flush leaves the existing + files intact. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index 82a8ccf50..42454e15c 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -10,8 +10,10 @@ table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. **Fix:** On a Delta table miss, use the local filesystem or the Delta storage -backend to find Parquet files at the table root and in Hive-style partitions. -When files exist, briefly retry opening the log to give a concurrent first -writer time to publish it, then raise `OrcapodDatabaseReadError` if the log -still cannot be opened. Discovery checks for missing logs and existence checks -open the current log even if the handle already holds a row snapshot. +backend to look for Parquet files at any depth, outside transaction logs and +separately published child tables. When files exist, briefly retry opening the +log to give a concurrent first writer time to publish it, then raise +`OrcapodDatabaseReadError` if the log still cannot be opened. Discovery checks +data ownership and identifies logs that are missing or still unpublished. +Existence checks open the current log even if the handle already holds a row +snapshot. Cached misses recheck for data files so they also surface orphaned rows. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c1650e078..b43b81f19 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -85,6 +85,7 @@ # Directory that marks its parent directory as a Delta table. _DELTA_LOG_DIRECTORY = "_delta_log" +_DELTA_LOG_MARKERS = ("00000000000000000000.json", "_last_checkpoint") # A first writer can put its Parquet files in place before publishing version zero. _MISSING_LOG_RETRY_DELAYS = (0.02, 0.08, 0.2, 0.5) @@ -162,21 +163,21 @@ def _is_delta_partition_directory(name: str) -> bool: return name.find("=") > 0 -def _list_local_directory(directory: str) -> tuple[list[str], bool]: - """Return subdirectory names and whether the directory contains Parquet files. +def _list_local_directory(directory: str) -> tuple[list[str], list[str]]: + """Return the names of the subdirectories and Parquet files. A symbolic link to a directory is not a subdirectory here: following one that points at an ancestor would send the table walk in circles. """ children: list[str] = [] - has_parquet = False + parquet_files: list[str] = [] with os.scandir(directory) as entries: for entry in entries: if entry.is_dir(follow_symlinks=False): children.append(entry.name) elif entry.name.endswith(".parquet") and entry.is_file(): - has_parquet = True - return children, has_parquet + parquet_files.append(entry.name) + return children, parquet_files def _join_local_path(directory: str, name: str) -> str: @@ -1828,9 +1829,9 @@ def __init__( on_empty=self._discard_pending_index, ) ) - # Record keys whose table was found absent (ITL-1173), so lookups do not try - # to open it again on every row. Family-wide like the loaded tables, and - # forgotten on any flush of the family and on a flush of the key: a table + # Record keys whose table was found absent (ITL-1173), so lookups can defer + # opening it again until there is evidence of data. Family-wide like the + # loaded tables, and forgotten on any flush of the family or the key: a table # another process creates is seen after this database's next flush, as rows # it appends to a loaded table are. ``table_exists`` always checks again. self._absent_tables: set[str] = ( @@ -1941,11 +1942,16 @@ def _get_delta_table( else: if dt := self._delta_table_cache.get(record_key): return dt - if record_key in self._absent_tables: - return None + table_uri = self._get_table_uri(record_path) try: - delta_table = self._load_delta_table(self._get_table_uri(record_path)) + if record_key in self._absent_tables: + # Keep healthy external commits invisible until the next flush, + # but refuse newly visible data whose log never became readable. + if self._has_delta_data_files(table_uri): + self._load_delta_table(table_uri, data_present=True) + return None + delta_table = self._load_delta_table(table_uri) except Exception as load_error: raise self._read_failed(record_path) from load_error if delta_table is None: @@ -1956,11 +1962,14 @@ def _get_delta_table( logger.debug(f"Loaded existing Delta table for {record_key}") return delta_table - def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: + def _load_delta_table( + self, table_uri: str, *, data_present: bool | None = None + ) -> deltalake.DeltaTable | None: """Open the current Delta log, checking a missing log for existing data. Args: table_uri: The table's storage location. + data_present: Evidence from an existing filesystem walk, if available. Returns: The loaded table, or ``None`` when neither a log nor data files exist. @@ -1974,7 +1983,9 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: try: return deltalake.DeltaTable(table_uri, storage_options=options) except TableNotFoundError as missing_log: - if not self._has_delta_data_files(table_uri): + if data_present is None: + data_present = self._has_delta_data_files(table_uri) + if not data_present: return None for delay in _MISSING_LOG_RETRY_DELAYS: sleep(delay) @@ -1987,23 +1998,32 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: ) from missing_log def _has_delta_data_files(self, table_uri: str) -> bool: - """Check for Parquet files at the table root or in its Hive partitions.""" + """Find Parquet files at any depth outside logs and published child tables.""" if not self._is_cloud: pending = [table_uri] while pending: directory = pending.pop() try: - children, has_parquet = _list_local_directory(directory) + children, parquet_files = _list_local_directory(directory) except FileNotFoundError: continue - if directory != table_uri and _DELTA_LOG_DIRECTORY in children: - continue # A child table owns its own data files. - if has_parquet: + if ( + directory != table_uri + and _DELTA_LOG_DIRECTORY in children + and any( + os.path.isfile( + os.path.join(directory, _DELTA_LOG_DIRECTORY, name) + ) + for name in _DELTA_LOG_MARKERS + ) + ): + continue + if parquet_files: return True pending.extend( _join_local_path(directory, name) for name in children - if _is_delta_partition_directory(name) + if name != _DELTA_LOG_DIRECTORY ) return False @@ -2015,20 +2035,20 @@ def _has_delta_data_files(self, table_uri: str) -> bool: FileSelector("", recursive=True, allow_not_found=True) ) paths = [(entry.path.split("/"), entry.type) for entry in entries] - # The log files also mark the boundary when the object store only lists files. + # A committed child log marks a separate table even when the store lists files only. child_tables = { - tuple(parts[:index]) - for parts, _ in paths - for index, name in enumerate(parts) - if index > 0 and name == _DELTA_LOG_DIRECTORY + tuple(parts[:-2]) + for parts, kind in paths + if kind == FileType.File + and len(parts) > 2 + and parts[-2] == _DELTA_LOG_DIRECTORY + and parts[-1] in _DELTA_LOG_MARKERS } for parts, kind in paths: if kind != FileType.File or not parts[-1].endswith(".parquet"): continue - if all( - _is_delta_partition_directory(name) - and tuple(parts[:depth]) not in child_tables - for depth, name in enumerate(parts[:-1], start=1) + if _DELTA_LOG_DIRECTORY not in parts[:-1] and not any( + tuple(parts[:depth]) in child_tables for depth in range(1, len(parts)) ): return True return False @@ -2053,10 +2073,8 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] Walks the directories below ``prefix``: a directory that holds a ``_delta_log`` directory is a table. The walk goes on below a table, because tables can be nested (Orcapod v0.3 stores a table one level below where - v0.2 stored it), and never enters ``_delta_log``. Parquet files at a table - root or in its partitions without a log directory trigger a log-open - retry, then an error if the log remains missing. Only flushed tables are - listed, as with ``table_exists``. + v0.2 stored it), and never enters ``_delta_log``. Parquet files that no + readable Delta log accounts for trigger a bounded log-open retry. A local database is listed exactly. A cloud database is listed through ``fsspec`` with one list request per directory: ``s3://`` and ``s3a://`` through @@ -2077,15 +2095,23 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] OrcapodDatabaseReadError: If a local directory could not be listed or data files have no readable transaction log. """ + return self._discover_tables(prefix) + + def _discover_tables( + self, prefix: tuple[str, ...], *, sources_only: bool = False + ) -> list[tuple[str, ...]]: + """Walk data directories once and check any evidence of an unpublished log.""" full_prefix = self._path_prefix + prefix + root = self._root if self._root is not None else self if self._is_cloud: - list_directory = self._cloud_directory_lister() + list_directory, is_file = self._cloud_directory_lister() start = self._root_uri.split("://", 1)[1].rstrip("/") start = "/".join((start,) + full_prefix) join = _join_cloud_path component = str else: list_directory = _list_local_directory + is_file = os.path.isfile start = str( self._local_root.joinpath( *(self._sanitize_path_component(part) for part in full_prefix) @@ -2094,17 +2120,13 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] join = _join_local_path component = _stored_component - found: set[tuple[str, ...]] = set() - suspected: set[tuple[str, ...]] = set() - owner = prefix - while owner and _is_delta_partition_directory(owner[-1]): - owner = owner[:-1] - # Each directory carries its path and the table path owning its data. - to_visit = [(start, prefix, owner)] + found: dict[tuple[str, ...], str] = {} + data: dict[tuple[str, ...], list[str]] = {} + to_visit = [(start, full_prefix)] while to_visit: - directory, path, owner = to_visit.pop() + directory, path = to_visit.pop() try: - children, has_parquet = list_directory(directory) + children, parquet_files = list_directory(directory) except FileNotFoundError: continue except Exception as exc: @@ -2113,31 +2135,127 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] f"Could not list the tables of the Delta database at " f"{self._root_uri!r}: {type(exc).__name__}: {exc}" ) from exc - raise OrcapodDatabaseReadError( - directory, self._path_prefix + path - ) from exc + if sources_only and isinstance(exc, OSError): + logger.warning("Could not list directory %s: %s", directory, exc) + continue + raise OrcapodDatabaseReadError(directory, path) from exc if _DELTA_LOG_DIRECTORY in children: - found.add(path) - owner = path - elif has_parquet: - suspected.add(owner) + found[path] = directory + if parquet_files: + data[path] = parquet_files for name in children: if name != _DELTA_LOG_DIRECTORY: - child = path + (component(name),) - child_owner = ( - owner if _is_delta_partition_directory(name) else child + to_visit.append((join(directory, name), path + (component(name),))) + + opened: dict[tuple[str, ...], deltalake.DeltaTable | None] = {} + active_files: dict[tuple[str, ...], set[str]] = {} + + def load( + path: tuple[str, ...], + *, + data_present: bool, + data_path: tuple[str, ...] | None = None, + ) -> deltalake.DeltaTable | None: + """Open a discovery candidate once and attribute failures to that path.""" + if path not in opened or (opened[path] is None and data_present): + try: + opened[path] = root._load_delta_table( + root._get_table_uri(path), data_present=data_present + ) + except Exception as exc: + if ( + isinstance(exc, FileNotFoundError) + and data_path is not None + and data_path != path + ): + location = root._get_table_uri(data_path) + cause = FileNotFoundError(f"{exc} at {location!r}") + cause.__cause__ = exc + raise root._read_failed(path) from cause + raise root._read_failed(path) from exc + return opened[path] + + for path, parquet_files in sorted(data.items()): + if path in found: + log = join(found[path], _DELTA_LOG_DIRECTORY) + if not any(is_file(join(log, name)) for name in _DELTA_LOG_MARKERS): + load(path, data_present=True) + continue + + owner = None + table = None + for depth in range(len(path) - 1, -1, -1): + ancestor = path[:depth] + if ancestor in found: + owner = ancestor + table = load(owner, data_present=True, data_path=path) + break + if depth < len(full_prefix): + if ( + not self._is_cloud + and not ( + Path(root._get_table_uri(ancestor)) / _DELTA_LOG_DIRECTORY + ).is_dir() + ): + continue + table = load(ancestor, data_present=False) + if table is not None: + owner = ancestor + break + + if owner is not None and table is not None: + relative = path[len(owner) :] + partition_columns = table.metadata().partition_columns + if partition_columns == [ + part.split("=", 1)[0] for part in relative + ] and all(_is_delta_partition_directory(part) for part in relative): + continue + if owner not in active_files: + active_files[owner] = set(table.file_uris()) + uri = root._get_table_uri(path) + if all( + join(uri, name) in active_files[owner] for name in parquet_files + ): + continue + + # A Hive-shaped suffix could be partitions of a lost table. Keep the + # actual data directory in the error, and respect the caller's scope. + candidate = path + boundary = max(len(full_prefix), len(owner) + 1 if owner is not None else 0) + while len(candidate) > boundary and _is_delta_partition_directory( + candidate[-1] + ): + candidate = candidate[:-1] + if load(candidate, data_present=True, data_path=path) is not None: + found[candidate] = root._get_table_uri(candidate) + + paths = sorted(found) + if sources_only: + # The legacy source listing returns the first table on each branch. + # Still walk below those tables to report independently damaged children. + sources: set[tuple[str, ...]] = set() + for path in paths: + depth = len(path) - len(full_prefix) + if ( + 0 < depth <= self.max_hierarchy_depth + and not any( + path[:index] in sources + for index in range(len(full_prefix) + 1, len(path)) ) - to_visit.append((join(directory, name), child, child_owner)) - for path in sorted(suspected - found): - if self.table_exists(path) and len(path) >= len(prefix): - found.add(path) - return sorted(found) + and load(path, data_present=False) is not None + ): + sources.add(path) + paths = sorted(sources) + return [path[len(self._path_prefix) :] for path in paths] - def _cloud_directory_lister(self) -> "Callable[[str], tuple[list[str], bool]]": - """Return a function listing the subdirectories of a cloud directory. + def _cloud_directory_lister( + self, + ) -> tuple[Callable[[str], tuple[list[str], list[str]]], Callable[[str], bool]]: + """Return functions to list cloud directory entries and check a file marker. Returns: - A function returning subdirectory names and whether there are Parquet files. + A directory lister returning subdirectory and Parquet file names, and + a file existence probe using the same filesystem. Raises: TableListingNotSupportedError: If no ``fsspec`` file system is available @@ -2176,20 +2294,26 @@ def _cloud_directory_lister(self) -> "Callable[[str], tuple[list[str], bool]]": f"({type(exc).__name__}: {exc})." ) from exc - def list_directory(directory: str) -> tuple[list[str], bool]: - """Return cloud subdirectory names and whether there are Parquet files.""" + def list_directory(directory: str) -> tuple[list[str], list[str]]: + """Return cloud subdirectory and Parquet file names.""" entries = file_system.ls(directory, detail=True) children = [ str(entry["name"]).rstrip("/").rsplit("/", 1)[-1] for entry in entries if entry["type"] == "directory" ] - return children, any( - entry["type"] == "file" and str(entry["name"]).endswith(".parquet") + parquet_files = [ + str(entry["name"]).rsplit("/", 1)[-1] for entry in entries - ) + if entry["type"] == "file" and str(entry["name"]).endswith(".parquet") + ] + return children, parquet_files - return list_directory + def is_file(path: str) -> bool: + """Check a log marker without walking the log directory.""" + return file_system.isfile(path) + + return list_directory, is_file def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a Delta table exists at ``record_path``. @@ -4413,39 +4537,4 @@ def list_sources(self) -> list[tuple[str, ...]]: "list_sources() is not supported for cloud storage paths" ) - sources: list[tuple[str, ...]] = [] - - def _scan(current_path: Path, path_components: tuple[str, ...]) -> None: - if len(path_components) >= self.max_hierarchy_depth: - return - try: - items = list(current_path.iterdir()) - except OSError as e: - logger.warning( - "Could not list directory %s during list_sources scan: %s", - current_path, - e, - ) - return - for item in items: - if not item.is_dir(): - continue - components = path_components + (item.name,) - try: - table = self._load_delta_table(str(item)) - except Exception as exc: - raise OrcapodDatabaseReadError( - str(item), self._path_prefix + components - ) from exc - if table is None: - _scan(item, components) - else: - sources.append(components) - - # Build the effective scoped root directory - scoped_root = self._local_root - for component in self._path_prefix: - scoped_root = scoped_root / self._sanitize_path_component(component) - - _scan(scoped_root, ()) - return sources + return self._discover_tables((), sources_only=True) diff --git a/tests/test_databases/test_delta_absent_tables.py b/tests/test_databases/test_delta_absent_tables.py index 7cdb6ee8d..98aa136c5 100644 --- a/tests/test_databases/test_delta_absent_tables.py +++ b/tests/test_databases/test_delta_absent_tables.py @@ -2,16 +2,18 @@ Until a table exists, a job's per-row lookups would each try to open it again. The family of a database (every handle from ``at()``) keeps the record keys it found absent and -answers lookups for them without opening the table, until any flush of the family (a -commit) or a flush of that table. ``table_exists`` always checks again. A table another -process creates is therefore seen after this database's next flush, as rows another -process appends to an already-loaded table are; a flush to a table believed absent -loads it first and never replaces it. +answers lookups without opening the table while no data files are visible. The +cached miss lasts until any flush of the family (a commit) or a flush of that table. +``table_exists`` always checks again. A healthy table another process creates is +therefore seen after this database's next flush, as rows another process appends to +an already-loaded table are. A flush to a table believed absent loads it first and +keeps its existing rows. """ from __future__ import annotations from pathlib import Path +import shutil from typing import cast import deltalake @@ -19,6 +21,8 @@ import pytest from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases +from orcapod.errors import OrcapodDatabaseReadError PATH = ("table",) @@ -129,6 +133,21 @@ def test_table_exists_checks_again(tmp_path: Path) -> None: assert _values(ours.get_all_records(PATH)) == [10] +def test_cached_miss_refuses_new_orphaned_data( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A prior miss still sees evidence of a damaged table from another writer.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + ours = DeltaTableDatabase(tmp_path) + assert ours.get_all_records(PATH) is None + DeltaTableDatabase(tmp_path).add_records(PATH, _rows(["x"], [10]), flush=True) + shutil.rmtree(tmp_path.joinpath(*PATH, "_delta_log")) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + ours.get_all_records(PATH) + assert info.value.record_path == PATH + + def test_flush_to_a_table_believed_absent_keeps_the_other_rows( tmp_path: Path, ) -> None: diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index f0d50b8c5..0ce5471fe 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -267,6 +267,116 @@ def test_partition_paths_do_not_count_as_separate_tables(base: Path, name: str) assert db.list_table_paths((*path, "tag1=a")) == [] +@pytest.mark.parametrize("write", [False, True], ids=["read", "flush"]) +def test_missing_log_with_non_hive_data_path( + base: Path, monkeypatch: pytest.MonkeyPatch, write: bool +) -> None: + """A valid AddFile path can contain arbitrary directory components.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + directory = table_dir(base) + data = pa.table({DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], "x": [1]}) + deltalake.write_deltalake(directory, data) + log = next((directory / "_delta_log").glob("*.json")) + original = next(directory.glob("*.parquet")) + moved = directory / "files" / "bucket" / original.name + moved.parent.mkdir(parents=True) + original.rename(moved) + actions = [json.loads(line) for line in log.read_text().splitlines()] + for action in actions: + if "add" in action: + action["add"]["path"] = moved.relative_to(directory).as_posix() + log.write_text("".join(json.dumps(action) + "\n" for action in actions)) + + db = DeltaTableDatabase(base_path=base) + original_rows = db.get_all_records(PATH) + assert original_rows is not None and original_rows.column("x").to_pylist() == [1] + shutil.rmtree(directory / "_delta_log") + before = snapshot(directory) + fresh = DeltaTableDatabase(base_path=base) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + if write: + fresh.add_record(PATH, b"b", pa.table({"x": [2]}), flush=True) + else: + fresh.get_all_records(PATH) + assert info.value.record_path == PATH + assert snapshot(directory) == before + + +@pytest.mark.parametrize("listing", ["list_table_paths", "list_sources"]) +def test_discovers_damaged_hive_named_child_of_healthy_table( + base: Path, monkeypatch: pytest.MonkeyPatch, listing: str +) -> None: + """The healthy parent's log does not own the separate Hive-named child.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + child = (*PATH, "tag=child") + data = pa.table({"tag1": ["a"], "x": [1]}) + deltalake.write_deltalake(table_dir(base), data, partition_by=["tag1"]) + deltalake.write_deltalake(base.joinpath(*child), data) + shutil.rmtree(base.joinpath(*child, "_delta_log")) + db = DeltaTableDatabase(base_path=base) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + getattr(db, listing)() + assert info.value.record_path == child + + +def test_discovery_names_ambiguous_hive_child( + base: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Without a log, both possible table locations appear in the error.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + child = ("group", "tag=child") + deltalake.write_deltalake(base.joinpath(*child), pa.table({"x": [1]})) + shutil.rmtree(base.joinpath(*child, "_delta_log")) + db = DeltaTableDatabase(base_path=base) + + for listing in (db.list_table_paths, db.list_sources): + with pytest.raises(OrcapodDatabaseReadError, match="tag=child") as info: + listing() + assert info.value.record_path == child[:-1] + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as scoped_info: + db.list_table_paths(child) + assert scoped_info.value.record_path == child + + +def test_scoped_partition_listing_only_walks_its_subtree( + base: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Scoping a handle inside a partition does not turn it into a table.""" + scope = (*PATH, "tag1=a") + data = pa.table({"tag1": ["a"], "tag2": ["b"], "x": [1]}) + deltalake.write_deltalake(table_dir(base), data, partition_by=["tag1", "tag2"]) + db = DeltaTableDatabase(base_path=base).at(*scope) + original = delta_lake_databases._list_local_directory # pyright: ignore[reportPrivateUsage] + + def list_scoped(directory: str): + assert Path(directory).is_relative_to(base.joinpath(*scope)) + return original(directory) + + monkeypatch.setattr(delta_lake_databases, "_list_local_directory", list_scoped) + assert db.list_table_paths() == [] + + +@pytest.mark.parametrize("listing", ["list_table_paths", "list_sources"]) +def test_discovery_refuses_empty_initial_log( + base: Path, monkeypatch: pytest.MonkeyPatch, listing: str +) -> None: + """A log directory alone cannot publish a table whose data are visible.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + data = pa.table({"tag1": ["a"], "x": [1]}) + deltalake.write_deltalake(table_dir(base), data, partition_by=["tag1"]) + log = table_dir(base) / "_delta_log" + shutil.rmtree(log) + log.mkdir() + db = DeltaTableDatabase(base_path=base) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + getattr(db, listing)() + assert info.value.record_path == PATH + + def test_flush_can_load_a_log_published_during_the_retry( base: Path, stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index b56ce8300..1a1d6593c 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -13,6 +13,8 @@ Run with: uv run pytest tests/test_databases/test_delta_table_database_s3.py -v """ +import json + import deltalake import pyarrow as pa import pytest @@ -120,6 +122,53 @@ def test_s3_table_with_missing_log_is_refused( assert {name: fs.cat_file(name) for name in fs.find(uri)} == before +def test_s3_non_hive_orphan_is_refused_by_fresh_and_cached_misses( + s3_base_uri: str, + s3_storage_options: dict[str, str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The Delta storage backend finds data at arbitrary depth after a miss.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + path = ("table",) + uri = f"{s3_base_uri}/table" + cached = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + assert cached.get_all_records(path) is None + writer = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + writer.add_record(path, b"a", pa.table({"x": [1]}), flush=True) + + fs = s3fs.S3FileSystem( + key=s3_storage_options["AWS_ACCESS_KEY_ID"], + secret=s3_storage_options["AWS_SECRET_ACCESS_KEY"], + client_kwargs={"endpoint_url": s3_storage_options["AWS_ENDPOINT_URL"]}, + use_listings_cache=False, + ) + log = f"{uri}/_delta_log/00000000000000000000.json" + actions = [json.loads(line) for line in fs.cat_file(log).splitlines()] + for action in actions: + if "add" in action: + original = action["add"]["path"] + moved = f"files/bucket/{original}" + fs.mv(f"{uri}/{original}", f"{uri}/{moved}") + action["add"]["path"] = moved + fs.pipe_file(log, "".join(json.dumps(action) + "\n" for action in actions).encode()) + fresh = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + assert fresh.list_table_paths() == [path] + assert fresh.at(*path, "files").list_table_paths() == [] + fs.rm(f"{uri}/_delta_log", recursive=True) + before = {name: fs.cat_file(name) for name in fs.find(uri)} + assert len(before) == 1 + + for operation in ( + lambda: fresh.get_all_records(path), + lambda: cached.get_all_records(path), + lambda: fresh.add_record(path, b"b", pa.table({"x": [2]}), flush=True), + ): + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + operation() + assert info.value.record_path == path + assert {name: fs.cat_file(name) for name in fs.find(uri)} == before + + def test_s3_skip_duplicates(s3_base_uri, s3_storage_options): db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) record = pa.table({"v": [1]}) From 1c70c64d920bd61baf6a5d67d9cb3bd237ed10d5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:14:31 -0800 Subject: [PATCH 05/10] fix(databases): preserve healthy Delta read and discovery paths --- changelog.d/ITL-916.md | 10 +- docs/dev/design_issues/ITL-916-DR2.md | 10 +- src/orcapod/databases/delta_lake_databases.py | 314 ++++++------------ .../test_delta_absent_tables.py | 30 +- .../test_delta_read_failures.py | 253 +++++++++----- .../test_delta_table_database_s3.py | 26 +- 6 files changed, 319 insertions(+), 324 deletions(-) diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md index 1b0b01e3c..d9083b0cd 100644 --- a/changelog.d/ITL-916.md +++ b/changelog.d/ITL-916.md @@ -1,7 +1,7 @@ ### Fixed -- Delta database reads, table discovery, existence checks, and writes now raise - `OrcapodDatabaseReadError` when a table has Parquet files and its transaction - log is missing or unpublished. This covers flat, partitioned, and arbitrary - nested data paths. The error names the table, and a flush leaves the existing - files intact. +- Delta database reads and writes raise `OrcapodDatabaseReadError` when they + would otherwise treat a table with existing Parquet files and a missing or + unpublished transaction log as absent. This covers flat, partitioned, and + arbitrary nested data paths. The error names the table, and a refused flush + leaves its files intact. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index 42454e15c..f441cc1da 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -9,11 +9,9 @@ Removing `_delta_log` from a table with stored rows made reads report an absent table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. -**Fix:** On a Delta table miss, use the local filesystem or the Delta storage -backend to look for Parquet files at any depth, outside transaction logs and +**Fix:** When a read or write opens a Delta table and the backend reports it +missing, look for Parquet files at any depth outside transaction logs and separately published child tables. When files exist, briefly retry opening the log to give a concurrent first writer time to publish it, then raise -`OrcapodDatabaseReadError` if the log still cannot be opened. Discovery checks -data ownership and identifies logs that are missing or still unpublished. -Existence checks open the current log even if the handle already holds a row -snapshot. Cached misses recheck for data files so they also surface orphaned rows. +`OrcapodDatabaseReadError` if the log still cannot be opened. Discovery and +cached reads keep their existing behavior. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index b43b81f19..1c3182ea6 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -158,26 +158,14 @@ def _s3fs_options(storage_options: Mapping[str, str]) -> dict[str, Any]: return options -def _is_delta_partition_directory(name: str) -> bool: - """Recognize Delta's Hive-style ``column=value`` directory names.""" - return name.find("=") > 0 - - -def _list_local_directory(directory: str) -> tuple[list[str], list[str]]: - """Return the names of the subdirectories and Parquet files. +def _list_local_directory(directory: str) -> list[str]: + """Return the names of the subdirectories of a local directory. A symbolic link to a directory is not a subdirectory here: following one that points at an ancestor would send the table walk in circles. """ - children: list[str] = [] - parquet_files: list[str] = [] with os.scandir(directory) as entries: - for entry in entries: - if entry.is_dir(follow_symlinks=False): - children.append(entry.name) - elif entry.name.endswith(".parquet") and entry.is_file(): - parquet_files.append(entry.name) - return children, parquet_files + return [entry.name for entry in entries if entry.is_dir(follow_symlinks=False)] def _join_local_path(directory: str, name: str) -> str: @@ -1829,9 +1817,9 @@ def __init__( on_empty=self._discard_pending_index, ) ) - # Record keys whose table was found absent (ITL-1173), so lookups can defer - # opening it again until there is evidence of data. Family-wide like the - # loaded tables, and forgotten on any flush of the family or the key: a table + # Record keys whose table was found absent (ITL-1173), so lookups do not try + # to open it again on every row. Family-wide like the loaded tables, and + # forgotten on any flush of the family and on a flush of the key: a table # another process creates is seen after this database's next flush, as rows # it appends to a loaded table are. ``table_exists`` always checks again. self._absent_tables: set[str] = ( @@ -1924,52 +1912,46 @@ def _validate_record_path(self, record_path: tuple[str, ...]) -> None: ) def _get_delta_table( - self, record_path: tuple[str, ...], *, check_current: bool = False + self, record_path: tuple[str, ...] ) -> deltalake.DeltaTable | None: """ Get an existing Delta table, either from cache or by loading it. Args: record_path: Tuple of path components - check_current: Open the current log even when a row snapshot is cached. Returns: deltalake.DeltaTable instance or None if table doesn't exist """ record_key = self._get_record_key(record_path) - if check_current: - self._absent_tables.discard(record_key) - else: - if dt := self._delta_table_cache.get(record_key): - return dt - table_uri = self._get_table_uri(record_path) + + # Check cache first + if dt := self._delta_table_cache.get(record_key): + return dt + if record_key in self._absent_tables: + return None + try: - if record_key in self._absent_tables: - # Keep healthy external commits invisible until the next flush, - # but refuse newly visible data whose log never became readable. - if self._has_delta_data_files(table_uri): - self._load_delta_table(table_uri, data_present=True) - return None delta_table = self._load_delta_table(table_uri) - except Exception as load_error: - raise self._read_failed(record_path) from load_error + except Exception as e: + # The table exists but could not be loaded: never report it as absent. + self._delta_table_cache.pop(record_key, None) + raise self._read_failed(record_path) from e + if delta_table is None: # Table doesn't exist: remembered until the next flush (ITL-1173). self._absent_tables.add(record_key) else: - self._delta_table_cache.setdefault(record_key, delta_table) + self._delta_table_cache[record_key] = delta_table logger.debug(f"Loaded existing Delta table for {record_key}") return delta_table - def _load_delta_table( - self, table_uri: str, *, data_present: bool | None = None - ) -> deltalake.DeltaTable | None: + def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: """Open the current Delta log, checking a missing log for existing data. Args: table_uri: The table's storage location. - data_present: Evidence from an existing filesystem walk, if available. Returns: The loaded table, or ``None`` when neither a log nor data files exist. @@ -1983,9 +1965,7 @@ def _load_delta_table( try: return deltalake.DeltaTable(table_uri, storage_options=options) except TableNotFoundError as missing_log: - if data_present is None: - data_present = self._has_delta_data_files(table_uri) - if not data_present: + if not self._has_delta_data_files(table_uri): return None for delay in _MISSING_LOG_RETRY_DELAYS: sleep(delay) @@ -2003,28 +1983,22 @@ def _has_delta_data_files(self, table_uri: str) -> bool: pending = [table_uri] while pending: directory = pending.pop() + if directory != table_uri and any( + os.path.isfile(os.path.join(directory, _DELTA_LOG_DIRECTORY, name)) + for name in _DELTA_LOG_MARKERS + ): + continue try: - children, parquet_files = _list_local_directory(directory) + with os.scandir(directory) as entries: + for entry in entries: + if entry.name == _DELTA_LOG_DIRECTORY: + continue + if entry.is_dir(follow_symlinks=False): + pending.append(entry.path) + elif entry.name.endswith(".parquet") and entry.is_file(): + return True except FileNotFoundError: continue - if ( - directory != table_uri - and _DELTA_LOG_DIRECTORY in children - and any( - os.path.isfile( - os.path.join(directory, _DELTA_LOG_DIRECTORY, name) - ) - for name in _DELTA_LOG_MARKERS - ) - ): - continue - if parquet_files: - return True - pending.extend( - _join_local_path(directory, name) - for name in children - if name != _DELTA_LOG_DIRECTORY - ) return False from deltalake.fs import DeltaStorageHandler @@ -2073,8 +2047,8 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] Walks the directories below ``prefix``: a directory that holds a ``_delta_log`` directory is a table. The walk goes on below a table, because tables can be nested (Orcapod v0.3 stores a table one level below where - v0.2 stored it), and never enters ``_delta_log``. Parquet files that no - readable Delta log accounts for trigger a bounded log-open retry. + v0.2 stored it), and never enters ``_delta_log``. No table is opened. Only + flushed tables are listed, as with ``table_exists``. A local database is listed exactly. A cloud database is listed through ``fsspec`` with one list request per directory: ``s3://`` and ``s3a://`` through @@ -2092,26 +2066,17 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] Raises: TableListingNotSupportedError: If the database is on cloud storage and could not be listed; the reason is chained. - OrcapodDatabaseReadError: If a local directory could not be listed or - data files have no readable transaction log. + OrcapodDatabaseReadError: If a local directory could not be listed. """ - return self._discover_tables(prefix) - - def _discover_tables( - self, prefix: tuple[str, ...], *, sources_only: bool = False - ) -> list[tuple[str, ...]]: - """Walk data directories once and check any evidence of an unpublished log.""" full_prefix = self._path_prefix + prefix - root = self._root if self._root is not None else self if self._is_cloud: - list_directory, is_file = self._cloud_directory_lister() + list_directory = self._cloud_directory_lister() start = self._root_uri.split("://", 1)[1].rstrip("/") start = "/".join((start,) + full_prefix) join = _join_cloud_path component = str else: list_directory = _list_local_directory - is_file = os.path.isfile start = str( self._local_root.joinpath( *(self._sanitize_path_component(part) for part in full_prefix) @@ -2120,13 +2085,13 @@ def _discover_tables( join = _join_local_path component = _stored_component - found: dict[tuple[str, ...], str] = {} - data: dict[tuple[str, ...], list[str]] = {} - to_visit = [(start, full_prefix)] + found: list[tuple[str, ...]] = [] + # Directories still to visit, each with its path below ``prefix``. + to_visit: list[tuple[str, tuple[str, ...]]] = [(start, ())] while to_visit: - directory, path = to_visit.pop() + directory, below = to_visit.pop() try: - children, parquet_files = list_directory(directory) + children = list_directory(directory) except FileNotFoundError: continue except Exception as exc: @@ -2135,127 +2100,20 @@ def _discover_tables( f"Could not list the tables of the Delta database at " f"{self._root_uri!r}: {type(exc).__name__}: {exc}" ) from exc - if sources_only and isinstance(exc, OSError): - logger.warning("Could not list directory %s: %s", directory, exc) - continue - raise OrcapodDatabaseReadError(directory, path) from exc - if _DELTA_LOG_DIRECTORY in children: - found[path] = directory - if parquet_files: - data[path] = parquet_files + raise OrcapodDatabaseReadError(directory, full_prefix + below) from exc for name in children: - if name != _DELTA_LOG_DIRECTORY: - to_visit.append((join(directory, name), path + (component(name),))) - - opened: dict[tuple[str, ...], deltalake.DeltaTable | None] = {} - active_files: dict[tuple[str, ...], set[str]] = {} - - def load( - path: tuple[str, ...], - *, - data_present: bool, - data_path: tuple[str, ...] | None = None, - ) -> deltalake.DeltaTable | None: - """Open a discovery candidate once and attribute failures to that path.""" - if path not in opened or (opened[path] is None and data_present): - try: - opened[path] = root._load_delta_table( - root._get_table_uri(path), data_present=data_present - ) - except Exception as exc: - if ( - isinstance(exc, FileNotFoundError) - and data_path is not None - and data_path != path - ): - location = root._get_table_uri(data_path) - cause = FileNotFoundError(f"{exc} at {location!r}") - cause.__cause__ = exc - raise root._read_failed(path) from cause - raise root._read_failed(path) from exc - return opened[path] - - for path, parquet_files in sorted(data.items()): - if path in found: - log = join(found[path], _DELTA_LOG_DIRECTORY) - if not any(is_file(join(log, name)) for name in _DELTA_LOG_MARKERS): - load(path, data_present=True) - continue - - owner = None - table = None - for depth in range(len(path) - 1, -1, -1): - ancestor = path[:depth] - if ancestor in found: - owner = ancestor - table = load(owner, data_present=True, data_path=path) - break - if depth < len(full_prefix): - if ( - not self._is_cloud - and not ( - Path(root._get_table_uri(ancestor)) / _DELTA_LOG_DIRECTORY - ).is_dir() - ): - continue - table = load(ancestor, data_present=False) - if table is not None: - owner = ancestor - break - - if owner is not None and table is not None: - relative = path[len(owner) :] - partition_columns = table.metadata().partition_columns - if partition_columns == [ - part.split("=", 1)[0] for part in relative - ] and all(_is_delta_partition_directory(part) for part in relative): - continue - if owner not in active_files: - active_files[owner] = set(table.file_uris()) - uri = root._get_table_uri(path) - if all( - join(uri, name) in active_files[owner] for name in parquet_files - ): - continue + if name == _DELTA_LOG_DIRECTORY: + found.append(prefix + below) + else: + to_visit.append((join(directory, name), below + (component(name),))) + return sorted(found) - # A Hive-shaped suffix could be partitions of a lost table. Keep the - # actual data directory in the error, and respect the caller's scope. - candidate = path - boundary = max(len(full_prefix), len(owner) + 1 if owner is not None else 0) - while len(candidate) > boundary and _is_delta_partition_directory( - candidate[-1] - ): - candidate = candidate[:-1] - if load(candidate, data_present=True, data_path=path) is not None: - found[candidate] = root._get_table_uri(candidate) - - paths = sorted(found) - if sources_only: - # The legacy source listing returns the first table on each branch. - # Still walk below those tables to report independently damaged children. - sources: set[tuple[str, ...]] = set() - for path in paths: - depth = len(path) - len(full_prefix) - if ( - 0 < depth <= self.max_hierarchy_depth - and not any( - path[:index] in sources - for index in range(len(full_prefix) + 1, len(path)) - ) - and load(path, data_present=False) is not None - ): - sources.add(path) - paths = sorted(sources) - return [path[len(self._path_prefix) :] for path in paths] - - def _cloud_directory_lister( - self, - ) -> tuple[Callable[[str], tuple[list[str], list[str]]], Callable[[str], bool]]: - """Return functions to list cloud directory entries and check a file marker. + def _cloud_directory_lister(self) -> "Callable[[str], list[str]]": + """Return a function listing the subdirectories of a cloud directory. Returns: - A directory lister returning subdirectory and Parquet file names, and - a file existence probe using the same filesystem. + A function from a directory (bucket and key, no scheme) to the names of + its subdirectories. Raises: TableListingNotSupportedError: If no ``fsspec`` file system is available @@ -2294,32 +2152,21 @@ def _cloud_directory_lister( f"({type(exc).__name__}: {exc})." ) from exc - def list_directory(directory: str) -> tuple[list[str], list[str]]: - """Return cloud subdirectory and Parquet file names.""" + def list_directory(directory: str) -> list[str]: + """Return the names of the subdirectories of a cloud directory.""" entries = file_system.ls(directory, detail=True) - children = [ + return [ str(entry["name"]).rstrip("/").rsplit("/", 1)[-1] for entry in entries if entry["type"] == "directory" ] - parquet_files = [ - str(entry["name"]).rsplit("/", 1)[-1] - for entry in entries - if entry["type"] == "file" and str(entry["name"]).endswith(".parquet") - ] - return children, parquet_files - - def is_file(path: str) -> bool: - """Check a log marker without walking the log directory.""" - return file_system.isfile(path) - return list_directory, is_file + return list_directory def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a Delta table exists at ``record_path``. - Check the current log without loading records or replacing a cached - row snapshot. + This is a cheap existence check that does NOT load any records. Args: record_path: Path components identifying the table, relative to @@ -2327,12 +2174,10 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: Returns: ``True`` if a table exists at the given path, ``False`` otherwise. - - Raises: - OrcapodDatabaseReadError: If the current log cannot be opened for a - table with data files. """ - return self._get_delta_table(record_path, check_current=True) is not None + # Checks again even when the table was found absent before (ITL-1173). + self._absent_tables.discard(self._get_record_key(record_path)) + return self._get_delta_table(record_path) is not None def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the latest Delta schema from the log or the table's first batch.""" @@ -4530,11 +4375,42 @@ def list_sources(self) -> list[tuple[str, ...]]: Raises: NotImplementedError: For cloud base paths (filesystem walk not supported). - OrcapodDatabaseReadError: If a table has data files but no readable log. """ if self._is_cloud: raise NotImplementedError( "list_sources() is not supported for cloud storage paths" ) - return self._discover_tables((), sources_only=True) + sources: list[tuple[str, ...]] = [] + + def _scan(current_path: Path, path_components: tuple[str, ...]) -> None: + if len(path_components) >= self.max_hierarchy_depth: + return + try: + items = list(current_path.iterdir()) + except OSError as e: + logger.warning( + "Could not list directory %s during list_sources scan: %s", + current_path, + e, + ) + return + for item in items: + if not item.is_dir(): + continue + components = path_components + (item.name,) + try: + deltalake.DeltaTable( + str(item), storage_options=self._storage_options or None + ) + sources.append(components) + except deltalake.exceptions.TableNotFoundError: + _scan(item, components) + + # Build the effective scoped root directory + scoped_root = self._local_root + for component in self._path_prefix: + scoped_root = scoped_root / self._sanitize_path_component(component) + + _scan(scoped_root, ()) + return sources diff --git a/tests/test_databases/test_delta_absent_tables.py b/tests/test_databases/test_delta_absent_tables.py index 98aa136c5..4df42d601 100644 --- a/tests/test_databases/test_delta_absent_tables.py +++ b/tests/test_databases/test_delta_absent_tables.py @@ -2,8 +2,8 @@ Until a table exists, a job's per-row lookups would each try to open it again. The family of a database (every handle from ``at()``) keeps the record keys it found absent and -answers lookups without opening the table while no data files are visible. The -cached miss lasts until any flush of the family (a commit) or a flush of that table. +answers lookups without opening the table until any flush of the family (a commit) or +a flush of that table. ``table_exists`` always checks again. A healthy table another process creates is therefore seen after this database's next flush, as rows another process appends to an already-loaded table are. A flush to a table believed absent loads it first and @@ -12,6 +12,7 @@ from __future__ import annotations +import os from pathlib import Path import shutil from typing import cast @@ -133,10 +134,29 @@ def test_table_exists_checks_again(tmp_path: Path) -> None: assert _values(ours.get_all_records(PATH)) == [10] -def test_cached_miss_refuses_new_orphaned_data( +def test_cached_miss_ignores_external_creation_without_storage_probes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, table_opens: list[str] +) -> None: + """A cached miss stays in memory even after another handle creates the table.""" + ours = DeltaTableDatabase(tmp_path) + assert ours.get_all_records(PATH) is None + DeltaTableDatabase(tmp_path).add_records(PATH, _rows(["x"], [10]), flush=True) + table_opens.clear() + + def unexpected_listing(*_args: object, **_kwargs: object) -> None: + pytest.fail("A cached miss should not scan for files") + + with monkeypatch.context() as probes: + probes.setattr(os, "scandir", unexpected_listing) + for _ in range(3): + assert ours.get_record_by_id(PATH, b"x") is None + assert not table_opens + + +def test_flush_after_a_cached_miss_refuses_new_orphaned_data( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """A prior miss still sees evidence of a damaged table from another writer.""" + """A write that would create a table must recheck storage after a cached miss.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) ours = DeltaTableDatabase(tmp_path) assert ours.get_all_records(PATH) is None @@ -144,7 +164,7 @@ def test_cached_miss_refuses_new_orphaned_data( shutil.rmtree(tmp_path.joinpath(*PATH, "_delta_log")) with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - ours.get_all_records(PATH) + ours.add_records(PATH, _rows(["y"], [20]), flush=True) assert info.value.record_path == PATH diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 0ce5471fe..08d639512 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -17,9 +17,11 @@ from __future__ import annotations +import asyncio import dataclasses import datetime import json +import os import shutil from collections.abc import Callable from pathlib import Path @@ -30,6 +32,7 @@ import pytest from deltalake.exceptions import DeltaProtocolError +from orcapod import function_pod from orcapod.databases import DeltaTableDatabase from orcapod.databases import delta_lake_databases from orcapod.errors import ( @@ -37,6 +40,7 @@ OrcapodDatabaseReadError, TypeIdentityError, ) +from orcapod.pipeline import PipelineJob from orcapod.sources import DictSource PATH = ("results", "t") @@ -160,22 +164,22 @@ def damaged_path(request: pytest.FixtureRequest) -> tuple[str, ...]: params=[None, ["tag1", "tag2"], ["tag2", "tag1"]], ids=["flat", "partitioned", "reordered-partitions"], ) -def damaged_stores( +def damaged_store( base: Path, damaged_path: tuple[str, ...], request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, -) -> tuple[DeltaTableDatabase, DeltaTableDatabase]: - """Return fresh and warm handles after dropping the log from a populated table.""" +) -> DeltaTableDatabase: + """Return a fresh handle after dropping the log from a populated table.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) directory = base.joinpath(*damaged_path) data = pa.table( { - DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], - "tag1": ["a"], - "tag2": ["b"], - "x": [1], - "y": [2], + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a", b"b"], + "tag1": ["a", "c"], + "tag2": ["b", "d"], + "x": [1, 3], + "y": [2, 4], } ) partitions = request.param @@ -188,23 +192,28 @@ def damaged_stores( assert warm.get_all_records(damaged_path) is not None assert any(directory.rglob("*.parquet")) shutil.rmtree(directory / "_delta_log") - return DeltaTableDatabase(base_path=base), warm + return DeltaTableDatabase(base_path=base) MISSING_LOG_READS: dict[ str, Callable[[DeltaTableDatabase, tuple[str, ...]], object] ] = { "get_all_records": lambda db, path: db.get_all_records(path), - "get_records_by_ids": lambda db, path: db.get_records_by_ids(path, [b"a", b"b"]), + "get_records_by_ids_forward": lambda db, path: db.get_records_by_ids( + path, [b"a", b"b"] + ), + "get_records_by_ids_reverse": lambda db, path: db.get_records_by_ids( + path, [b"b", b"a"] + ), "get_record_by_id": lambda db, path: db.get_record_by_id(path, b"a"), - "get_records_with_column_value": lambda db, path: db.get_records_with_column_value( - path, {"y": 2, "x": 1} + "get_records_with_column_value_reverse": lambda db, path: ( + db.get_records_with_column_value(path, {"y": 2, "x": 1}) + ), + "get_records_with_column_value_forward": lambda db, path: ( + db.get_records_with_column_value(path, {"x": 1, "y": 2}) ), "get_table_schema": lambda db, path: db.get_table_schema(path), "table_exists": lambda db, path: db.table_exists(path), - "list_sources": lambda db, _path: db.list_sources(), - "list_table_paths": lambda db, _path: db.list_table_paths(), - "list_table_paths_with_prefix": lambda db, path: db.list_table_paths(path), } @@ -213,43 +222,44 @@ def damaged_stores( ) def test_missing_log_is_a_read_error( damaged_path: tuple[str, ...], - damaged_stores: tuple[DeltaTableDatabase, DeltaTableDatabase], + damaged_store: DeltaTableDatabase, read: Callable[[DeltaTableDatabase, tuple[str, ...]], object], ) -> None: - """Row reads and metadata discovery name the table with orphaned data.""" - fresh, _ = damaged_stores + """Reads and table metadata queries name the table with orphaned data.""" with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - read(fresh, damaged_path) + _ = read(damaged_store, damaged_path) assert info.value.record_path == damaged_path -def test_table_exists_refuses_a_missing_log_on_a_warm_handle( - damaged_path: tuple[str, ...], - damaged_stores: tuple[DeltaTableDatabase, DeltaTableDatabase], +def test_table_exists_uses_the_loaded_snapshot( + stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch ) -> None: - """An existence check sees the missing log while row reads keep their snapshot.""" - _, warm = damaged_stores - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - warm.table_exists(damaged_path) - assert info.value.record_path == damaged_path - assert warm.get_all_records(damaged_path) is not None + """A warm existence check performs no new log opens or data-directory walks.""" + assert stored.get_all_records(PATH) is not None + + def unexpected_io(*_args: object, **_kwargs: object) -> None: + pytest.fail("A warm existence check should use the loaded snapshot") + + with monkeypatch.context() as probes: + probes.setattr(deltalake.DeltaTable, "__init__", unexpected_io) + probes.setattr(os, "scandir", unexpected_io) + assert stored.table_exists(PATH) def test_flush_refuses_a_missing_log( base: Path, damaged_path: tuple[str, ...], - damaged_stores: tuple[DeltaTableDatabase, DeltaTableDatabase], + damaged_store: DeltaTableDatabase, ) -> None: """Flushing to a folder with orphaned data writes no files or log.""" - fresh, _ = damaged_stores directory = base.joinpath(*damaged_path) before = snapshot(directory) - fresh.add_records( + damaged_store.add_records( damaged_path, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" ) with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - fresh.flush() + damaged_store.flush() assert info.value.record_path == damaged_path assert snapshot(directory) == before @@ -267,15 +277,8 @@ def test_partition_paths_do_not_count_as_separate_tables(base: Path, name: str) assert db.list_table_paths((*path, "tag1=a")) == [] -@pytest.mark.parametrize("write", [False, True], ids=["read", "flush"]) -def test_missing_log_with_non_hive_data_path( - base: Path, monkeypatch: pytest.MonkeyPatch, write: bool -) -> None: - """A valid AddFile path can contain arbitrary directory components.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) - directory = table_dir(base) - data = pa.table({DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], "x": [1]}) - deltalake.write_deltalake(directory, data) +def move_delta_data_file(directory: Path) -> Path: + """Move a Delta file into an arbitrary directory while retaining its AddFile.""" log = next((directory / "_delta_log").glob("*.json")) original = next(directory.glob("*.parquet")) moved = directory / "files" / "bucket" / original.name @@ -287,6 +290,20 @@ def test_missing_log_with_non_hive_data_path( action["add"]["path"] = moved.relative_to(directory).as_posix() log.write_text("".join(json.dumps(action) + "\n" for action in actions)) + return moved + + +@pytest.mark.parametrize("write", [False, True], ids=["read", "flush"]) +def test_missing_log_with_non_hive_data_path( + base: Path, monkeypatch: pytest.MonkeyPatch, write: bool +) -> None: + """A valid AddFile path can contain arbitrary directory components.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + directory = table_dir(base) + data = pa.table({DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], "x": [1]}) + deltalake.write_deltalake(directory, data) + _ = move_delta_data_file(directory) + db = DeltaTableDatabase(base_path=base) original_rows = db.get_all_records(PATH) assert original_rows is not None and original_rows.column("x").to_pylist() == [1] @@ -304,41 +321,71 @@ def test_missing_log_with_non_hive_data_path( @pytest.mark.parametrize("listing", ["list_table_paths", "list_sources"]) -def test_discovers_damaged_hive_named_child_of_healthy_table( - base: Path, monkeypatch: pytest.MonkeyPatch, listing: str +def test_discovery_keeps_a_table_with_retained_non_hive_data( + base: Path, listing: str ) -> None: - """The healthy parent's log does not own the separate Hive-named child.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) - child = (*PATH, "tag=child") - data = pa.table({"tag1": ["a"], "x": [1]}) - deltalake.write_deltalake(table_dir(base), data, partition_by=["tag1"]) - deltalake.write_deltalake(base.joinpath(*child), data) - shutil.rmtree(base.joinpath(*child, "_delta_log")) - db = DeltaTableDatabase(base_path=base) + """A retired data file in a subdirectory does not hide a healthy table.""" + directory = table_dir(base) + deltalake.write_deltalake(directory, pa.table({"x": [1]})) + retired = move_delta_data_file(directory) + deltalake.write_deltalake(directory, pa.table({"x": [2]}), mode="overwrite") + assert retired.is_file() - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - getattr(db, listing)() - assert info.value.record_path == child + db = DeltaTableDatabase(base) + assert getattr(db, listing)() == [PATH] -def test_discovery_names_ambiguous_hive_child( - base: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Without a log, both possible table locations appear in the error.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) - child = ("group", "tag=child") - deltalake.write_deltalake(base.joinpath(*child), pa.table({"x": [1]})) - shutil.rmtree(base.joinpath(*child, "_delta_log")) - db = DeltaTableDatabase(base_path=base) +def test_list_sources_keeps_directory_symlink_aliases(base: Path) -> None: + """Source listing follows a directory alias as it does a regular table path.""" + target = base / "table" + deltalake.write_deltalake(target, pa.table({"x": [1]})) + try: + (base / "alias").symlink_to(target, target_is_directory=True) + except OSError as exc: + pytest.skip(f"Directory symlinks unavailable: {exc}") - for listing in (db.list_table_paths, db.list_sources): - with pytest.raises(OrcapodDatabaseReadError, match="tag=child") as info: - listing() - assert info.value.record_path == child[:-1] + db = DeltaTableDatabase(base) + assert sorted(db.list_sources()) == [("alias",), ("table",)] + assert db.list_table_paths() == [("table",)] - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as scoped_info: - db.list_table_paths(child) - assert scoped_info.value.record_path == child + +@pytest.mark.parametrize("listing", ["list_table_paths", "list_sources"]) +def test_healthy_partitioned_discovery_keeps_legacy_io( + base: Path, monkeypatch: pytest.MonkeyPatch, listing: str +) -> None: + """Path listing opens no log, and source listing stops at the first table.""" + deltalake.write_deltalake( + table_dir(base), + pa.table({"tag1": ["a", "b"], "tag2": ["c", "d"], "x": [1, 2]}), + partition_by=["tag1", "tag2"], + ) + db = DeltaTableDatabase(base) + opens: list[Path] = [] + directories: list[Path] = [] + original_open = deltalake.DeltaTable.__init__ + original_scandir = os.scandir + + def track_open( + table: deltalake.DeltaTable, + uri: str, + *, + storage_options: dict[str, str] | None = None, + ) -> None: + opens.append(Path(uri)) + original_open(table, uri, storage_options=storage_options) + + def track_scandir(directory: str): + directories.append(Path(directory)) + return original_scandir(directory) + + monkeypatch.setattr(deltalake.DeltaTable, "__init__", track_open) + monkeypatch.setattr(os, "scandir", track_scandir) + assert getattr(db, listing)() == [PATH] + if listing == "list_table_paths": + assert not opens + else: + assert opens == [base / PATH[0], table_dir(base)] + assert all(not path.is_relative_to(table_dir(base)) for path in directories) def test_scoped_partition_listing_only_walks_its_subtree( @@ -359,24 +406,74 @@ def list_scoped(directory: str): assert db.list_table_paths() == [] -@pytest.mark.parametrize("listing", ["list_table_paths", "list_sources"]) -def test_discovery_refuses_empty_initial_log( - base: Path, monkeypatch: pytest.MonkeyPatch, listing: str +def test_empty_initial_log_is_refused_on_read( + base: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """A log directory alone cannot publish a table whose data are visible.""" + """An empty log with existing data cannot be mistaken for an absent table.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) - data = pa.table({"tag1": ["a"], "x": [1]}) - deltalake.write_deltalake(table_dir(base), data, partition_by=["tag1"]) + deltalake.write_deltalake(table_dir(base), pa.table({"x": [1]})) log = table_dir(base) / "_delta_log" shutil.rmtree(log) log.mkdir() - db = DeltaTableDatabase(base_path=base) with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - getattr(db, listing)() + DeltaTableDatabase(base).get_all_records(PATH) assert info.value.record_path == PATH +@function_pod(output_keys=["sum", "difference"]) +def _combine(x: int, y: int) -> tuple[int, int]: + """Compute two columns for the persistent job result.""" + return x + y, x - y + + +@pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["forward", "reverse"]) +def test_job_refuses_a_missing_result_log( + base: Path, monkeypatch: pytest.MonkeyPatch, use_async: bool, reverse: bool +) -> None: + """A rebuilt job refuses orphaned results without writing to the store.""" + monkeypatch.setattr( + delta_lake_databases, "sleep", lambda _delay: None, raising=False + ) + records = [ + {"tag1": "a", "tag2": 1, "x": 2, "y": 7}, + {"tag1": "b", "tag2": 2, "x": 4, "y": 8}, + ] + tags = ["tag1", "tag2"] + if reverse: + records = [dict(reversed(list(record.items()))) for record in records] + tags.reverse() + + def run() -> None: + source = DictSource( + records, tag_columns=tags, tag_only_columns=True, source_id="input" + ) + job = PipelineJob(name="missing_log", database=DeltaTableDatabase(base)) + with job: + _ = _combine.pod(source, label="combine") + if use_async: + _ = asyncio.run(job.run_async()) + else: + _ = job.run() + + run() + (result_log,) = [ + log + for log in base.rglob("_delta_log") + if "_result" in log.relative_to(base).parts + and any(log.parent.glob("*.parquet")) + ] + shutil.rmtree(result_log) + before = snapshot(base) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + run() + + assert Path(info.value.table) == result_log.parent + assert snapshot(base) == before + + def test_flush_can_load_a_log_published_during_the_retry( base: Path, stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index 1a1d6593c..1d9c26b77 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -68,7 +68,9 @@ def test_s3_flush_and_read(s3_base_uri, s3_storage_options): "path", [("table",), ("group", "table")], ids=["top-level", "nested"] ) @pytest.mark.parametrize( - "partitions", [None, ["tag1", "tag2"]], ids=["flat", "partitioned"] + "partitions", + [None, ["tag1", "tag2"], ["tag2", "tag1"]], + ids=["flat", "partitioned", "reordered-partitions"], ) def test_s3_table_with_missing_log_is_refused( s3_base_uri: str, @@ -89,11 +91,13 @@ def test_s3_table_with_missing_log_is_refused( "x": [1], } ) + if partitions == ["tag2", "tag1"]: + data = data.select( + ["x", "tag2", DeltaTableDatabase.RECORD_ID_COLUMN, "tag1", "y"] + ) deltalake.write_deltalake( uri, data, partition_by=partitions, storage_options=s3_storage_options ) - warm = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) - assert warm.get_all_records(path) is not None fs = s3fs.S3FileSystem( key=s3_storage_options["AWS_ACCESS_KEY_ID"], @@ -110,9 +114,6 @@ def test_s3_table_with_missing_log_is_refused( lambda: fresh.get_all_records(path), lambda: fresh.get_table_schema(path), lambda: fresh.table_exists(path), - lambda: warm.table_exists(path), - lambda: fresh.list_table_paths(), - lambda: fresh.list_table_paths(path), lambda: fresh.add_record(path, b"b", pa.table({"v": [2]}), flush=True), ): with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: @@ -122,7 +123,7 @@ def test_s3_table_with_missing_log_is_refused( assert {name: fs.cat_file(name) for name in fs.find(uri)} == before -def test_s3_non_hive_orphan_is_refused_by_fresh_and_cached_misses( +def test_s3_non_hive_orphan_is_refused_on_first_read_and_flush( s3_base_uri: str, s3_storage_options: dict[str, str], monkeypatch: pytest.MonkeyPatch, @@ -131,8 +132,10 @@ def test_s3_non_hive_orphan_is_refused_by_fresh_and_cached_misses( monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) path = ("table",) uri = f"{s3_base_uri}/table" - cached = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) - assert cached.get_all_records(path) is None + writer_with_cached_miss = DeltaTableDatabase( + s3_base_uri, storage_options=s3_storage_options + ) + assert writer_with_cached_miss.get_all_records(path) is None writer = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) writer.add_record(path, b"a", pa.table({"x": [1]}), flush=True) @@ -160,8 +163,9 @@ def test_s3_non_hive_orphan_is_refused_by_fresh_and_cached_misses( for operation in ( lambda: fresh.get_all_records(path), - lambda: cached.get_all_records(path), - lambda: fresh.add_record(path, b"b", pa.table({"x": [2]}), flush=True), + lambda: writer_with_cached_miss.add_record( + path, b"b", pa.table({"x": [2]}), flush=True + ), ): with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: operation() From f0549a5ad15180dd7bc6052b80293143ffb41902 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:56:17 -0800 Subject: [PATCH 06/10] fix(databases): preserve independent Delta tables at partition paths --- docs/dev/design_issues/ITL-916-DR2.md | 5 +- src/orcapod/databases/delta_lake_databases.py | 65 ++++++++++++++++--- .../test_delta_read_failures.py | 61 +++++++++++++++++ .../test_delta_table_database_s3.py | 35 ++++++++++ 4 files changed, 155 insertions(+), 11 deletions(-) diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index f441cc1da..312a0341f 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -11,7 +11,8 @@ Parquet files, silently leaving their rows out of the table. **Fix:** When a read or write opens a Delta table and the backend reports it missing, look for Parquet files at any depth outside transaction logs and -separately published child tables. When files exist, briefly retry opening the -log to give a concurrent first writer time to publish it, then raise +separately published child tables. A readable ancestor log can identify files +that belong to its own table. When unclaimed files exist, briefly retry opening +the log to give a concurrent first writer time to publish it, then raise `OrcapodDatabaseReadError` if the log still cannot be opened. Discovery and cached reads keep their existing behavior. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 1c3182ea6..993db6132 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -7,12 +7,13 @@ import sys import uuid from collections import defaultdict -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Iterator, Mapping from contextlib import AbstractContextManager from dataclasses import dataclass -from pathlib import Path +from pathlib import Path, PurePosixPath from time import sleep from typing import TYPE_CHECKING, Any, Literal, cast +from urllib.parse import unquote import polars as pl import pyarrow as pa @@ -1965,7 +1966,7 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: try: return deltalake.DeltaTable(table_uri, storage_options=options) except TableNotFoundError as missing_log: - if not self._has_delta_data_files(table_uri): + if not self._has_orphaned_delta_data_files(table_uri): return None for delay in _MISSING_LOG_RETRY_DELAYS: sleep(delay) @@ -1977,8 +1978,55 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: f"Found Parquet data files without a readable {_DELTA_LOG_DIRECTORY}" ) from missing_log - def _has_delta_data_files(self, table_uri: str) -> bool: - """Find Parquet files at any depth outside logs and published child tables.""" + def _has_orphaned_delta_data_files(self, table_uri: str) -> bool: + """Check whether the missing table path holds data unclaimed by ancestors.""" + ancestor_files: set[str] | None = None + for path in self._delta_data_paths(table_uri): + if ancestor_files is None: + ancestor_files = self._ancestor_delta_data_paths(table_uri) + if path not in ancestor_files: + return True + return False + + def _ancestor_delta_data_paths(self, table_uri: str) -> set[str]: + """Get files under the candidate path registered in readable ancestor logs.""" + from deltalake.exceptions import DeltaError + + if self._is_cloud: + scheme, separator, location = table_uri.partition("://") + uri_prefix = scheme + separator + table_path = PurePosixPath(location) + else: + uri_prefix = "" + table_path = Path(table_uri).absolute() + + owned: set[str] = set() + for ancestor in table_path.parents: + if not ancestor.parts: + continue # A cloud URI must include its bucket or container. + if ( + isinstance(ancestor, Path) + and not (ancestor / _DELTA_LOG_DIRECTORY).is_dir() + ): + continue + ancestor_uri = uri_prefix + str(ancestor) + prefix = table_path.relative_to(ancestor).as_posix() + "/" + try: + table = deltalake.DeltaTable( + ancestor_uri, storage_options=self._storage_options or None + ) + actions = table.get_add_actions() + except DeltaError: + continue # Only a readable ancestor log can establish ownership. + for path in actions.column("path").to_pylist(): + # Delta encodes AddFile paths, including '%' in Hive partition names. + relative_path = unquote(path) + if relative_path.startswith(prefix): + owned.add(relative_path[len(prefix) :]) + return owned + + def _delta_data_paths(self, table_uri: str) -> Iterator[str]: + """Yield relative Parquet paths outside logs and published child tables.""" if not self._is_cloud: pending = [table_uri] while pending: @@ -1996,10 +2044,10 @@ def _has_delta_data_files(self, table_uri: str) -> bool: if entry.is_dir(follow_symlinks=False): pending.append(entry.path) elif entry.name.endswith(".parquet") and entry.is_file(): - return True + yield Path(entry.path).relative_to(table_uri).as_posix() except FileNotFoundError: continue - return False + return from deltalake.fs import DeltaStorageHandler from pyarrow.fs import FileSelector, FileType @@ -2024,8 +2072,7 @@ def _has_delta_data_files(self, table_uri: str) -> bool: if _DELTA_LOG_DIRECTORY not in parts[:-1] and not any( tuple(parts[:depth]) in child_tables for depth in range(1, len(parts)) ): - return True - return False + yield "/".join(parts) def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError: """Build the error for a table at ``record_path`` that exists but cannot be read. diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 08d639512..f4410a92e 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -277,6 +277,67 @@ def test_partition_paths_do_not_count_as_separate_tables(base: Path, name: str) assert db.list_table_paths((*path, "tag1=a")) == [] +@pytest.mark.parametrize("operation", ["exists", "read", "schema", "create"]) +def test_partition_path_accepts_independent_child( + base: Path, monkeypatch: pytest.MonkeyPatch, operation: str +) -> None: + """A parent's active data files do not make its partition a damaged child.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + parent = ("group", "table") + partition = (*parent, "tag1=a", "tag2=b") + data = pa.table( + { + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag1": ["a"], + "tag2": ["b"], + "x": [1], + } + ) + deltalake.write_deltalake( + base.joinpath(*parent), data, partition_by=["tag1", "tag2"] + ) + db = DeltaTableDatabase(base).at(*partition[:-1]) + child = partition[-1:] + if operation == "exists": + assert not db.table_exists(child) + elif operation == "read": + assert db.get_all_records(child) is None + elif operation == "schema": + assert db.get_table_schema(child) is None + else: + db.add_record(child, b"b", pa.table({"x": [2]}), flush=True) + child_rows = DeltaTableDatabase(base).get_all_records(partition) + assert child_rows is not None and child_rows.column("x").to_pylist() == [2] + parent_rows = DeltaTableDatabase(base).get_all_records(parent) + assert parent_rows is not None and parent_rows.column("x").to_pylist() == [1] + + +def test_missing_child_log_is_refused_inside_occupied_partition( + base: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A parent's files and a damaged child's files can share a partition.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + parent = ("parent",) + child = (*parent, "tag1=a", "tag2=b") + record_id = DeltaTableDatabase.RECORD_ID_COLUMN + data = pa.table({record_id: [b"a"], "tag1": ["a"], "tag2": ["b"], "x": [1]}) + deltalake.write_deltalake( + base.joinpath(*parent), data, partition_by=["tag1", "tag2"] + ) + directory = base.joinpath(*child) + deltalake.write_deltalake(directory, pa.table({record_id: [b"b"], "x": [2]})) + shutil.rmtree(directory / "_delta_log") + before = snapshot(directory) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): + DeltaTableDatabase(base).get_all_records(child) + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): + DeltaTableDatabase(base).add_record( + child, b"c", pa.table({"x": [3]}), flush=True + ) + assert snapshot(directory) == before + + def move_delta_data_file(directory: Path) -> Path: """Move a Delta file into an arbitrary directory while retaining its AddFile.""" log = next((directory / "_delta_log").glob("*.json")) diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index 1d9c26b77..e727e45c2 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -173,6 +173,41 @@ def test_s3_non_hive_orphan_is_refused_on_first_read_and_flush( assert {name: fs.cat_file(name) for name in fs.find(uri)} == before +def test_s3_partition_path_accepts_independent_child( + s3_base_uri: str, + s3_storage_options: dict[str, str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Objects registered in a parent's log are not orphaned at its partition.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + path = ("parent",) + partition = (*path, "tag1=a", "tag2=b") + data = pa.table( + { + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag1": ["a"], + "tag2": ["b"], + "x": [1], + } + ) + deltalake.write_deltalake( + f"{s3_base_uri}/parent", + data, + partition_by=["tag1", "tag2"], + storage_options=s3_storage_options, + ) + db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + assert not db.table_exists(partition) + assert db.get_all_records(partition) is None + assert db.get_table_schema(partition) is None + db.add_record(partition, b"b", pa.table({"x": [2]}), flush=True) + fresh = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + child_rows = fresh.get_all_records(partition) + assert child_rows is not None and child_rows.column("x").to_pylist() == [2] + parent_rows = fresh.get_all_records(path) + assert parent_rows is not None and parent_rows.column("x").to_pylist() == [1] + + def test_s3_skip_duplicates(s3_base_uri, s3_storage_options): db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) record = pa.table({"v": [1]}) From e555a940b9446d832f9a4c4e07be204b123f8c37 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 07:02:56 -0800 Subject: [PATCH 07/10] fix(databases): distinguish retained Delta files and non-Parquet objects --- docs/dev/design_issues/ITL-916-DR2.md | 7 +- src/orcapod/databases/delta_lake_databases.py | 68 +++++++++++++++---- .../test_delta_read_failures.py | 37 +++++++++- .../test_delta_table_database_s3.py | 52 +++++++++++++- 4 files changed, 143 insertions(+), 21 deletions(-) diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index 312a0341f..abf2d6e91 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -10,9 +10,10 @@ table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. **Fix:** When a read or write opens a Delta table and the backend reports it -missing, look for Parquet files at any depth outside transaction logs and -separately published child tables. A readable ancestor log can identify files -that belong to its own table. When unclaimed files exist, briefly retry opening +missing, check the header and footer markers of candidate Parquet files at any +depth outside transaction logs and separately published child tables. A readable +ancestor log can identify its active files and retained files pending vacuum. +When unclaimed files exist, briefly retry opening the log to give a concurrent first writer time to publish it, then raise `OrcapodDatabaseReadError` if the log still cannot be opened. Discovery and cached reads keep their existing behavior. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 993db6132..5de759fa1 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -12,7 +12,7 @@ from dataclasses import dataclass from pathlib import Path, PurePosixPath from time import sleep -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast from urllib.parse import unquote import polars as pl @@ -91,6 +91,16 @@ # A first writer can put its Parquet files in place before publishing version zero. _MISSING_LOG_RETRY_DELAYS = (0.02, 0.08, 0.2, 0.5) + +def _has_parquet_magic(file: BinaryIO | pa.NativeFile) -> bool: + """Check the header and footer markers without reading the Parquet metadata.""" + return ( + file.read(4) == b"PAR1" + and file.seek(-4, os.SEEK_END) >= 8 + and file.read(4) == b"PAR1" + ) + + # How many times a flush tries to commit a table's pending rows when other writers # keep committing first; after the last attempt it raises the last conflict # (ITL-1377). A writer that lost waits until the others pause: measured with 4 @@ -1980,16 +1990,18 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: def _has_orphaned_delta_data_files(self, table_uri: str) -> bool: """Check whether the missing table path holds data unclaimed by ancestors.""" - ancestor_files: set[str] | None = None + ancestor_files = self._ancestor_delta_data_paths(table_uri) + owned: set[str] = set() for path in self._delta_data_paths(table_uri): - if ancestor_files is None: - ancestor_files = self._ancestor_delta_data_paths(table_uri) - if path not in ancestor_files: - return True + while path not in owned: + ancestor_file = next(ancestor_files, None) + if ancestor_file is None: + return True + owned.add(ancestor_file) return False - def _ancestor_delta_data_paths(self, table_uri: str) -> set[str]: - """Get files under the candidate path registered in readable ancestor logs.""" + def _ancestor_delta_data_paths(self, table_uri: str) -> Iterator[str]: + """Yield active files, then retained files recorded by ancestor tables.""" from deltalake.exceptions import DeltaError if self._is_cloud: @@ -2000,7 +2012,7 @@ def _ancestor_delta_data_paths(self, table_uri: str) -> set[str]: uri_prefix = "" table_path = Path(table_uri).absolute() - owned: set[str] = set() + ancestors: list[tuple[deltalake.DeltaTable, str]] = [] for ancestor in table_path.parents: if not ancestor.parts: continue # A cloud URI must include its bucket or container. @@ -2018,12 +2030,28 @@ def _ancestor_delta_data_paths(self, table_uri: str) -> set[str]: actions = table.get_add_actions() except DeltaError: continue # Only a readable ancestor log can establish ownership. + ancestors.append((table, prefix)) for path in actions.column("path").to_pylist(): # Delta encodes AddFile paths, including '%' in Hive partition names. relative_path = unquote(path) if relative_path.startswith(prefix): - owned.add(relative_path[len(prefix) :]) - return owned + yield relative_path[len(prefix) :] + + for table, prefix in ancestors: + try: + # A LITE dry run exposes removed files recorded in the log without + # claiming untracked files such as those of a damaged child. + removed = table.vacuum( + retention_hours=0, + dry_run=True, + enforce_retention_duration=False, + full=False, + ) + except DeltaError: + continue + for path in removed: + if path.startswith(prefix): + yield path[len(prefix) :] def _delta_data_paths(self, table_uri: str) -> Iterator[str]: """Yield relative Parquet paths outside logs and published child tables.""" @@ -2044,7 +2072,17 @@ def _delta_data_paths(self, table_uri: str) -> Iterator[str]: if entry.is_dir(follow_symlinks=False): pending.append(entry.path) elif entry.name.endswith(".parquet") and entry.is_file(): - yield Path(entry.path).relative_to(table_uri).as_posix() + try: + with open(entry.path, "rb") as file: + is_parquet = _has_parquet_magic(file) + except FileNotFoundError: + continue + if is_parquet: + yield ( + Path(entry.path) + .relative_to(table_uri) + .as_posix() + ) except FileNotFoundError: continue return @@ -2072,7 +2110,11 @@ def _delta_data_paths(self, table_uri: str) -> Iterator[str]: if _DELTA_LOG_DIRECTORY not in parts[:-1] and not any( tuple(parts[:depth]) in child_tables for depth in range(1, len(parts)) ): - yield "/".join(parts) + path = "/".join(parts) + with handler.open_input_file(path) as file: + is_parquet = _has_parquet_magic(file) + if is_parquet: + yield path def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError: """Build the error for a table at ``record_path`` that exists but cannot be read. diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index f4410a92e..49fc3c73e 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -278,10 +278,11 @@ def test_partition_paths_do_not_count_as_separate_tables(base: Path, name: str) @pytest.mark.parametrize("operation", ["exists", "read", "schema", "create"]) +@pytest.mark.parametrize("overwrite", [False, True], ids=["active", "retained"]) def test_partition_path_accepts_independent_child( - base: Path, monkeypatch: pytest.MonkeyPatch, operation: str + base: Path, monkeypatch: pytest.MonkeyPatch, operation: str, overwrite: bool ) -> None: - """A parent's active data files do not make its partition a damaged child.""" + """A parent's active and retired files leave its partition usable as a child.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) parent = ("group", "table") partition = (*parent, "tag1=a", "tag2=b") @@ -296,6 +297,14 @@ def test_partition_path_accepts_independent_child( deltalake.write_deltalake( base.joinpath(*parent), data, partition_by=["tag1", "tag2"] ) + if overwrite: + deltalake.write_deltalake( + base.joinpath(*parent), + data.set_column(3, "x", pa.array([3])), + partition_by=["tag1", "tag2"], + mode="overwrite", + ) + assert len(list(base.joinpath(*partition).glob("*.parquet"))) == 2 db = DeltaTableDatabase(base).at(*partition[:-1]) child = partition[-1:] if operation == "exists": @@ -309,7 +318,29 @@ def test_partition_path_accepts_independent_child( child_rows = DeltaTableDatabase(base).get_all_records(partition) assert child_rows is not None and child_rows.column("x").to_pylist() == [2] parent_rows = DeltaTableDatabase(base).get_all_records(parent) - assert parent_rows is not None and parent_rows.column("x").to_pylist() == [1] + assert parent_rows is not None + assert parent_rows.column("x").to_pylist() == [3 if overwrite else 1] + + +@pytest.mark.parametrize("contents", [b"plain text", b"PAR1 plain text"]) +def test_non_parquet_file_does_not_make_a_missing_table_unreadable( + base: Path, monkeypatch: pytest.MonkeyPatch, contents: bytes +) -> None: + """A Parquet suffix or header alone does not identify a Parquet file.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + directory = table_dir(base) + directory.mkdir(parents=True) + note = directory / "note.parquet" + _ = note.write_bytes(contents) + + assert not DeltaTableDatabase(base).table_exists(PATH) + assert DeltaTableDatabase(base).get_all_records(PATH) is None + assert DeltaTableDatabase(base).get_table_schema(PATH) is None + DeltaTableDatabase(base).add_record(PATH, b"a", pa.table({"x": [1]}), flush=True) + + records = DeltaTableDatabase(base).get_all_records(PATH) + assert records is not None and records.column("x").to_pylist() == [1] + assert note.read_bytes() == contents def test_missing_child_log_is_refused_inside_occupied_partition( diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index e727e45c2..d69817ca7 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -173,12 +173,14 @@ def test_s3_non_hive_orphan_is_refused_on_first_read_and_flush( assert {name: fs.cat_file(name) for name in fs.find(uri)} == before +@pytest.mark.parametrize("overwrite", [False, True], ids=["active", "retained"]) def test_s3_partition_path_accepts_independent_child( s3_base_uri: str, s3_storage_options: dict[str, str], monkeypatch: pytest.MonkeyPatch, + overwrite: bool, ) -> None: - """Objects registered in a parent's log are not orphaned at its partition.""" + """A healthy parent owns its active objects and those pending vacuum.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) path = ("parent",) partition = (*path, "tag1=a", "tag2=b") @@ -196,6 +198,21 @@ def test_s3_partition_path_accepts_independent_child( partition_by=["tag1", "tag2"], storage_options=s3_storage_options, ) + if overwrite: + deltalake.write_deltalake( + f"{s3_base_uri}/parent", + data.set_column(3, "x", pa.array([3])), + partition_by=["tag1", "tag2"], + mode="overwrite", + storage_options=s3_storage_options, + ) + fs = s3fs.S3FileSystem( + key=s3_storage_options["AWS_ACCESS_KEY_ID"], + secret=s3_storage_options["AWS_SECRET_ACCESS_KEY"], + client_kwargs={"endpoint_url": s3_storage_options["AWS_ENDPOINT_URL"]}, + use_listings_cache=False, + ) + assert len(fs.glob("/".join((s3_base_uri, *partition, "*.parquet")))) == 2 db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) assert not db.table_exists(partition) assert db.get_all_records(partition) is None @@ -205,7 +222,38 @@ def test_s3_partition_path_accepts_independent_child( child_rows = fresh.get_all_records(partition) assert child_rows is not None and child_rows.column("x").to_pylist() == [2] parent_rows = fresh.get_all_records(path) - assert parent_rows is not None and parent_rows.column("x").to_pylist() == [1] + assert parent_rows is not None + assert parent_rows.column("x").to_pylist() == [3 if overwrite else 1] + + +def test_s3_non_parquet_file_does_not_make_a_missing_table_unreadable( + s3_base_uri: str, + s3_storage_options: dict[str, str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An unrelated object ending in .parquet can coexist with a new table.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + fs = s3fs.S3FileSystem( + key=s3_storage_options["AWS_ACCESS_KEY_ID"], + secret=s3_storage_options["AWS_SECRET_ACCESS_KEY"], + client_kwargs={"endpoint_url": s3_storage_options["AWS_ENDPOINT_URL"]}, + use_listings_cache=False, + ) + path = ("table",) + note = f"{s3_base_uri}/table/note.parquet" + fs.pipe_file(note, b"PAR1 plain text") + + for query in ("table_exists", "get_all_records", "get_table_schema"): + fresh = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + assert getattr(fresh, query)(path) is ( + False if query == "table_exists" else None + ) + db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) + db.add_record(path, b"a", pa.table({"x": [1]}), flush=True) + + records = db.get_all_records(path) + assert records is not None and records.column("x").to_pylist() == [1] + assert fs.cat_file(note) == b"PAR1 plain text" def test_s3_skip_duplicates(s3_base_uri, s3_storage_options): From b8de858dafcf6774e095d2a03f7e4b09b6625fd9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:19:52 -0800 Subject: [PATCH 08/10] fix(databases): narrow missing Delta log detection --- changelog.d/ITL-916.md | 8 +- docs/dev/design_issues/ITL-916-DR2.md | 11 +- src/orcapod/databases/delta_lake_databases.py | 220 ++++++++---------- .../test_delta_read_failures.py | 164 ++++++++++--- .../test_delta_table_database_s3.py | 21 +- 5 files changed, 255 insertions(+), 169 deletions(-) diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md index d9083b0cd..3b4dce93e 100644 --- a/changelog.d/ITL-916.md +++ b/changelog.d/ITL-916.md @@ -1,7 +1,7 @@ ### Fixed -- Delta database reads and writes raise `OrcapodDatabaseReadError` when they - would otherwise treat a table with existing Parquet files and a missing or - unpublished transaction log as absent. This covers flat, partitioned, and - arbitrary nested data paths. The error names the table, and a refused flush +- Delta database reads and writes raise `OrcapodDatabaseReadError` when a + missing table path contains Parquet files directly or in Hive partition + subdirectories and neither the table nor an ancestor within the database has + transaction log content. The error names the table, and a refused flush leaves its files intact. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index abf2d6e91..de521aa0a 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -10,10 +10,11 @@ table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. **Fix:** When a read or write opens a Delta table and the backend reports it -missing, check the header and footer markers of candidate Parquet files at any -depth outside transaction logs and separately published child tables. A readable -ancestor log can identify its active files and retained files pending vacuum. -When unclaimed files exist, briefly retry opening -the log to give a concurrent first writer time to publish it, then raise +missing, check whether the table or any ancestor through the database root has +transaction log content. If none does, check for Parquet markers in regular +`.parquet` files at the table path and in its Hive partition subdirectories. +Skip inaccessible entries and subdirectories with their own log content. +When a candidate passes the marker check, briefly retry opening the log to +give a concurrent first writer time to publish it, then raise `OrcapodDatabaseReadError` if the log still cannot be opened. Discovery and cached reads keep their existing behavior. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 5de759fa1..82885d351 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -7,13 +7,12 @@ import sys import uuid from collections import defaultdict -from collections.abc import Callable, Collection, Iterator, Mapping +from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from dataclasses import dataclass from pathlib import Path, PurePosixPath from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast -from urllib.parse import unquote import polars as pl import pyarrow as pa @@ -86,7 +85,6 @@ # Directory that marks its parent directory as a Delta table. _DELTA_LOG_DIRECTORY = "_delta_log" -_DELTA_LOG_MARKERS = ("00000000000000000000.json", "_last_checkpoint") # A first writer can put its Parquet files in place before publishing version zero. _MISSING_LOG_RETRY_DELAYS = (0.02, 0.08, 0.2, 0.5) @@ -96,11 +94,25 @@ def _has_parquet_magic(file: BinaryIO | pa.NativeFile) -> bool: """Check the header and footer markers without reading the Parquet metadata.""" return ( file.read(4) == b"PAR1" - and file.seek(-4, os.SEEK_END) >= 8 + and file.seek(-4, os.SEEK_END) > 4 and file.read(4) == b"PAR1" ) +def _is_hive_partition(name: str) -> bool: + """Recognize the column=value syntax used by Hive partition directories.""" + return name.find("=") > 0 + + +def _local_delta_log_has_content(directory: Path) -> bool: + """Check for any entry in the log without interpreting its contents.""" + try: + with os.scandir(directory / _DELTA_LOG_DIRECTORY) as entries: + return next(entries, None) is not None + except FileNotFoundError: + return False + + # How many times a flush tries to commit a table's pending rows when other writers # keep committing first; after the last attempt it raises the last conflict # (ITL-1377). A writer that lost waits until the others pause: measured with 4 @@ -1989,132 +2001,98 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: ) from missing_log def _has_orphaned_delta_data_files(self, table_uri: str) -> bool: - """Check whether the missing table path holds data unclaimed by ancestors.""" - ancestor_files = self._ancestor_delta_data_paths(table_uri) - owned: set[str] = set() - for path in self._delta_data_paths(table_uri): - while path not in owned: - ancestor_file = next(ancestor_files, None) - if ancestor_file is None: - return True - owned.add(ancestor_file) - return False + """Look for Parquet in a location with no exact or ancestor log.""" + if self._is_cloud: + return self._has_orphaned_cloud_delta_data(table_uri) - def _ancestor_delta_data_paths(self, table_uri: str) -> Iterator[str]: - """Yield active files, then retained files recorded by ancestor tables.""" - from deltalake.exceptions import DeltaError + root = Path(os.path.abspath(self._local_root)) + table = Path(os.path.abspath(table_uri)) + if not table.is_relative_to(root): + return False + ancestors = [table, *(p for p in table.parents if p.is_relative_to(root))] + try: + if any(_local_delta_log_has_content(directory) for directory in ancestors): + return False + except OSError: + return False - if self._is_cloud: - scheme, separator, location = table_uri.partition("://") - uri_prefix = scheme + separator - table_path = PurePosixPath(location) - else: - uri_prefix = "" - table_path = Path(table_uri).absolute() - - ancestors: list[tuple[deltalake.DeltaTable, str]] = [] - for ancestor in table_path.parents: - if not ancestor.parts: - continue # A cloud URI must include its bucket or container. - if ( - isinstance(ancestor, Path) - and not (ancestor / _DELTA_LOG_DIRECTORY).is_dir() - ): - continue - ancestor_uri = uri_prefix + str(ancestor) - prefix = table_path.relative_to(ancestor).as_posix() + "/" - try: - table = deltalake.DeltaTable( - ancestor_uri, storage_options=self._storage_options or None - ) - actions = table.get_add_actions() - except DeltaError: - continue # Only a readable ancestor log can establish ownership. - ancestors.append((table, prefix)) - for path in actions.column("path").to_pylist(): - # Delta encodes AddFile paths, including '%' in Hive partition names. - relative_path = unquote(path) - if relative_path.startswith(prefix): - yield relative_path[len(prefix) :] - - for table, prefix in ancestors: + pending = [table] + while pending: + directory = pending.pop() try: - # A LITE dry run exposes removed files recorded in the log without - # claiming untracked files such as those of a damaged child. - removed = table.vacuum( - retention_hours=0, - dry_run=True, - enforce_retention_duration=False, - full=False, - ) - except DeltaError: - continue - for path in removed: - if path.startswith(prefix): - yield path[len(prefix) :] - - def _delta_data_paths(self, table_uri: str) -> Iterator[str]: - """Yield relative Parquet paths outside logs and published child tables.""" - if not self._is_cloud: - pending = [table_uri] - while pending: - directory = pending.pop() - if directory != table_uri and any( - os.path.isfile(os.path.join(directory, _DELTA_LOG_DIRECTORY, name)) - for name in _DELTA_LOG_MARKERS - ): + if directory != table and _local_delta_log_has_content(directory): continue - try: - with os.scandir(directory) as entries: - for entry in entries: - if entry.name == _DELTA_LOG_DIRECTORY: - continue - if entry.is_dir(follow_symlinks=False): - pending.append(entry.path) - elif entry.name.endswith(".parquet") and entry.is_file(): - try: - with open(entry.path, "rb") as file: - is_parquet = _has_parquet_magic(file) - except FileNotFoundError: - continue - if is_parquet: - yield ( - Path(entry.path) - .relative_to(table_uri) - .as_posix() - ) - except FileNotFoundError: - continue - return + with os.scandir(directory) as entries: + for entry in entries: + try: + if _is_hive_partition(entry.name) and entry.is_dir( + follow_symlinks=False + ): + pending.append(Path(entry.path)) + elif entry.name.endswith(".parquet") and entry.is_file( + follow_symlinks=False + ): + with open(entry.path, "rb") as file: + if _has_parquet_magic(file): + return True + except OSError: + continue + except OSError: + continue + return False + def _has_orphaned_cloud_delta_data(self, table_uri: str) -> bool: + """Inspect only the table and its Hive subdirectories in object storage.""" from deltalake.fs import DeltaStorageHandler from pyarrow.fs import FileSelector, FileType - handler = DeltaStorageHandler(table_uri, self._storage_options or None) - entries = handler.get_file_info_selector( - FileSelector("", recursive=True, allow_not_found=True) - ) - paths = [(entry.path.split("/"), entry.type) for entry in entries] - # A committed child log marks a separate table even when the store lists files only. - child_tables = { - tuple(parts[:-2]) - for parts, kind in paths - if kind == FileType.File - and len(parts) > 2 - and parts[-2] == _DELTA_LOG_DIRECTORY - and parts[-1] in _DELTA_LOG_MARKERS - } - for parts, kind in paths: - if kind != FileType.File or not parts[-1].endswith(".parquet"): + root = self._root_uri.rstrip("/") + if not table_uri.startswith(root + "/"): + return False + table = PurePosixPath(table_uri[len(root) + 1 :]) + + def has_log(directory: PurePosixPath) -> bool: + """Report whether this directory has any transaction log content.""" + log = str(directory / _DELTA_LOG_DIRECTORY) + return bool( + handler.get_file_info_selector(FileSelector(log, allow_not_found=True)) + ) + + try: + handler = DeltaStorageHandler(root, self._storage_options or None) + if any(has_log(directory) for directory in (table, *table.parents)): + return False + except Exception: # noqa: BLE001 # The storage backend also raises bare Exception. + return False + + pending = [table] + while pending: + directory = pending.pop() + try: + if directory != table and has_log(directory): + continue + entries = handler.get_file_info_selector( + FileSelector( + str(directory) if directory.parts else "", allow_not_found=True + ) + ) + except Exception: # noqa: BLE001 # A failed optional listing leaves a miss. continue - if _DELTA_LOG_DIRECTORY not in parts[:-1] and not any( - tuple(parts[:depth]) in child_tables for depth in range(1, len(parts)) - ): - path = "/".join(parts) - with handler.open_input_file(path) as file: - is_parquet = _has_parquet_magic(file) - if is_parquet: - yield path + for entry in entries: + if entry.type == FileType.Directory and _is_hive_partition( + entry.base_name + ): + pending.append(PurePosixPath(entry.path)) + elif entry.type == FileType.File and entry.base_name.endswith( + ".parquet" + ): + try: + with handler.open_input_file(entry.path) as file: + if _has_parquet_magic(file): + return True + except Exception: # noqa: BLE001 # A failed optional read is skipped. + continue + return False def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError: """Build the error for a table at ``record_path`` that exists but cannot be read. diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 49fc3c73e..3345f2dce 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -322,7 +322,7 @@ def test_partition_path_accepts_independent_child( assert parent_rows.column("x").to_pylist() == [3 if overwrite else 1] -@pytest.mark.parametrize("contents", [b"plain text", b"PAR1 plain text"]) +@pytest.mark.parametrize("contents", [b"plain text", b"PAR1 plain text", b"PAR1PAR1"]) def test_non_parquet_file_does_not_make_a_missing_table_unreadable( base: Path, monkeypatch: pytest.MonkeyPatch, contents: bytes ) -> None: @@ -343,11 +343,8 @@ def test_non_parquet_file_does_not_make_a_missing_table_unreadable( assert note.read_bytes() == contents -def test_missing_child_log_is_refused_inside_occupied_partition( - base: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A parent's files and a damaged child's files can share a partition.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) +def test_missing_child_log_under_parent_log_follows_main(base: Path) -> None: + """A child under an ancestor with a log can publish a replacement log.""" parent = ("parent",) child = (*parent, "tag1=a", "tag2=b") record_id = DeltaTableDatabase.RECORD_ID_COLUMN @@ -360,13 +357,11 @@ def test_missing_child_log_is_refused_inside_occupied_partition( shutil.rmtree(directory / "_delta_log") before = snapshot(directory) - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): - DeltaTableDatabase(base).get_all_records(child) - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): - DeltaTableDatabase(base).add_record( - child, b"c", pa.table({"x": [3]}), flush=True - ) - assert snapshot(directory) == before + assert DeltaTableDatabase(base).get_all_records(child) is None + DeltaTableDatabase(base).add_record(child, b"c", pa.table({"x": [3]}), flush=True) + records = DeltaTableDatabase(base).get_all_records(child) + assert records is not None and records.column("x").to_pylist() == [3] + assert all((directory / path).read_bytes() == data for path, data in before.items()) def move_delta_data_file(directory: Path) -> Path: @@ -385,33 +380,148 @@ def move_delta_data_file(directory: Path) -> Path: return moved -@pytest.mark.parametrize("write", [False, True], ids=["read", "flush"]) -def test_missing_log_with_non_hive_data_path( - base: Path, monkeypatch: pytest.MonkeyPatch, write: bool -) -> None: - """A valid AddFile path can contain arbitrary directory components.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) +def test_missing_log_with_non_hive_data_path_follows_main(base: Path) -> None: + """Parquet below a non-partition folder does not stop a replacement write.""" directory = table_dir(base) data = pa.table({DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], "x": [1]}) deltalake.write_deltalake(directory, data) - _ = move_delta_data_file(directory) + moved = move_delta_data_file(directory) db = DeltaTableDatabase(base_path=base) original_rows = db.get_all_records(PATH) assert original_rows is not None and original_rows.column("x").to_pylist() == [1] shutil.rmtree(directory / "_delta_log") - before = snapshot(directory) + before = moved.read_bytes() fresh = DeltaTableDatabase(base_path=base) + assert fresh.get_all_records(PATH) is None + fresh.add_record(PATH, b"b", pa.table({"x": [2]}), flush=True) + records = DeltaTableDatabase(base).get_all_records(PATH) + assert records is not None and records.column("x").to_pylist() == [2] + assert moved.read_bytes() == before - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - if write: - fresh.add_record(PATH, b"b", pa.table({"x": [2]}), flush=True) - else: - fresh.get_all_records(PATH) - assert info.value.record_path == PATH + +def test_partition_path_accepts_independent_child_after_delta_cleanup( + base: Path, +) -> None: + """Log and tombstone expiry leave the parent's partition available.""" + parent = ("parent",) + partition = (*parent, "tag1=a", "tag2=b") + directory = base.joinpath(*parent) + data = pa.table( + { + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag1": ["a"], + "tag2": ["b"], + "x": [1], + "y": [2], + } + ) + partitions = ["tag1", "tag2"] + deltalake.write_deltalake( + directory, + data, + partition_by=partitions, + configuration={ + "delta.logRetentionDuration": "interval 0 seconds", + "delta.deletedFileRetentionDuration": "interval 0 seconds", + }, + ) + retired = next(base.joinpath(*partition).glob("*.parquet")) + deltalake.write_deltalake( + directory, data, mode="overwrite", partition_by=partitions + ) + deltalake.write_deltalake(directory, data, mode="append", partition_by=partitions) + table = deltalake.DeltaTable(directory) + table.create_checkpoint() + table.cleanup_metadata() + assert not (directory / "_delta_log" / "00000000000000000000.json").exists() + assert retired.is_file() + parent_rows = DeltaTableDatabase(base).get_all_records(parent) + assert parent_rows is not None and parent_rows.num_rows == 2 + + assert not DeltaTableDatabase(base).table_exists(partition) + DeltaTableDatabase(base).add_record( + partition, b"b", pa.table({"x": [3], "y": [4]}), flush=True + ) + child = DeltaTableDatabase(base).get_all_records(partition) + assert child is not None and child.to_pylist() == [{"x": 3, "y": 4}] + + +@pytest.mark.parametrize("name", ["private", "tag=private"]) +def test_new_table_can_coexist_with_unreadable_directory(base: Path, name: str) -> None: + """An unreadable subdirectory leaves the surrounding location usable.""" + denied = table_dir(base) / name + denied.mkdir(parents=True) + _ = (denied / "note.txt").write_text("unrelated") + denied.chmod(0) + try: + if os.access(denied, os.R_OK): + pytest.skip("This process can read directories with mode 000") + assert not DeltaTableDatabase(base).table_exists(PATH) + DeltaTableDatabase(base).add_record( + PATH, b"a", pa.table({"x": [1]}), flush=True + ) + finally: + denied.chmod(0o700) + assert (denied / "note.txt").read_text() == "unrelated" + assert DeltaTableDatabase(base).table_exists(PATH) + + +@pytest.mark.parametrize("name", ["child", "tag=child"]) +def test_parent_can_be_created_above_checkpointed_child(base: Path, name: str) -> None: + """A child remains independent even after Delta cleans old commit markers.""" + child = (*PATH, name) + directory = base.joinpath(*child) + data = pa.table({"x": [1], "y": [2]}) + deltalake.write_deltalake( + directory, + data, + configuration={"delta.logRetentionDuration": "interval 0 seconds"}, + ) + deltalake.write_deltalake(directory, data, mode="append") + table = deltalake.DeltaTable(directory) + table.create_checkpoint() + table.cleanup_metadata() + log = directory / "_delta_log" + (log / "_last_checkpoint").unlink() + assert sorted(path.name for path in log.iterdir()) == [ + "00000000000000000001.checkpoint.parquet", + "00000000000000000001.json", + ] + child_rows = DeltaTableDatabase(base).get_all_records(child) + assert child_rows is not None and child_rows.num_rows == 2 + before = snapshot(directory) + + assert not DeltaTableDatabase(base).table_exists(PATH) + DeltaTableDatabase(base).add_record(PATH, b"a", pa.table({"x": [3]}), flush=True) + assert DeltaTableDatabase(base).table_exists(PATH) assert snapshot(directory) == before +def test_read_below_regular_file_reports_missing_table(base: Path) -> None: + """A backend miss stays a miss when an intermediate component is a file.""" + base.mkdir() + _ = (base / "file").write_text("unrelated") + assert DeltaTableDatabase(base).get_all_records(("file", "child")) is None + + +def test_plain_text_with_both_parquet_magic_markers_is_a_candidate(base: Path) -> None: + """A file passing the two-marker check can be a false positive.""" + directory = table_dir(base) + directory.mkdir(parents=True) + note = directory / "note.parquet" + contents = b"PAR1 This is a plain-text note ending in PAR1" + _ = note.write_bytes(contents) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): + DeltaTableDatabase(base).table_exists(PATH) + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): + DeltaTableDatabase(base).add_record( + PATH, b"a", pa.table({"x": [1]}), flush=True + ) + assert snapshot(directory) == {"note.parquet": contents} + + @pytest.mark.parametrize("listing", ["list_table_paths", "list_sources"]) def test_discovery_keeps_a_table_with_retained_non_hive_data( base: Path, listing: str diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index d69817ca7..af645ad15 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -123,12 +123,12 @@ def test_s3_table_with_missing_log_is_refused( assert {name: fs.cat_file(name) for name in fs.find(uri)} == before -def test_s3_non_hive_orphan_is_refused_on_first_read_and_flush( +def test_s3_non_hive_data_path_follows_main( s3_base_uri: str, s3_storage_options: dict[str, str], monkeypatch: pytest.MonkeyPatch, ) -> None: - """The Delta storage backend finds data at arbitrary depth after a miss.""" + """Parquet below a non-partition prefix does not stop a replacement write.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) path = ("table",) uri = f"{s3_base_uri}/table" @@ -161,16 +161,13 @@ def test_s3_non_hive_orphan_is_refused_on_first_read_and_flush( before = {name: fs.cat_file(name) for name in fs.find(uri)} assert len(before) == 1 - for operation in ( - lambda: fresh.get_all_records(path), - lambda: writer_with_cached_miss.add_record( - path, b"b", pa.table({"x": [2]}), flush=True - ), - ): - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - operation() - assert info.value.record_path == path - assert {name: fs.cat_file(name) for name in fs.find(uri)} == before + assert fresh.get_all_records(path) is None + writer_with_cached_miss.add_record(path, b"b", pa.table({"x": [2]}), flush=True) + records = DeltaTableDatabase( + s3_base_uri, storage_options=s3_storage_options + ).get_all_records(path) + assert records is not None and records.column("x").to_pylist() == [2] + assert {name: fs.cat_file(name) for name in before} == before @pytest.mark.parametrize("overwrite", [False, True], ids=["active", "retained"]) From 440f562b97639be4a9b5f26b16d02b87720208e7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:29:12 -0800 Subject: [PATCH 09/10] fix(databases): preserve Delta alias and object-store misses --- changelog.d/ITL-916.md | 12 +- docs/dev/design_issues/ITL-916-DR2.md | 18 +-- src/orcapod/databases/delta_lake_databases.py | 140 ++++++------------ .../test_delta_read_failures.py | 87 ++++++++++- .../test_delta_table_database_s3.py | 34 ++--- 5 files changed, 163 insertions(+), 128 deletions(-) diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md index 3b4dce93e..8640979a9 100644 --- a/changelog.d/ITL-916.md +++ b/changelog.d/ITL-916.md @@ -1,7 +1,11 @@ ### Fixed -- Delta database reads and writes raise `OrcapodDatabaseReadError` when a +- Local Delta database reads and writes raise `OrcapodDatabaseReadError` when a missing table path contains Parquet files directly or in Hive partition - subdirectories and neither the table nor an ancestor within the database has - transaction log content. The error names the table, and a refused flush - leaves its files intact. + subdirectories and no transaction log content is found at the table path or + its ancestors, including through a directory alias. The error names the + table, and a refused flush leaves its files intact. + +### Known limitations + +- Delta tables on object stores skip this missing-log check. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index de521aa0a..1929e14da 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -9,12 +9,12 @@ Removing `_delta_log` from a table with stored rows made reads report an absent table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. -**Fix:** When a read or write opens a Delta table and the backend reports it -missing, check whether the table or any ancestor through the database root has -transaction log content. If none does, check for Parquet markers in regular -`.parquet` files at the table path and in its Hive partition subdirectories. -Skip inaccessible entries and subdirectories with their own log content. -When a candidate passes the marker check, briefly retry opening the log to -give a concurrent first writer time to publish it, then raise -`OrcapodDatabaseReadError` if the log still cannot be opened. Discovery and -cached reads keep their existing behavior. +**Fix:** When a local read or write opens a Delta table and the backend reports +it missing, check for Parquet markers in regular `.parquet` files at the table +path and in its Hive partition subdirectories. Skip inaccessible entries and +subdirectories with their own log content. If a candidate passes the marker +check, look for transaction log content at the table path and its ancestors +through the database root, including the resolved location of a directory +alias. If none is found, briefly retry opening the log to give a concurrent +first writer time to publish it, then raise `OrcapodDatabaseReadError` if the log +still cannot be opened. Object stores skip the Parquet check. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 82885d351..6fef28ec7 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -10,7 +10,7 @@ from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from dataclasses import dataclass -from pathlib import Path, PurePosixPath +from pathlib import Path from time import sleep from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast @@ -90,7 +90,7 @@ _MISSING_LOG_RETRY_DELAYS = (0.02, 0.08, 0.2, 0.5) -def _has_parquet_magic(file: BinaryIO | pa.NativeFile) -> bool: +def _has_parquet_magic(file: BinaryIO) -> bool: """Check the header and footer markers without reading the Parquet metadata.""" return ( file.read(4) == b"PAR1" @@ -113,6 +113,34 @@ def _local_delta_log_has_content(directory: Path) -> bool: return False +def _local_delta_data_has_parquet(table: Path) -> bool: + """Look for Parquet directly in the table and in unlogged Hive partitions.""" + pending = [table] + while pending: + directory = pending.pop() + try: + if directory != table and _local_delta_log_has_content(directory): + continue + with os.scandir(directory) as entries: + for entry in entries: + try: + if _is_hive_partition(entry.name) and entry.is_dir( + follow_symlinks=False + ): + pending.append(Path(entry.path)) + elif entry.name.endswith(".parquet") and entry.is_file( + follow_symlinks=False + ): + with open(entry.path, "rb") as file: + if _has_parquet_magic(file): + return True + except OSError: + continue + except OSError: + continue + return False + + # How many times a flush tries to commit a table's pending rows when other writers # keep committing first; after the last attempt it raises the last conflict # (ITL-1377). A writer that lost waits until the others pause: measured with 4 @@ -1971,13 +1999,13 @@ def _get_delta_table( return delta_table def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: - """Open the current Delta log, checking a missing log for existing data. + """Open the current Delta log, checking a local miss for existing data. Args: table_uri: The table's storage location. Returns: - The loaded table, or ``None`` when neither a log nor data files exist. + The loaded table, or ``None`` for a miss without detected orphaned data. Raises: FileNotFoundError: If the folder holds data files and the log is missing. @@ -1988,7 +2016,7 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: try: return deltalake.DeltaTable(table_uri, storage_options=options) except TableNotFoundError as missing_log: - if not self._has_orphaned_delta_data_files(table_uri): + if self._is_cloud or not self._has_orphaned_delta_data_files(table_uri): return None for delay in _MISSING_LOG_RETRY_DELAYS: sleep(delay) @@ -2001,98 +2029,28 @@ def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: ) from missing_log def _has_orphaned_delta_data_files(self, table_uri: str) -> bool: - """Look for Parquet in a location with no exact or ancestor log.""" - if self._is_cloud: - return self._has_orphaned_cloud_delta_data(table_uri) - + """Check a local candidate for a log at its path or an ancestor.""" root = Path(os.path.abspath(self._local_root)) table = Path(os.path.abspath(table_uri)) - if not table.is_relative_to(root): - return False - ancestors = [table, *(p for p in table.parents if p.is_relative_to(root))] - try: - if any(_local_delta_log_has_content(directory) for directory in ancestors): - return False - except OSError: + if not table.is_relative_to(root) or not _local_delta_data_has_parquet(table): return False - pending = [table] - while pending: - directory = pending.pop() - try: - if directory != table and _local_delta_log_has_content(directory): - continue - with os.scandir(directory) as entries: - for entry in entries: - try: - if _is_hive_partition(entry.name) and entry.is_dir( - follow_symlinks=False - ): - pending.append(Path(entry.path)) - elif entry.name.endswith(".parquet") and entry.is_file( - follow_symlinks=False - ): - with open(entry.path, "rb") as file: - if _has_parquet_magic(file): - return True - except OSError: - continue - except OSError: - continue - return False - - def _has_orphaned_cloud_delta_data(self, table_uri: str) -> bool: - """Inspect only the table and its Hive subdirectories in object storage.""" - from deltalake.fs import DeltaStorageHandler - from pyarrow.fs import FileSelector, FileType - - root = self._root_uri.rstrip("/") - if not table_uri.startswith(root + "/"): - return False - table = PurePosixPath(table_uri[len(root) + 1 :]) - - def has_log(directory: PurePosixPath) -> bool: - """Report whether this directory has any transaction log content.""" - log = str(directory / _DELTA_LOG_DIRECTORY) - return bool( - handler.get_file_info_selector(FileSelector(log, allow_not_found=True)) - ) - + directories = {table, *(p for p in table.parents if p.is_relative_to(root))} try: - handler = DeltaStorageHandler(root, self._storage_options or None) - if any(has_log(directory) for directory in (table, *table.parents)): - return False - except Exception: # noqa: BLE001 # The storage backend also raises bare Exception. - return False - - pending = [table] - while pending: - directory = pending.pop() - try: - if directory != table and has_log(directory): - continue - entries = handler.get_file_info_selector( - FileSelector( - str(directory) if directory.parts else "", allow_not_found=True - ) + resolved = table.resolve() + resolved_root = root.resolve() + directories.add(resolved) + if resolved.is_relative_to(resolved_root): + directories.update( + p for p in resolved.parents if p.is_relative_to(resolved_root) ) - except Exception: # noqa: BLE001 # A failed optional listing leaves a miss. - continue - for entry in entries: - if entry.type == FileType.Directory and _is_hive_partition( - entry.base_name - ): - pending.append(PurePosixPath(entry.path)) - elif entry.type == FileType.File and entry.base_name.endswith( - ".parquet" - ): - try: - with handler.open_input_file(entry.path) as file: - if _has_parquet_magic(file): - return True - except Exception: # noqa: BLE001 # A failed optional read is skipped. - continue - return False + else: + # An alias can point into a partition of a table outside this store. + directories.update(resolved.parents) + return not any(_local_delta_log_has_content(path) for path in directories) + except (OSError, RuntimeError): + # Path.resolve raises RuntimeError for symlink loops on Python 3.11/3.12. + return False def _read_failed(self, record_path: tuple[str, ...]) -> OrcapodDatabaseReadError: """Build the error for a table at ``record_path`` that exists but cannot be read. diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index 3345f2dce..c272ed713 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -26,8 +26,10 @@ from collections.abc import Callable from pathlib import Path from typing import Any +from unittest.mock import Mock, patch import deltalake +import deltalake.fs import pyarrow as pa import pytest from deltalake.exceptions import DeltaProtocolError @@ -322,6 +324,86 @@ def test_partition_path_accepts_independent_child( assert parent_rows.column("x").to_pylist() == [3 if overwrite else 1] +@pytest.mark.parametrize("parent_outside_root", [False, True]) +@pytest.mark.parametrize("operation", ["exists", "create"]) +def test_partition_alias_accepts_independent_child( + base: Path, + monkeypatch: pytest.MonkeyPatch, + parent_outside_root: bool, + operation: str, +) -> None: + """A partition reached through an alias is still owned by its parent.""" + monkeypatch.setattr( + delta_lake_databases, "sleep", Mock(return_value=None), raising=False + ) + base.mkdir() + parent = (base.parent if parent_outside_root else base) / "parent" + data = pa.table( + { + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag1": ["a"], + "tag2": ["b"], + "x": [1], + } + ) + deltalake.write_deltalake(parent, data, partition_by=["tag1", "tag2"]) + try: + (base / "alias").symlink_to( + parent / "tag1=a" / "tag2=b", target_is_directory=True + ) + except OSError as exc: + pytest.skip(f"Directory symlinks unavailable: {exc}") + + db = DeltaTableDatabase(base) + if operation == "exists": + assert not db.table_exists(("alias",)) + else: + db.add_record(("alias",), b"b", pa.table({"x": [2]}), flush=True) + child_rows = DeltaTableDatabase(base).get_all_records(("alias",)) + assert child_rows is not None and child_rows.column("x").to_pylist() == [2] + parent_rows = DeltaTableDatabase(parent.parent).get_all_records((parent.name,)) + assert parent_rows is not None and parent_rows.column("x").to_pylist() == [1] + + +def test_empty_local_delta_lookup_lists_only_the_table_directory(base: Path) -> None: + """A cold miss in an empty local directory does not need ancestor listings.""" + path = ("n1", "n2", "table") + directory = base.joinpath(*path) + directory.mkdir(parents=True) + with patch.object(os, "scandir", wraps=os.scandir) as scandir: + assert not DeltaTableDatabase(base).table_exists(path) + assert scandir.call_count <= 1 + + +def test_cold_cloud_delta_lookup_adds_no_selector_listings(base: Path) -> None: + """A cold cloud miss needs only the backend's native Delta open.""" + root = "s3://example-bucket/store" + path = ("n1", "n2", "table") + uri = "/".join((root, *path)) + directory = base.joinpath(*path) + directory.mkdir(parents=True) + native_table = deltalake.DeltaTable + handler_type = deltalake.fs.DeltaStorageHandler + handler = handler_type(str(base)) + + def load( + table_uri: str, storage_options: dict[str, str] | None = None + ) -> deltalake.DeltaTable: + """Give the native Delta open an empty directory without contacting S3.""" + assert table_uri == uri + return native_table(directory, storage_options=storage_options) + + with ( + patch.object(deltalake, "DeltaTable", side_effect=load), + patch.object( + handler_type, "get_file_info_selector", wraps=handler.get_file_info_selector + ) as selector, + patch.object(deltalake.fs, "DeltaStorageHandler", return_value=handler), + ): + assert not DeltaTableDatabase(root).table_exists(path) + selector.assert_not_called() + + @pytest.mark.parametrize("contents", [b"plain text", b"PAR1 plain text", b"PAR1PAR1"]) def test_non_parquet_file_does_not_make_a_missing_table_unreadable( base: Path, monkeypatch: pytest.MonkeyPatch, contents: bytes @@ -505,8 +587,11 @@ def test_read_below_regular_file_reports_missing_table(base: Path) -> None: assert DeltaTableDatabase(base).get_all_records(("file", "child")) is None -def test_plain_text_with_both_parquet_magic_markers_is_a_candidate(base: Path) -> None: +def test_plain_text_with_both_parquet_magic_markers_is_a_candidate( + base: Path, monkeypatch: pytest.MonkeyPatch +) -> None: """A file passing the two-marker check can be a false positive.""" + monkeypatch.setattr(delta_lake_databases, "sleep", Mock(return_value=None)) directory = table_dir(base) directory.mkdir(parents=True) note = directory / "note.parquet" diff --git a/tests/test_databases/test_delta_table_database_s3.py b/tests/test_databases/test_delta_table_database_s3.py index af645ad15..ba6a1a497 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -22,8 +22,6 @@ from upath import UPath from orcapod.databases import DeltaTableDatabase -from orcapod.databases import delta_lake_databases -from orcapod.errors import OrcapodDatabaseReadError pytestmark = pytest.mark.s3 @@ -72,15 +70,13 @@ def test_s3_flush_and_read(s3_base_uri, s3_storage_options): [None, ["tag1", "tag2"], ["tag2", "tag1"]], ids=["flat", "partitioned", "reordered-partitions"], ) -def test_s3_table_with_missing_log_is_refused( +def test_s3_table_with_missing_log_follows_main( s3_base_uri: str, s3_storage_options: dict[str, str], - monkeypatch: pytest.MonkeyPatch, path: tuple[str, ...], partitions: list[str] | None, ) -> None: - """Cloud reads, metadata and flushes refuse a missing log and preserve the objects.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + """A missing cloud log allows a replacement write alongside the old object.""" uri = "/".join((s3_base_uri,) + path) data = pa.table( { @@ -110,26 +106,22 @@ def test_s3_table_with_missing_log_is_refused( assert len(before) == 1 and next(iter(before)).endswith(".parquet") fresh = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) - for operation in ( - lambda: fresh.get_all_records(path), - lambda: fresh.get_table_schema(path), - lambda: fresh.table_exists(path), - lambda: fresh.add_record(path, b"b", pa.table({"v": [2]}), flush=True), - ): - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - _ = operation() - assert info.value.table == uri - assert info.value.record_path == path - assert {name: fs.cat_file(name) for name in fs.find(uri)} == before + assert fresh.get_all_records(path) is None + assert fresh.get_table_schema(path) is None + assert not fresh.table_exists(path) + fresh.add_record(path, b"b", pa.table({"x": [3]}), flush=True) + records = DeltaTableDatabase( + s3_base_uri, storage_options=s3_storage_options + ).get_all_records(path) + assert records is not None and records.column("x").to_pylist() == [3] + assert {name: fs.cat_file(name) for name in before} == before def test_s3_non_hive_data_path_follows_main( s3_base_uri: str, s3_storage_options: dict[str, str], - monkeypatch: pytest.MonkeyPatch, ) -> None: """Parquet below a non-partition prefix does not stop a replacement write.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) path = ("table",) uri = f"{s3_base_uri}/table" writer_with_cached_miss = DeltaTableDatabase( @@ -174,11 +166,9 @@ def test_s3_non_hive_data_path_follows_main( def test_s3_partition_path_accepts_independent_child( s3_base_uri: str, s3_storage_options: dict[str, str], - monkeypatch: pytest.MonkeyPatch, overwrite: bool, ) -> None: """A healthy parent owns its active objects and those pending vacuum.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) path = ("parent",) partition = (*path, "tag1=a", "tag2=b") data = pa.table( @@ -226,10 +216,8 @@ def test_s3_partition_path_accepts_independent_child( def test_s3_non_parquet_file_does_not_make_a_missing_table_unreadable( s3_base_uri: str, s3_storage_options: dict[str, str], - monkeypatch: pytest.MonkeyPatch, ) -> None: """An unrelated object ending in .parquet can coexist with a new table.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) fs = s3fs.S3FileSystem( key=s3_storage_options["AWS_ACCESS_KEY_ID"], secret=s3_storage_options["AWS_SECRET_ACCESS_KEY"], From 878ff4e26fcc05a996807ee7f0de10d8896c32a4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 10:43:17 -0800 Subject: [PATCH 10/10] fix(databases): check orphaned Delta files only before creation --- changelog.d/ITL-916.md | 15 ++-- docs/dev/design_issues/ITL-916-DR2.md | 19 ++-- src/orcapod/databases/delta_lake_databases.py | 60 +++++++------ .../test_delta_read_failures.py | 90 ++++++++++++++----- 4 files changed, 117 insertions(+), 67 deletions(-) diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md index 8640979a9..4d7a1f35b 100644 --- a/changelog.d/ITL-916.md +++ b/changelog.d/ITL-916.md @@ -1,11 +1,14 @@ ### Fixed -- Local Delta database reads and writes raise `OrcapodDatabaseReadError` when a - missing table path contains Parquet files directly or in Hive partition - subdirectories and no transaction log content is found at the table path or - its ancestors, including through a directory alias. The error names the - table, and a refused flush leaves its files intact. +- A flush that would create a local Delta table raises + `OrcapodDatabaseReadError` when it finds Parquet data directly in the table + folder or in Hive partition subdirectories and no transaction log content at + the path or along its ancestors up to the filesystem root. The check includes + resolved directory aliases. The error names the table and the flush leaves + the existing files intact. ### Known limitations -- Delta tables on object stores skip this missing-log check. +- A fresh read of a Delta table folder with Parquet data and no log still + reports an absent table. +- Delta tables on object stores skip the creation check. diff --git a/docs/dev/design_issues/ITL-916-DR2.md b/docs/dev/design_issues/ITL-916-DR2.md index 1929e14da..70976f553 100644 --- a/docs/dev/design_issues/ITL-916-DR2.md +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -9,12 +9,13 @@ Removing `_delta_log` from a table with stored rows made reads report an absent table. A later flush could create a new log that did not reference the original Parquet files, silently leaving their rows out of the table. -**Fix:** When a local read or write opens a Delta table and the backend reports -it missing, check for Parquet markers in regular `.parquet` files at the table -path and in its Hive partition subdirectories. Skip inaccessible entries and -subdirectories with their own log content. If a candidate passes the marker -check, look for transaction log content at the table path and its ancestors -through the database root, including the resolved location of a directory -alias. If none is found, briefly retry opening the log to give a concurrent -first writer time to publish it, then raise `OrcapodDatabaseReadError` if the log -still cannot be opened. Object stores skip the Parquet check. +**Fix:** Before a flush would create a local Delta table, check for Parquet +markers in regular `.parquet` files at the table path and in its Hive partition +subdirectories. Skip inaccessible entries and subdirectories with their own log +content. After finding the first candidate, look for transaction log content at +the table path and along its ancestors up to the filesystem root, including the +resolved location of a directory alias. If none is found, briefly retry opening +the log to give a concurrent first writer time to publish it. If the backend +still reports the table missing, raise `OrcapodDatabaseReadError` and preserve +the existing files. A log-less folder still reads as absent, and object stores +skip the creation check. diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 6fef28ec7..9e2877228 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1984,28 +1984,32 @@ def _get_delta_table( return None try: - delta_table = self._load_delta_table(table_uri) + delta_table = deltalake.DeltaTable( + table_uri, storage_options=self._storage_options or None + ) + self._delta_table_cache[record_key] = delta_table + logger.debug(f"Loaded existing Delta table for {record_key}") + return delta_table + except deltalake.exceptions.TableNotFoundError: + # Table doesn't exist: remembered until the next flush (ITL-1173). + self._absent_tables.add(record_key) + return None except Exception as e: # The table exists but could not be loaded: never report it as absent. self._delta_table_cache.pop(record_key, None) raise self._read_failed(record_path) from e - if delta_table is None: - # Table doesn't exist: remembered until the next flush (ITL-1173). - self._absent_tables.add(record_key) - else: - self._delta_table_cache[record_key] = delta_table - logger.debug(f"Loaded existing Delta table for {record_key}") - return delta_table - - def _load_delta_table(self, table_uri: str) -> deltalake.DeltaTable | None: - """Open the current Delta log, checking a local miss for existing data. + def _load_delta_table_for_commit( + self, table_uri: str + ) -> deltalake.DeltaTable | None: + """Load the current log or check that the table can safely be created. Args: table_uri: The table's storage location. Returns: - The loaded table, or ``None`` for a miss without detected orphaned data. + The loaded table, or ``None`` if the backend reports it missing and + the creation check finds no orphaned data. Raises: FileNotFoundError: If the folder holds data files and the log is missing. @@ -2035,18 +2039,13 @@ def _has_orphaned_delta_data_files(self, table_uri: str) -> bool: if not table.is_relative_to(root) or not _local_delta_data_has_parquet(table): return False - directories = {table, *(p for p in table.parents if p.is_relative_to(root))} try: resolved = table.resolve() - resolved_root = root.resolve() - directories.add(resolved) - if resolved.is_relative_to(resolved_root): - directories.update( - p for p in resolved.parents if p.is_relative_to(resolved_root) - ) - else: - # An alias can point into a partition of a table outside this store. - directories.update(resolved.parents) + # A database root or an alias can sit inside another table's partition. + # Check both chains up to the filesystem root, nearest directories first. + directories = dict.fromkeys( + (resolved, *resolved.parents, table, *table.parents) + ) return not any(_local_delta_log_has_content(path) for path in directories) except (OSError, RuntimeError): # Path.resolve raises RuntimeError for symlink loops on Python 3.11/3.12. @@ -2206,14 +2205,19 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the latest Delta schema from the log or the table's first batch.""" + from deltalake.exceptions import TableNotFoundError + try: - table = self._load_delta_table(self._get_table_uri(record_path)) - if table is not None: - return pa.schema(_held_columns(table).values()) + table = deltalake.DeltaTable( + self._get_table_uri(record_path), + storage_options=self._storage_options or None, + ) + return pa.schema(_held_columns(table).values()) + except TableNotFoundError: + pending = self._pending_batches.get(self._get_record_key(record_path)) + return None if pending is None else pending.schema except Exception as exc: raise self._read_failed(record_path) from exc - pending = self._pending_batches.get(self._get_record_key(record_path)) - return None if pending is None else pending.schema def _ensure_record_id_column( self, arrow_data: pa.Table, record_id: str | bytes @@ -3897,7 +3901,7 @@ def _commit_once( # form with its type recorded (ITL-928). combined_table = to_delta_layout(original_table) try: - delta_table = self._load_delta_table(table_uri) + delta_table = self._load_delta_table_for_commit(table_uri) except Exception as load_error: raise OrcapodDatabaseReadError( table_uri, abs_path_components diff --git a/tests/test_databases/test_delta_read_failures.py b/tests/test_databases/test_delta_read_failures.py index c272ed713..716a90786 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -170,10 +170,8 @@ def damaged_store( base: Path, damaged_path: tuple[str, ...], request: pytest.FixtureRequest, - monkeypatch: pytest.MonkeyPatch, ) -> DeltaTableDatabase: """Return a fresh handle after dropping the log from a populated table.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) directory = base.joinpath(*damaged_path) data = pa.table( { @@ -222,15 +220,14 @@ def damaged_store( @pytest.mark.parametrize( "read", MISSING_LOG_READS.values(), ids=list(MISSING_LOG_READS) ) -def test_missing_log_is_a_read_error( +def test_missing_log_reads_as_absent( damaged_path: tuple[str, ...], damaged_store: DeltaTableDatabase, read: Callable[[DeltaTableDatabase, tuple[str, ...]], object], ) -> None: - """Reads and table metadata queries name the table with orphaned data.""" - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - _ = read(damaged_store, damaged_path) - assert info.value.record_path == damaged_path + """Reads and metadata queries retain the backend's missing-table result.""" + result = read(damaged_store, damaged_path) + assert result is (False if read is MISSING_LOG_READS["table_exists"] else None) def test_table_exists_uses_the_loaded_snapshot( @@ -252,8 +249,10 @@ def test_flush_refuses_a_missing_log( base: Path, damaged_path: tuple[str, ...], damaged_store: DeltaTableDatabase, + monkeypatch: pytest.MonkeyPatch, ) -> None: """Flushing to a folder with orphaned data writes no files or log.""" + monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) directory = base.joinpath(*damaged_path) before = snapshot(directory) damaged_store.add_records( @@ -281,11 +280,20 @@ def test_partition_paths_do_not_count_as_separate_tables(base: Path, name: str) @pytest.mark.parametrize("operation", ["exists", "read", "schema", "create"]) @pytest.mark.parametrize("overwrite", [False, True], ids=["active", "retained"]) +@pytest.mark.parametrize( + "database_at_partition", [False, True], ids=["scoped", "rooted"] +) def test_partition_path_accepts_independent_child( - base: Path, monkeypatch: pytest.MonkeyPatch, operation: str, overwrite: bool + base: Path, + monkeypatch: pytest.MonkeyPatch, + operation: str, + overwrite: bool, + database_at_partition: bool, ) -> None: """A parent's active and retired files leave its partition usable as a child.""" - monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) + monkeypatch.setattr( + delta_lake_databases, "sleep", lambda _delay: None, raising=False + ) parent = ("group", "table") partition = (*parent, "tag1=a", "tag2=b") data = pa.table( @@ -307,7 +315,11 @@ def test_partition_path_accepts_independent_child( mode="overwrite", ) assert len(list(base.joinpath(*partition).glob("*.parquet"))) == 2 - db = DeltaTableDatabase(base).at(*partition[:-1]) + db = ( + DeltaTableDatabase(base.joinpath(*partition[:-1])) + if database_at_partition + else DeltaTableDatabase(base).at(*partition[:-1]) + ) child = partition[-1:] if operation == "exists": assert not db.table_exists(child) @@ -317,7 +329,7 @@ def test_partition_path_accepts_independent_child( assert db.get_table_schema(child) is None else: db.add_record(child, b"b", pa.table({"x": [2]}), flush=True) - child_rows = DeltaTableDatabase(base).get_all_records(partition) + child_rows = db.get_all_records(child) assert child_rows is not None and child_rows.column("x").to_pylist() == [2] parent_rows = DeltaTableDatabase(base).get_all_records(parent) assert parent_rows is not None @@ -365,14 +377,41 @@ def test_partition_alias_accepts_independent_child( assert parent_rows is not None and parent_rows.column("x").to_pylist() == [1] -def test_empty_local_delta_lookup_lists_only_the_table_directory(base: Path) -> None: - """A cold miss in an empty local directory does not need ancestor listings.""" - path = ("n1", "n2", "table") - directory = base.joinpath(*path) - directory.mkdir(parents=True) - with patch.object(os, "scandir", wraps=os.scandir) as scandir: - assert not DeltaTableDatabase(base).table_exists(path) - assert scandir.call_count <= 1 +@pytest.mark.parametrize("layout", ["empty", "partition", "logged_children"]) +@pytest.mark.parametrize("operation", ["exists", "read", "schema"]) +def test_cold_local_delta_miss_adds_no_filesystem_calls( + base: Path, layout: str, operation: str +) -> None: + """Match main's zero Python listings and file opens on a cold miss.""" + path = PATH + if layout == "empty": + table_dir(base).mkdir(parents=True) + elif layout == "partition": + deltalake.write_deltalake( + table_dir(base), pa.table({"tag": ["a"], "x": [1]}), partition_by=["tag"] + ) + path = (*PATH, "tag=a") + else: + for index in range(20): + deltalake.write_deltalake( + table_dir(base) / f"tag={index}", pa.table({"x": [index]}) + ) + + db = DeltaTableDatabase(base) + with ( + patch.object(os, "scandir", wraps=os.scandir) as scandir, + patch.object( + delta_lake_databases, "open", wraps=open, create=True + ) as file_open, + ): + if operation == "exists": + assert not db.table_exists(path) + elif operation == "read": + assert db.get_all_records(path) is None + else: + assert db.get_table_schema(path) is None + scandir.assert_not_called() + file_open.assert_not_called() def test_cold_cloud_delta_lookup_adds_no_selector_listings(base: Path) -> None: @@ -598,8 +637,7 @@ def test_plain_text_with_both_parquet_magic_markers_is_a_candidate( contents = b"PAR1 This is a plain-text note ending in PAR1" _ = note.write_bytes(contents) - with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): - DeltaTableDatabase(base).table_exists(PATH) + assert not DeltaTableDatabase(base).table_exists(PATH) with pytest.raises(OrcapodDatabaseReadError, match="_delta_log"): DeltaTableDatabase(base).add_record( PATH, b"a", pa.table({"x": [1]}), flush=True @@ -693,19 +731,23 @@ def list_scoped(directory: str): assert db.list_table_paths() == [] -def test_empty_initial_log_is_refused_on_read( +def test_empty_initial_log_is_refused_on_flush( base: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """An empty log with existing data cannot be mistaken for an absent table.""" + """A flush cannot replace an empty log when its data are present.""" monkeypatch.setattr(delta_lake_databases, "sleep", lambda _delay: None) deltalake.write_deltalake(table_dir(base), pa.table({"x": [1]})) log = table_dir(base) / "_delta_log" shutil.rmtree(log) log.mkdir() + before = snapshot(table_dir(base)) with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: - DeltaTableDatabase(base).get_all_records(PATH) + DeltaTableDatabase(base).add_record( + PATH, b"a", pa.table({"x": [2]}), flush=True + ) assert info.value.record_path == PATH + assert snapshot(table_dir(base)) == before @function_pod(output_keys=["sum", "difference"])