diff --git a/changelog.d/ITL-916.md b/changelog.d/ITL-916.md new file mode 100644 index 000000000..4d7a1f35b --- /dev/null +++ b/changelog.d/ITL-916.md @@ -0,0 +1,14 @@ +### Fixed + +- 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 + +- 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 new file mode 100644 index 000000000..70976f553 --- /dev/null +++ b/docs/dev/design_issues/ITL-916-DR2.md @@ -0,0 +1,21 @@ +## `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:** 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 c88b322d8..9e2877228 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -5,14 +5,14 @@ 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 typing import TYPE_CHECKING, Any, Literal, cast +from time import sleep +from typing import TYPE_CHECKING, Any, BinaryIO, Literal, cast import polars as pl import pyarrow as pa @@ -86,6 +86,61 @@ # 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) + + +def _has_parquet_magic(file: BinaryIO) -> 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) > 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 + + +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 @@ -115,7 +170,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. @@ -1929,7 +1984,6 @@ def _get_delta_table( return None try: - # Try to load existing table delta_table = deltalake.DeltaTable( table_uri, storage_options=self._storage_options or None ) @@ -1945,6 +1999,58 @@ def _get_delta_table( self._delta_table_cache.pop(record_key, None) raise self._read_failed(record_path) from e + 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`` 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. + """ + from deltalake.exceptions import TableNotFoundError + + options = self._storage_options or None + try: + return deltalake.DeltaTable(table_uri, storage_options=options) + except TableNotFoundError as missing_log: + 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) + 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_orphaned_delta_data_files(self, table_uri: str) -> bool: + """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) or not _local_delta_data_has_parquet(table): + return False + + try: + resolved = table.resolve() + # 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. + 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. @@ -3789,19 +3895,13 @@ 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 + 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_absent_tables.py b/tests/test_databases/test_delta_absent_tables.py index 7cdb6ee8d..4df42d601 100644 --- a/tests/test_databases/test_delta_absent_tables.py +++ b/tests/test_databases/test_delta_absent_tables.py @@ -2,16 +2,19 @@ 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 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 +import os from pathlib import Path +import shutil from typing import cast import deltalake @@ -19,6 +22,8 @@ import pytest from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases +from orcapod.errors import OrcapodDatabaseReadError PATH = ("table",) @@ -129,6 +134,40 @@ def test_table_exists_checks_again(tmp_path: Path) -> None: assert _values(ours.get_all_records(PATH)) == [10] +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 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 + 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.add_records(PATH, _rows(["y"], [20]), flush=True) + 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 4af6e7292..716a90786 100644 --- a/tests/test_databases/test_delta_read_failures.py +++ b/tests/test_databases/test_delta_read_failures.py @@ -17,24 +17,32 @@ 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 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 +from orcapod import function_pod from orcapod.databases import DeltaTableDatabase +from orcapod.databases import delta_lake_databases from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, TypeIdentityError, ) +from orcapod.pipeline import PipelineJob from orcapod.sources import DictSource PATH = ("results", "t") @@ -148,6 +156,691 @@ def assert_names_table(exc: OrcapodDatabaseReadError, base: Path) -> None: } +@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_store( + base: Path, + damaged_path: tuple[str, ...], + request: pytest.FixtureRequest, +) -> DeltaTableDatabase: + """Return a fresh handle after dropping the log from a populated table.""" + directory = base.joinpath(*damaged_path) + data = pa.table( + { + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a", b"b"], + "tag1": ["a", "c"], + "tag2": ["b", "d"], + "x": [1, 3], + "y": [2, 4], + } + ) + 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) + + +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_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_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), +} + + +@pytest.mark.parametrize( + "read", MISSING_LOG_READS.values(), ids=list(MISSING_LOG_READS) +) +def test_missing_log_reads_as_absent( + damaged_path: tuple[str, ...], + damaged_store: DeltaTableDatabase, + read: Callable[[DeltaTableDatabase, tuple[str, ...]], object], +) -> None: + """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( + stored: DeltaTableDatabase, monkeypatch: pytest.MonkeyPatch +) -> 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_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( + damaged_path, rows([b"c"], pa.array([3], pa.int64())), record_id_column="rid" + ) + + with pytest.raises(OrcapodDatabaseReadError, match="_delta_log") as info: + damaged_store.flush() + + 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")) == [] + + +@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, + 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, raising=False + ) + 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"] + ) + 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.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) + 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 = 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 + 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] + + +@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: + """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 +) -> 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_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 + 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) + + 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: + """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 + 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)) + + return moved + + +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) + 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 = 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 + + +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, 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" + contents = b"PAR1 This is a plain-text note ending in PAR1" + _ = note.write_bytes(contents) + + 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 + ) + 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 +) -> None: + """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() + + db = DeltaTableDatabase(base) + assert getattr(db, listing)() == [PATH] + + +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}") + + db = DeltaTableDatabase(base) + assert sorted(db.list_sources()) == [("alias",), ("table",)] + assert db.list_table_paths() == [("table",)] + + +@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( + 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() == [] + + +def test_empty_initial_log_is_refused_on_flush( + base: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """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).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"]) +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: + """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..ba6a1a497 100644 --- a/tests/test_databases/test_delta_table_database_s3.py +++ b/tests/test_databases/test_delta_table_database_s3.py @@ -13,8 +13,12 @@ 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 +import s3fs from upath import UPath from orcapod.databases import DeltaTableDatabase @@ -58,6 +62,185 @@ 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"], ["tag2", "tag1"]], + ids=["flat", "partitioned", "reordered-partitions"], +) +def test_s3_table_with_missing_log_follows_main( + s3_base_uri: str, + s3_storage_options: dict[str, str], + path: tuple[str, ...], + partitions: list[str] | None, +) -> None: + """A missing cloud log allows a replacement write alongside the old object.""" + uri = "/".join((s3_base_uri,) + path) + data = pa.table( + { + "y": [2], + "tag1": ["a"], + DeltaTableDatabase.RECORD_ID_COLUMN: [b"a"], + "tag2": ["b"], + "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 + ) + + 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 = {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) + 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], +) -> None: + """Parquet below a non-partition prefix does not stop a replacement write.""" + path = ("table",) + uri = f"{s3_base_uri}/table" + 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) + + 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 + + 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"]) +def test_s3_partition_path_accepts_independent_child( + s3_base_uri: str, + s3_storage_options: dict[str, str], + overwrite: bool, +) -> None: + """A healthy parent owns its active objects and those pending vacuum.""" + 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, + ) + 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 + 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 + 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], +) -> None: + """An unrelated object ending in .parquet can coexist with a new table.""" + 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): db = DeltaTableDatabase(s3_base_uri, storage_options=s3_storage_options) record = pa.table({"v": [1]})