Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions changelog.d/ITL-916.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 21 additions & 0 deletions docs/dev/design_issues/ITL-916-DR2.md
Original file line number Diff line number Diff line change
@@ -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.
124 changes: 112 additions & 12 deletions src/orcapod/databases/delta_lake_databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
)
Expand All @@ -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.

Expand Down Expand Up @@ -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
Expand Down
49 changes: 44 additions & 5 deletions tests/test_databases/test_delta_absent_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,28 @@

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
import pyarrow as pa
import pytest

from orcapod.databases import DeltaTableDatabase
from orcapod.databases import delta_lake_databases
from orcapod.errors import OrcapodDatabaseReadError

PATH = ("table",)

Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading