diff --git a/changelog.d/ITL-1446.md b/changelog.d/ITL-1446.md new file mode 100644 index 000000000..c9af35b6c --- /dev/null +++ b/changelog.d/ITL-1446.md @@ -0,0 +1,3 @@ +### Changed + +- Run pipeline store conformance tests against Delta, in-memory, SQLite and the disk-backed SpiralDB fake. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 013370f38..758a3f762 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -428,6 +428,12 @@ batch = Batch(batch_size=10, drop_partial_batch=True) of tag values are the only thing that tells a batch's members apart. `GroupBy` (below) has a key and keeps only that. +`Batch` uses the order in which its source supplies rows. Treat rows read from a database +as a set unless the database documents an ordering guarantee. A stored source read from +SpiralDB can therefore produce different batch members than the same rows read from Delta. +Reading the rows a node holds for its current synchronous run still gives the order in +which that run passed them downstream. + ### GroupBy Collapses every set of rows that share a tag tuple into a single row -- the one many-to-one diff --git a/tests/conftest.py b/tests/conftest.py index de039dd5d..4cb99f369 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -16,9 +16,15 @@ from __future__ import annotations import os +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import TYPE_CHECKING import pytest +if TYPE_CHECKING: + from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + def _running_in_ci() -> bool: """Whether the tests run in CI: ``CI`` is ``true`` (or ``1``), as GitHub Actions sets it.""" @@ -65,3 +71,26 @@ def pytest_collection_modifyitems( for item in items: if any(mark.name == "postgres" for mark in item.iter_markers()): item.add_marker(skip_marker) + + +@pytest.fixture +def pipeline_store_factory( + request: pytest.FixtureRequest, tmp_path: Path +) -> Iterator[Callable[[str], ArrowDatabaseProtocol]]: + """Open named, isolated stores of the same backend for one test. + + Disk-backed stores return a fresh handle for an existing name. In-memory + stores keep their original handle so a second open can see the same data. + """ + from tests.pipeline_stores import open_stores + + with open_stores(request.param, tmp_path) as factory: + yield factory + + +@pytest.fixture +def pipeline_store( + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], +) -> ArrowDatabaseProtocol: + """An empty store for tests that only need one handle.""" + return pipeline_store_factory("store") diff --git a/tests/pipeline_stores.py b/tests/pipeline_stores.py new file mode 100644 index 000000000..8cf3e6874 --- /dev/null +++ b/tests/pipeline_stores.py @@ -0,0 +1,81 @@ +"""Backend parameters for shared pipeline store tests.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from contextlib import ExitStack, contextmanager +from pathlib import Path + +import pytest + +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + SpiralDBConnector, + SQLiteConnector, +) +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from tests.test_databases import fake_pyspiral + +from orcapod.errors import UnstorableColumnError + +STORE_KINDS = ("in_memory", "delta", "sqlite", "spiral") + +_SPIRAL_RESERVED_COLUMNS = pytest.param( + "spiral", + marks=pytest.mark.xfail( + strict=True, + raises=UnstorableColumnError, + reason="TODO-ITL: SpiralDB reserves the '__' prefix on value columns.", + ), +) +_SQLITE_EXECUTOR_INFO = pytest.param( + "sqlite", + marks=pytest.mark.xfail( + strict=True, + raises=UnstorableColumnError, + reason="TODO-ITL: SQLite cannot store the function executor's list of structs.", + ), +) + +function_store_cases = pytest.mark.parametrize( + "pipeline_store_factory", + ("in_memory", "delta", _SQLITE_EXECUTOR_INFO, _SPIRAL_RESERVED_COLUMNS), + indirect=True, +) +cache_store_cases = pytest.mark.parametrize( + "pipeline_store_factory", + ("in_memory", "delta", "sqlite", _SPIRAL_RESERVED_COLUMNS), + indirect=True, +) + + +@contextmanager +def open_stores( + kind: str, root: Path +) -> Iterator[Callable[[str], ArrowDatabaseProtocol]]: + """Open stores of one kind, with named namespaces for isolation and reopening.""" + with ExitStack() as resources: + if kind == "spiral": + resources.enter_context(fake_pyspiral.install(root / "spiral")) + memory: dict[str, InMemoryArrowDatabase] = {} + + def open_store(name: str) -> ArrowDatabaseProtocol: + """Open a store and register any connector for teardown.""" + if kind == "in_memory": + if name not in memory: + memory[name] = InMemoryArrowDatabase() + return memory[name] + if kind == "delta": + return DeltaTableDatabase(root / name) + if kind == "sqlite": + connector = SQLiteConnector(root / f"{name}.db") + elif kind == "spiral": + connector = SpiralDBConnector("p", dataset=name) + else: + raise AssertionError(f"Unknown test store: {kind}") + resources.callback(connector.close) + return ConnectorArrowDatabase(connector) + + yield open_store diff --git a/tests/test_core/sources/test_cached_source.py b/tests/test_core/sources/test_cached_source.py index f1912aa1a..0b0690cc5 100644 --- a/tests/test_core/sources/test_cached_source.py +++ b/tests/test_core/sources/test_cached_source.py @@ -22,6 +22,7 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.system_constants import constants +from tests.pipeline_stores import cache_store_cases # --------------------------------------------------------------------------- @@ -209,28 +210,29 @@ def test_keys_match_source(self, simple_source, db): # --------------------------------------------------------------------------- +@cache_store_cases class TestCachedSourceStreaming: - def test_as_table_matches_source(self, simple_source, db): - ps = CachedSource(simple_source, cache_database=db) + def test_as_table_matches_source(self, simple_source, pipeline_store): + ps = CachedSource(simple_source, cache_database=pipeline_store) ps_table = ps.as_table() src_table = simple_source.as_table() assert ps_table.num_rows == src_table.num_rows assert set(ps_table.column_names) == set(src_table.column_names) - def test_iter_data_count(self, simple_source, db): - ps = CachedSource(simple_source, cache_database=db) + def test_iter_data_count(self, simple_source, pipeline_store): + ps = CachedSource(simple_source, cache_database=pipeline_store) data = list(ps.iter_data()) assert len(data) == 3 - def test_iter_data_tags_and_data(self, simple_source, db): - ps = CachedSource(simple_source, cache_database=db) + def test_iter_data_tags_and_data(self, simple_source, pipeline_store): + ps = CachedSource(simple_source, cache_database=pipeline_store) for tag, data in ps.iter_data(): assert "name" in tag.keys() assert "age" in data.keys() - def test_system_tags_preserved(self, simple_source, db): + def test_system_tags_preserved(self, simple_source, pipeline_store): """System tags flow through the cache correctly.""" - ps = CachedSource(simple_source, cache_database=db) + ps = CachedSource(simple_source, cache_database=pipeline_store) table = ps.as_table(columns={"system_tags": True}) sys_tag_cols = [ c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) @@ -249,9 +251,9 @@ def test_system_tags_preserved(self, simple_source, db): assert len(source_id_cols) == 1 assert len(record_id_cols) == 1 - def test_source_info_preserved(self, simple_source, db): + def test_source_info_preserved(self, simple_source, pipeline_store): """Source info columns flow through the cache correctly.""" - ps = CachedSource(simple_source, cache_database=db) + ps = CachedSource(simple_source, cache_database=pipeline_store) table = ps.as_table(columns={"source": True}) source_cols = [ c for c in table.column_names if c.startswith(constants.SOURCE_PREFIX) @@ -264,6 +266,7 @@ def test_source_info_preserved(self, simple_source, db): # --------------------------------------------------------------------------- +@cache_store_cases class TestCachedSourceKeyPolicy: """Two sources that differ only in key policy never share a cache (ITL-1154).""" @@ -277,7 +280,7 @@ def _record_ids(source: CachedSource) -> list[str]: ] return sorted(str(value) for value in table.column(column).to_pylist()) - def test_one_source_id_two_key_policies_get_separate_caches(self, db): + def test_one_source_id_two_key_policies_get_separate_caches(self, pipeline_store): table = pa.table({"k": ["a", "b"], "v": [1, 2]}) by_position = ArrowTableSource( table, tag_columns=["k"], source_id="s", tag_only_columns=True @@ -292,40 +295,41 @@ def test_one_source_id_two_key_policies_get_separate_caches(self, db): assert by_position.pipeline_hash() == by_key.pipeline_hash() assert by_position.content_hash() != by_key.content_hash() - cached_by_position = CachedSource(by_position, cache_database=db) - cached_by_key = CachedSource(by_key, cache_database=db) + cached_by_position = CachedSource(by_position, cache_database=pipeline_store) + cached_by_key = CachedSource(by_key, cache_database=pipeline_store) assert cached_by_position.cache_path != cached_by_key.cache_path cached_by_position.flow() cached_by_key.flow() # A later read of either source sees only its own rows. - again_by_position = CachedSource(by_position, cache_database=db) - again_by_key = CachedSource(by_key, cache_database=db) + again_by_position = CachedSource(by_position, cache_database=pipeline_store) + again_by_key = CachedSource(by_key, cache_database=pipeline_store) assert self._record_ids(again_by_position) == ["row_0", "row_1"] assert self._record_ids(again_by_key) == ['{"k":"a"}', '{"k":"b"}'] +@cache_store_cases class TestCachedSourceCumulative: - def test_dedup_on_same_data(self, simple_source, db): + def test_dedup_on_same_data(self, simple_source, pipeline_store): """Running twice with the same data produces no duplicates.""" - ps1 = CachedSource(simple_source, cache_database=db) + ps1 = CachedSource(simple_source, cache_database=pipeline_store) ps1.flow() - ps2 = CachedSource(simple_source, cache_database=db) + ps2 = CachedSource(simple_source, cache_database=pipeline_store) ps2.flow() table = ps2.as_table() assert table.num_rows == 3 # no duplicates - def test_clear_cache_rebuilds(self, simple_source, db): + def test_clear_cache_rebuilds(self, simple_source, pipeline_store): """clear_cache forces a fresh merge from DB on next access.""" - ps = CachedSource(simple_source, cache_database=db) + ps = CachedSource(simple_source, cache_database=pipeline_store) t1 = ps.as_table() ps.clear_cache() t2 = ps.as_table() assert t1.num_rows == t2.num_rows - def test_source_modified_time_triggers_rebuild(self, simple_source, db): + def test_source_modified_time_triggers_rebuild(self, simple_source, pipeline_store): """Updating the wrapped source's modified time triggers a cache rebuild.""" - ps = CachedSource(simple_source, cache_database=db) + ps = CachedSource(simple_source, cache_database=pipeline_store) # First access: build and cache t1 = ps.as_table() assert t1.num_rows == 3 @@ -339,7 +343,7 @@ def test_source_modified_time_triggers_rebuild(self, simple_source, db): # Verify CachedSource's own modified time was updated past the source's assert not ps.is_stale - def test_cumulative_across_runs(self, db): + def test_cumulative_across_runs(self, pipeline_store): """Data from different runs accumulates in the cache.""" # Use a single source_id to make them share the same canonical identity # but with different data (different content_hash → different cache_path) @@ -362,7 +366,7 @@ def test_cumulative_across_runs(self, db): # Different data → different content_hash → different cache_paths # So cumulative within the SAME cache_path requires same content_hash - ps1 = CachedSource(s1, cache_database=db) + ps1 = CachedSource(s1, cache_database=pipeline_store) ps1.flow() assert ps1.as_table().num_rows == 2 @@ -374,12 +378,12 @@ def test_cumulative_across_runs(self, db): infer_nullable=True, tag_only_columns=True, ) - ps1_again = CachedSource(s1_again, cache_database=db) + ps1_again = CachedSource(s1_again, cache_database=pipeline_store) ps1_again.flow() assert ps1_again.as_table().num_rows == 2 # Different source (s2) has different cache_path - ps2 = CachedSource(s2, cache_database=db) + ps2 = CachedSource(s2, cache_database=pipeline_store) ps2.flow() assert ps2.as_table().num_rows == 3 @@ -394,8 +398,9 @@ def test_cumulative_across_runs(self, db): # --------------------------------------------------------------------------- +@cache_store_cases class TestCachedSourceIntegration: - def test_join_with_cached_source(self, db): + def test_join_with_cached_source(self, pipeline_store): """CachedSource can be joined with another stream.""" from orcapod.core.operators import Join @@ -416,8 +421,8 @@ def test_join_with_cached_source(self, db): tag_only_columns=True, ) - ps1 = CachedSource(s1, cache_database=db) - ps2 = CachedSource(s2, cache_database=db) + ps1 = CachedSource(s1, cache_database=pipeline_store) + ps2 = CachedSource(s2, cache_database=pipeline_store) joined = Join()(ps1, ps2) table = joined.as_table() @@ -425,7 +430,7 @@ def test_join_with_cached_source(self, db): assert "val_a" in table.column_names assert "val_b" in table.column_names - def test_function_pod_with_cached_source(self, db): + def test_function_pod_with_cached_source(self, pipeline_store): """CachedSource works as input to a FunctionPod.""" from orcapod.core.function_pod import FunctionPod from orcapod.core.data_function import PythonDataFunction @@ -444,7 +449,7 @@ def double_age(age: int) -> int: infer_nullable=True, tag_only_columns=True, ) - ps = CachedSource(source, cache_database=db) + ps = CachedSource(source, cache_database=pipeline_store) result = pod(ps) data = list(result.iter_data()) @@ -458,6 +463,7 @@ def double_age(age: int) -> int: # --------------------------------------------------------------------------- +@cache_store_cases class TestCachedSourceWithSourceProxy: """CachedSource loaded from config where the inner source is not reconstructable should still serve data from the cache database.""" @@ -477,7 +483,7 @@ def _make_proxy(source): expected_class_name=source.__class__.__name__, ) - def test_serves_cached_data_when_inner_source_unrecoverable(self, db): + def test_serves_cached_data_when_inner_source_unrecoverable(self, pipeline_store): """Populate cache → replace inner source with SourceProxy → data still available from cache.""" table = pa.table( @@ -493,7 +499,7 @@ def test_serves_cached_data_when_inner_source_unrecoverable(self, db): infer_nullable=True, tag_only_columns=True, ) - cached = CachedSource(source, cache_database=db) + cached = CachedSource(source, cache_database=pipeline_store) # Force data into the cache _ = cached.as_table() @@ -502,7 +508,7 @@ def test_serves_cached_data_when_inner_source_unrecoverable(self, db): proxy = self._make_proxy(source) loaded = CachedSource( source=proxy, - cache_database=db, + cache_database=pipeline_store, # An explicit cache_path excludes the layout component (sdb_v1). cache_path=cached.cache_path[:-1], ) @@ -514,7 +520,7 @@ def test_serves_cached_data_when_inner_source_unrecoverable(self, db): assert "name" in result.column_names assert "age" in result.column_names - def test_inner_source_is_source_proxy(self, db): + def test_inner_source_is_source_proxy(self, pipeline_store): """Verify the CachedSource wraps a SourceProxy.""" from orcapod.core.sources.source_proxy import SourceProxy @@ -532,12 +538,12 @@ def test_inner_source_is_source_proxy(self, db): tag_only_columns=True, ) proxy = self._make_proxy(source) - loaded = CachedSource(source=proxy, cache_database=db) + loaded = CachedSource(source=proxy, cache_database=pipeline_store) assert isinstance(loaded._source, SourceProxy) assert loaded._source.expected_class_name == "ArrowTableSource" - def test_identity_preserved_with_proxy(self, db): + def test_identity_preserved_with_proxy(self, pipeline_store): """CachedSource wrapping SourceProxy has same content_hash and pipeline_hash as the original CachedSource.""" table = pa.table( @@ -553,7 +559,7 @@ def test_identity_preserved_with_proxy(self, db): infer_nullable=True, tag_only_columns=True, ) - cached = CachedSource(source, cache_database=db) + cached = CachedSource(source, cache_database=pipeline_store) original_content = cached.content_hash() original_pipeline = cached.pipeline_hash() @@ -561,7 +567,7 @@ def test_identity_preserved_with_proxy(self, db): proxy = self._make_proxy(source) loaded = CachedSource( source=proxy, - cache_database=db, + cache_database=pipeline_store, # An explicit cache_path excludes the layout component (sdb_v1). cache_path=cached.cache_path[:-1], ) @@ -569,7 +575,7 @@ def test_identity_preserved_with_proxy(self, db): assert loaded.content_hash() == original_content assert loaded.pipeline_hash() == original_pipeline - def test_empty_cache_returns_empty_stream(self, db): + def test_empty_cache_returns_empty_stream(self, pipeline_store): """CachedSource with unrecoverable source and empty cache returns an empty stream rather than raising.""" table = pa.table( @@ -589,7 +595,7 @@ def test_empty_cache_returns_empty_stream(self, db): loaded = CachedSource( source=proxy, - cache_database=db, + cache_database=pipeline_store, cache_path=("test", "empty"), ) @@ -597,22 +603,23 @@ def test_empty_cache_returns_empty_stream(self, db): assert result.num_rows == 0 +@cache_store_cases class TestCachedConvenienceMethod: """Test the ``RootSource.cached()`` convenience method.""" - def test_cached_returns_cached_source(self, simple_source, db): - cached = simple_source.cached(cache_database=db) + def test_cached_returns_cached_source(self, simple_source, pipeline_store): + cached = simple_source.cached(cache_database=pipeline_store) assert isinstance(cached, CachedSource) - def test_cached_with_path_prefix(self, simple_source, db): + def test_cached_with_path_prefix(self, simple_source, pipeline_store): cached = simple_source.cached( - cache_database=db, + cache_database=pipeline_store, cache_path_prefix=("my", "prefix"), ) assert cached.cache_path[:2] == ("my", "prefix") - def test_cached_data_matches_source(self, simple_source, db): - cached = simple_source.cached(cache_database=db) + def test_cached_data_matches_source(self, simple_source, pipeline_store): + cached = simple_source.cached(cache_database=pipeline_store) original_table = simple_source.as_table() cached_table = cached.as_table() diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index 9bc7a0fb1..23bd74054 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -45,6 +45,24 @@ refused unless written with ``push_down_nulls=True``, which turns it into a struct of null fields (observed live, ITL-936; top-level struct columns only in the fake). * Rows come back sorted by key and writes upsert by key (SpiralDB is a key-sorted store). + +Limits of this double (pyspiral 0.16.33 client docstrings and the connector's live tests): + +* A project ID and client configuration are accepted without authentication, permissions, + service-side name/key-schema validation, or storage routing. ``root_uri`` and transaction + options are ignored. Deleting an absent table succeeds, while the real client first opens it. +* Each write replaces a local Arrow file. The fake does not enforce the client's unique-key + requirement within one transaction, and offers no transaction, atomic visibility, or + server conflict semantics for concurrent writes. Metadata limits are checked, but the + unversioned metadata race is not simulated. +* Scans record ``asof`` but always read current rows. The fake reads and filters the whole + file, so ``limit`` demonstrates the output bound but cannot establish early termination. + Batch arguments are ignored, including ``disable_view_types``; batch splitting is synthetic. +* The fake preserves written struct-child order and checks/pushes down null structs only in + top-level struct columns. Its Arrow casts and extension unwrapping are approximations. + Nested coercions, key types, identifier length limits, and service-side failures need live + checks. The fake refuses changes to the column set that raw SpiralDB can accept. + """ from __future__ import annotations diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index be47d4377..dfbc7cc4a 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -46,15 +46,12 @@ from orcapod.contexts import get_default_context from orcapod.databases import ( ConnectorArrowDatabase, - DeltaTableDatabase, - InMemoryArrowDatabase, PostgreSQLConnector, - SQLiteConnector, - SpiralDBConnector, ) from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] from orcapod.databases.utils import identity_node from orcapod.utils.arrow_utils import normalize_to_large_types +from tests.pipeline_stores import open_stores KEPT = "KEPT" RECORDED = "KEPT VIA RECORDED TYPE" @@ -630,26 +627,22 @@ def build_table(row: Row, root: Path) -> pa.Table: @contextlib.contextmanager def open_database(name: str, root: Path) -> Iterator[Any]: """The database ``name`` (one of ``DATABASES``), its files under ``root``.""" - if name == "in-memory": - yield InMemoryArrowDatabase() - elif name == "Delta": - yield DeltaTableDatabase(root / "delta") - elif name == "SQLite": - yield ConnectorArrowDatabase(SQLiteConnector(str(root / "store.db"))) - elif name == "SpiralDB": - from tests.test_databases import fake_pyspiral - - with fake_pyspiral.install(root / "spiral"): - fake_pyspiral.FakeSpiral().project("p") - yield ConnectorArrowDatabase(SpiralDBConnector("p")) - elif name == "PostgreSQL": + if name == "PostgreSQL": with patch("psycopg.connect") as connect: connect.return_value = MagicMock() yield ConnectorArrowDatabase( PostgreSQLConnector("postgresql://localhost/m") ) else: - raise AssertionError(name) + stores = { + "in-memory": ("in_memory", "store"), + "Delta": ("delta", "delta"), + "SQLite": ("sqlite", "store"), + "SpiralDB": ("spiral", "default"), + } + kind, namespace = stores[name] + with open_stores(kind, root) as open_store: + yield open_store(namespace) def _names_a_column(error: BaseException) -> bool: diff --git a/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py b/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py index a7bc71291..d46a074d6 100644 --- a/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py +++ b/tests/test_pipeline/loaded_job/test_loaded_operator_cache.py @@ -29,6 +29,8 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode +from tests.pipeline_stores import function_store_cases +from tests.pipeline_stores import cache_store_cases JOB_NAME = "loaded_operator_cache" NULLABILITY = { @@ -137,13 +139,13 @@ def _sorted(table: pa.Table) -> pa.Table: # --------------------------------------------------------------------------- -@pytest.mark.parametrize("store_kind", STORES) @pytest.mark.parametrize("nullability", list(NULLABILITY)) +@function_store_cases def test_every_node_keeps_its_identity_and_schema_through_save_and_load( - store_kind: str, nullability: str, tmp_path: pathlib.Path + pipeline_store: ArrowDatabaseProtocol, nullability: str, tmp_path: pathlib.Path ) -> None: """Pipeline hash, content hash, table path and output schema are the run's.""" - store = _store(store_kind, tmp_path) + store = pipeline_store job = _run(store, nullability) loaded = PipelineJob.load(str(_save(job, tmp_path)), database=store) # In-memory sources are not saved: a source node's content hash is its bound @@ -160,14 +162,17 @@ def test_every_node_keeps_its_identity_and_schema_through_save_and_load( @pytest.mark.parametrize("read", ["as_table", "iter_data", "head"]) -@pytest.mark.parametrize("store_kind", STORES) @pytest.mark.parametrize("nullability", list(NULLABILITY)) +@function_store_cases def test_loaded_replay_operator_reads_the_rows_its_run_stored( - store_kind: str, nullability: str, read: str, tmp_path: pathlib.Path + pipeline_store: ArrowDatabaseProtocol, + nullability: str, + read: str, + tmp_path: pathlib.Path, ) -> None: """A loaded operator node's stored view reads exactly the rows read before saving; the node itself is empty until it runs (ITL-1095).""" - store = _store(store_kind, tmp_path) + store = pipeline_store job = _run(store, nullability) expected = _sorted(job.nodes["joined"].as_table()) node = _load_replaying(_save(job, tmp_path), store).nodes["joined"] @@ -182,11 +187,12 @@ def test_loaded_replay_operator_reads_the_rows_its_run_stored( @pytest.mark.parametrize("nullability", list(NULLABILITY)) +@cache_store_cases def test_a_pipeline_loaded_and_bound_to_its_sources_reuses_the_operator_cache( - nullability: str, tmp_path: pathlib.Path + nullability: str, pipeline_store: ArrowDatabaseProtocol, tmp_path: pathlib.Path ) -> None: """``Pipeline.load`` + ``from_pipeline(sources=...)`` reads and writes the run's table.""" - store = InMemoryArrowDatabase() + store = pipeline_store # Pipeline.load rebuilds operators but not function pods: an operator-only pipeline. job = _run(store, nullability, with_function=False) expected = _sorted(job.nodes["joined"].as_table()) diff --git a/tests/test_pipeline/test_connector_store_conformance.py b/tests/test_pipeline/test_connector_store_conformance.py new file mode 100644 index 000000000..6d12f08a9 --- /dev/null +++ b/tests/test_pipeline/test_connector_store_conformance.py @@ -0,0 +1,117 @@ +"""Store requirements that can run even when a pipeline's schema is refused.""" + +from collections.abc import Callable +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.operators import SelectDataColumns +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import ArrowTableSource +from tests.pipeline_stores import STORE_KINDS + +COLUMNS = ("tag", "group", "measure", "note") +ORDERS = ( + COLUMNS, + ("group", "note", "tag", "measure"), + ("note", "measure", "group", "tag"), +) +_SHADOWED_PATHS = tuple( + pytest.param( + kind, + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="TODO-ITL: Distinct record paths sanitize to the same connector table name.", + ), + ) + if kind in {"sqlite", "spiral"} + else kind + for kind in STORE_KINDS +) +_NO_CONNECTOR_LOADER = tuple( + pytest.param( + kind, + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="TODO-ITL: PipelineJob.load cannot reconstruct a saved connector database (ITL-1391).", + ), + ) + if kind in {"sqlite", "spiral"} + else kind + for kind in STORE_KINDS +) + + +def _row(tag: int) -> pa.Table: + """Build a row with two tags and two values.""" + return pa.table( + { + "tag": [tag], + "group": pa.array(["a"], type=pa.large_string()), + "measure": [10 * tag], + "note": pa.array([f"n{tag}"], type=pa.large_string()), + } + ) + + +@pytest.mark.parametrize("pipeline_store_factory", STORE_KINDS, indirect=True) +def test_a_scan_includes_committed_and_pending_rows_in_different_column_orders( + pipeline_store: ArrowDatabaseProtocol, +) -> None: + path = ("ordered", "rows") + for tag, order in zip((3, 1, 2), ORDERS, strict=True): + pipeline_store.add_record( + path, bytes([tag]), _row(tag).select(list(order)), flush=tag == 3 + ) + + table = pipeline_store.get_all_records(path) + assert table is not None + assert {tuple(row.values()) for row in table.select(list(COLUMNS)).to_pylist()} == { + (tag, "a", 10 * tag, f"n{tag}") for tag in (1, 2, 3) + } + + +@pytest.mark.parametrize("pipeline_store_factory", _SHADOWED_PATHS, indirect=True) +def test_distinct_record_paths_keep_distinct_rows( + pipeline_store: ArrowDatabaseProtocol, +) -> None: + first, second = ("a__b", "c"), ("a", "b__c") + pipeline_store.add_record(first, b"a", _row(1), flush=True) + pipeline_store.add_record(second, b"b", _row(2), flush=True) + + one = pipeline_store.get_all_records(first) + two = pipeline_store.get_all_records(second) + assert one is not None and one["tag"].to_pylist() == [1] + assert two is not None and two["tag"].to_pylist() == [2] + + +@pytest.mark.parametrize("pipeline_store_factory", _NO_CONNECTOR_LOADER, indirect=True) +def test_job_load_restores_the_saved_database( + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], tmp_path: Path +) -> None: + database = pipeline_store_factory("pipeline") + source = ArrowTableSource( + pa.concat_tables([_row(1), _row(2)]), + tag_columns=["tag", "group"], + tag_only_columns=True, + source_id="rows", + ) + job = PipelineJob(name="conformance", database=database) + with job: + SelectDataColumns(["measure", "note"])(source, label="selected") + job.run() + path = tmp_path / "job.json" + job.save(path) + + # A caller that supplies a store can load and bind the job for every backend. + rebound = PipelineJob.load(path, database=pipeline_store_factory("pipeline")) + rebound.bind(sources={"rows": source}) + rebound.run(load_only=True) + assert rebound.nodes["selected"].as_table().equals(job.nodes["selected"].as_table()) + + # The saved configuration itself must also be sufficient to rebuild the binding. + assert PipelineJob.load(path).database is not None diff --git a/tests/test_pipeline/test_job_batched_commits.py b/tests/test_pipeline/test_job_batched_commits.py index 52a91b8c8..35df3b45b 100644 --- a/tests/test_pipeline/test_job_batched_commits.py +++ b/tests/test_pipeline/test_job_batched_commits.py @@ -38,6 +38,7 @@ from orcapod.databases.utils import as_table_committing from orcapod.sources import DictSource from orcapod.types import NodeConfig, PodConfig +from tests.pipeline_stores import function_store_cases ORCHESTRATORS: dict[str, Callable[..., Any]] = { "sync": SyncPipelineOrchestrator, @@ -465,20 +466,24 @@ def counting(self: FunctionJobNode, tag: Any, input_data: Any) -> bytes: @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) @pytest.mark.parametrize("source_id", ["s", None]) +@function_store_cases def test_records_read_right_after_the_run_are_complete( - tmp_path: Path, orchestrator: str, source_id: str | None + pipeline_store: Any, orchestrator: str, source_id: str | None ) -> None: """``get_all_records`` right after ``run`` returns every row (ITL-930).""" - job = PipelineJob(name="itl930", database=DeltaTableDatabase(tmp_path)) + job = PipelineJob(name="itl930", database=pipeline_store) with job: source = DictSource( - data=[{"k": "b", "x": 2}, {"k": "c", "x": 3}], - tag_columns=["k"], + data=[ + {"g": "a", "k": "b", "note": "first", "x": 2}, + {"g": "a", "k": "c", "note": "second", "x": 3}, + ], + tag_columns=["g", "k"], tag_only_columns=True, source_id=source_id, ) double.pod(source, label="double") - job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + job.run(orchestrator=ORCHESTRATORS[orchestrator](), commit_every_rows=1) records = job.nodes["double"].get_all_records() assert records is not None and records.num_rows == 2 assert job.nodes["double"].as_table().num_rows == 2 diff --git a/tests/test_pipeline/test_job_run_summary.py b/tests/test_pipeline/test_job_run_summary.py index 9bbbb418d..82cddc38e 100644 --- a/tests/test_pipeline/test_job_run_summary.py +++ b/tests/test_pipeline/test_job_run_summary.py @@ -41,6 +41,7 @@ Arrangement, make_table, ) +from tests.pipeline_stores import function_store_cases # --- The public names this feature adds, in one place --------------------------------- @@ -103,11 +104,11 @@ def double(x: int) -> int: def make_job(store: Any, pod: Any, label: str, n_rows: int = 4) -> PipelineJob: """A source of ``n_rows`` rows (x = 0..n-1) feeding ``pod`` under ``label``.""" - rows = [{"k": f"r{i}", "x": i} for i in range(n_rows)] + rows = [{"k": f"r{i}", "g": i % 2, "x": i, "note": f"n{i}"} for i in range(n_rows)] job = PipelineJob(name="summary_demo", database=store) with job: source = DictSource( - data=rows, tag_columns=["k"], tag_only_columns=True, source_id="rows" + data=rows, tag_columns=["k", "g"], tag_only_columns=True, source_id="rows" ) pod.pod(source, label=label) return job @@ -125,9 +126,10 @@ def store(request: pytest.FixtureRequest, tmp_path: Path) -> Any: return STORES[request.param](tmp_path / "store") -def test_some_rows_fail(store: Any, orchestrator: Any) -> None: +@function_store_cases +def test_some_rows_fail(pipeline_store: Any, orchestrator: Any) -> None: """Rows that fail are counted and reported once; the others are computed and stored.""" - job = make_job(store, even_only, "evens") + job = make_job(pipeline_store, even_only, "evens") with pytest.warns(RowFailuresWarning) as caught: summary = run(job, orchestrator) @@ -135,8 +137,8 @@ def test_some_rows_fail(store: Any, orchestrator: Any) -> None: error = first_error(summary, "evens") assert isinstance(error, ValueError) assert str(error).startswith("odd x=") - assert len(caught) == 1 - message = str(caught[0].message) + (warning,) = [w for w in caught if issubclass(w.category, RowFailuresWarning)] + message = str(warning.message) assert "2 of 4 rows failed in node 'evens'" in message assert "ValueError: odd x=" in message assert 'job.last_run.print_traceback("evens")' in message @@ -146,9 +148,10 @@ def test_some_rows_fail(store: Any, orchestrator: Any) -> None: assert ys == [0, 2] -def test_every_row_fails(store: Any, orchestrator: Any) -> None: +@function_store_cases +def test_every_row_fails(pipeline_store: Any, orchestrator: Any) -> None: """A function failing on every row is reported with its error, not as an empty success.""" - job = make_job(store, always_fails, "broken") + job = make_job(pipeline_store, always_fails, "broken") with pytest.warns(RowFailuresWarning, match="4 of 4 rows failed in node 'broken'"): summary = run(job, orchestrator) @@ -162,9 +165,10 @@ def test_every_row_fails(store: Any, orchestrator: Any) -> None: assert 'job.last_run.print_traceback("broken")' in text -def test_clean_run_is_quiet(store: Any, orchestrator: Any) -> None: +@function_store_cases +def test_clean_run_is_quiet(pipeline_store: Any, orchestrator: Any) -> None: """A run without failed rows issues no warning and counts every row as computed.""" - job = make_job(store, double, "doubled") + job = make_job(pipeline_store, double, "doubled") with warnings.catch_warnings(): warnings.simplefilter("error") summary = run(job, orchestrator) @@ -175,17 +179,45 @@ def test_clean_run_is_quiet(store: Any, orchestrator: Any) -> None: assert first_error(summary, "doubled") is None -def test_rerun_counts_rows_from_the_store(store: Any, orchestrator: Any) -> None: +@function_store_cases +def test_rerun_counts_rows_from_the_store( + pipeline_store: Any, orchestrator: Any +) -> None: """Running again counts the stored rows as from the database and computes only the new row.""" - run(make_job(store, double, "doubled"), orchestrator) - summary = run(make_job(store, double, "doubled", n_rows=5), orchestrator) + run(make_job(pipeline_store, double, "doubled"), orchestrator) + warm = run(make_job(pipeline_store, double, "doubled"), orchestrator) + assert node_counts(warm, "doubled") == (0, 4, 0) + summary = run(make_job(pipeline_store, double, "doubled", n_rows=5), orchestrator) assert node_counts(summary, "doubled") == (1, 4, 0) -def test_fail_fast_still_raises(store: Any) -> None: +@function_pod(output_keys="y", function_name="double", version="v1.0") +def double_v1(x: int) -> int: + """Return a changed value at a new version of the function.""" + return 2 * x + 1 + + +@function_store_cases +def test_a_new_function_version_computes_again( + pipeline_store: Any, orchestrator: Any +) -> None: + first = make_job(pipeline_store, double, "doubled") + assert node_counts(run(first, orchestrator), "doubled") == (4, 0, 0) + + changed = make_job(pipeline_store, double_v1, "doubled") + assert node_counts(run(changed, orchestrator), "doubled") == (4, 0, 0) + values = changed.nodes["doubled"].as_table()["y"].to_pylist() + if isinstance(orchestrator, AsyncPipelineOrchestrator): + assert set(values) == {1, 3, 5, 7} + else: + assert values == [1, 3, 5, 7] + + +@function_store_cases +def test_fail_fast_still_raises(pipeline_store: Any) -> None: """``error_policy='fail_fast'`` raises the row's error as before.""" - job = make_job(store, even_only, "evens") + job = make_job(pipeline_store, even_only, "evens") with pytest.raises(ValueError, match="odd x="): job.run(orchestrator=SyncPipelineOrchestrator(error_policy="fail_fast")) @@ -218,9 +250,10 @@ def test_notebook_representation_names_the_failing_node() -> None: assert "odd x=" in html -def test_run_async_returns_the_same_summary(store: Any) -> None: +@function_store_cases +def test_run_async_returns_the_same_summary(pipeline_store: Any) -> None: """``run_async`` returns the summary, warns, and keeps it as ``last_run``.""" - job = make_job(store, even_only, "evens") + job = make_job(pipeline_store, even_only, "evens") with pytest.warns(RowFailuresWarning, match="2 of 4 rows failed in node 'evens'"): summary = asyncio.run(job.run_async()) diff --git a/tests/test_pipeline/test_load_only_run.py b/tests/test_pipeline/test_load_only_run.py index 6e8f399a5..427caa86d 100644 --- a/tests/test_pipeline/test_load_only_run.py +++ b/tests/test_pipeline/test_load_only_run.py @@ -18,9 +18,11 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.side_effects import SideEffectPod, tap_pod from orcapod.sources import DictSource from orcapod.types import CacheMode +from tests.pipeline_stores import function_store_cases CALLS: list[str] = [] DELIVERED: list[int] = [] @@ -82,7 +84,7 @@ def _build( return job -def _snapshot(db: InMemoryArrowDatabase) -> dict[tuple[str, ...], int]: +def _snapshot(db: ArrowDatabaseProtocol) -> dict[tuple[str, ...], int]: """Every table of the database with its row count.""" db.flush() counts: dict[tuple[str, ...], int] = {} @@ -103,10 +105,11 @@ def _totals(job: PipelineJob) -> list[tuple[int, int]]: @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@function_store_cases def test_a_load_only_run_over_a_full_store_equals_a_run_and_computes_nothing( - orchestrator: str, + orchestrator: str, pipeline_store: ArrowDatabaseProtocol ) -> None: - db = InMemoryArrowDatabase() + db = pipeline_store _run(_build(ROWS, db), orchestrator) expected = _build(ROWS, InMemoryArrowDatabase()) _run(expected, orchestrator) @@ -128,11 +131,12 @@ def test_a_load_only_run_over_a_full_store_equals_a_run_and_computes_nothing( @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@function_store_cases def test_inputs_without_a_stored_result_are_skipped_and_counted( - orchestrator: str, + orchestrator: str, pipeline_store: ArrowDatabaseProtocol ) -> None: """The database holds a 3-row run; the source now has 6 rows.""" - db = InMemoryArrowDatabase() + db = pipeline_store _run(_build(ROWS[:3], db), orchestrator) CALLS.clear() before = _snapshot(db) @@ -161,10 +165,11 @@ def test_inputs_without_a_stored_result_are_skipped_and_counted( @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@function_store_cases def test_a_load_only_run_over_an_empty_store_fills_nothing_and_writes_nothing( - orchestrator: str, + orchestrator: str, pipeline_store: ArrowDatabaseProtocol ) -> None: - db = InMemoryArrowDatabase() + db = pipeline_store job = _build(ROWS, db) summary = _run(job, orchestrator, load_only=True) assert CALLS == [] @@ -176,10 +181,11 @@ def test_a_load_only_run_over_an_empty_store_fills_nothing_and_writes_nothing( @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +@function_store_cases def test_a_load_only_run_delivers_no_side_effect_and_passes_the_rows_on( - orchestrator: str, + orchestrator: str, pipeline_store: ArrowDatabaseProtocol ) -> None: - db = InMemoryArrowDatabase() + db = pipeline_store _run(_build(ROWS, db, with_tap=True), orchestrator) assert len(DELIVERED) == 6 DELIVERED.clear() @@ -196,8 +202,11 @@ def test_a_load_only_run_delivers_no_side_effect_and_passes_the_rows_on( @pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) -def test_a_log_operator_writes_nothing_in_a_load_only_run(orchestrator: str) -> None: - db = InMemoryArrowDatabase() +@function_store_cases +def test_a_log_operator_writes_nothing_in_a_load_only_run( + orchestrator: str, pipeline_store: ArrowDatabaseProtocol +) -> None: + db = pipeline_store _run(_build(ROWS[:3], db, cache_mode=CacheMode.LOG), orchestrator) before = _snapshot(db) @@ -208,8 +217,9 @@ def test_a_log_operator_writes_nothing_in_a_load_only_run(orchestrator: str) -> assert job.nodes["grouped"].as_table().num_rows == 2 -def test_run_async_takes_load_only() -> None: - db = InMemoryArrowDatabase() +@function_store_cases +def test_run_async_takes_load_only(pipeline_store: ArrowDatabaseProtocol) -> None: + db = pipeline_store _run(_build(ROWS, db), "sync") CALLS.clear() job = _build(ROWS, db) diff --git a/tests/test_pipeline/test_provenance.py b/tests/test_pipeline/test_provenance.py index 46ef49360..7f7a0776f 100644 --- a/tests/test_pipeline/test_provenance.py +++ b/tests/test_pipeline/test_provenance.py @@ -20,8 +20,10 @@ from orcapod.errors import ProvenanceInconsistencyError from orcapod.operators import Batch, Filter, GroupBy, Join, SelectDataColumns from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import ArrowTableSource from orcapod.types import Highlight, SourceCell, col +from tests.pipeline_stores import function_store_cases pytestmark = pytest.mark.filterwarnings("ignore::Warning") @@ -110,6 +112,7 @@ def build( sessions_first: bool = False, fold: str = "group", name: str = "prov", + database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob: """The test pipeline: units filtered (``depth_um < 500``, which removes ``row_5``), joined with sessions (``row_6`` has no session), a per-unit function with two outputs @@ -122,8 +125,14 @@ def build( sessions_first: Give the join its inputs in the other argument order. fold: ``"group"`` or ``"batch"``. name: The job's name. + database: Override the default Delta store. """ - job = PipelineJob(name=name, database=DeltaTableDatabase(root / "store")) + job = PipelineJob( + name=name, + database=database + if database is not None + else DeltaTableDatabase(root / "store"), + ) with job: kept = Filter(col("depth_um") < 500)(units()) left = SelectDataColumns(["n_spikes"])(kept) @@ -170,10 +179,14 @@ def cells(trace: Any) -> set[tuple[str, str, str, Any]]: @pytest.mark.parametrize("mode", ["sync", "async"]) @pytest.mark.parametrize("sessions_first", [False, True]) +@function_store_cases def test_trace_reaches_every_source_cell( - tmp_path: Path, mode: str, sessions_first: bool + tmp_path: Path, + mode: str, + sessions_first: bool, + pipeline_store: ArrowDatabaseProtocol, ) -> None: - job = build(tmp_path, sessions_first=sessions_first) + job = build(tmp_path, sessions_first=sessions_first, database=pipeline_store) run(job, mode) trace = job.nodes["means"].trace({"subject": "m1", "session": "s1"}, "mean_hz") assert trace.status == "traced" @@ -188,7 +201,11 @@ def test_trace_reaches_every_source_cell( (grouped,) = trace.root.inputs members = [step for step in grouped.walk() if step.node == "unit_rates"] assert [m.member for m in members] == [0, 1, 2] - assert [dict(m.tags)["unit"] for m in members] == ["u0", "u1", "u2"] + units_in_trace = [dict(m.tags)["unit"] for m in members] + if mode == "async": + assert set(units_in_trace) == {"u0", "u1", "u2"} + else: + assert units_in_trace == ["u0", "u1", "u2"] def test_argument_order_gives_one_trace(tmp_path: Path) -> None: diff --git a/tests/test_pipeline/test_result_database.py b/tests/test_pipeline/test_result_database.py index 315929dd6..9cde8b35c 100644 --- a/tests/test_pipeline/test_result_database.py +++ b/tests/test_pipeline/test_result_database.py @@ -12,6 +12,7 @@ import json import logging import pathlib +from collections.abc import Callable from typing import Any import pyarrow as pa @@ -24,6 +25,7 @@ from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import ArrowTableSource +from tests.pipeline_stores import function_store_cases Orchestrator = SyncPipelineOrchestrator | AsyncPipelineOrchestrator @@ -167,11 +169,15 @@ def test_a_scoped_view_is_used_as_given(self) -> None: class TestSharing: @pytest.mark.parametrize("names", [("a", "b"), ("b", "a")]) + @function_store_cases def test_a_second_job_computes_nothing_the_first_stored( - self, names: tuple[str, str], orchestrator: Orchestrator + self, + names: tuple[str, str], + orchestrator: Orchestrator, + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], ) -> None: - db = InMemoryArrowDatabase() - results = InMemoryArrowDatabase() + db = pipeline_store_factory("pipeline") + results = pipeline_store_factory("results") first = two_step_job(names[0], db, [1.0, 2.0, 3.0], result_database=results) _ = first.run(orchestrator=orchestrator) assert len(calls) == 6 @@ -184,16 +190,22 @@ def test_a_second_job_computes_nothing_the_first_stored( # Each job keeps its own pipeline records. assert {p.split("/")[0] for p in table_paths(db)} == {"a", "b"} + @function_store_cases def test_only_inputs_not_stored_are_computed( - self, orchestrator: Orchestrator + self, + orchestrator: Orchestrator, + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], ) -> None: - results = InMemoryArrowDatabase() + results = pipeline_store_factory("results") _ = two_step_job( - "a", InMemoryArrowDatabase(), [1.0, 2.0], result_database=results + "a", pipeline_store_factory("first"), [1.0, 2.0], result_database=results ).run(orchestrator=orchestrator) calls.clear() second = two_step_job( - "b", InMemoryArrowDatabase(), [2.0, 1.0, 4.0], result_database=results + "b", + pipeline_store_factory("second"), + [2.0, 1.0, 4.0], + result_database=results, ) _ = second.run(orchestrator=orchestrator) assert sorted(calls) == [("double", 4.0), ("shift", 8.0)] @@ -368,23 +380,35 @@ class TestSideEffectingFunctions: @staticmethod def notify_job( - name: str, xs: list[float], results: ArrowDatabaseProtocol + name: str, + xs: list[float], + results: ArrowDatabaseProtocol, + database: ArrowDatabaseProtocol | None = None, ) -> PipelineJob: job = PipelineJob( - name=name, database=InMemoryArrowDatabase(), result_database=results + name=name, + database=database if database is not None else InMemoryArrowDatabase(), + result_database=results, ) with job: notify.pod(make_source(xs), label="notify") return job + @function_store_cases def test_only_inputs_no_job_delivered_are_delivered( - self, orchestrator: Orchestrator + self, + orchestrator: Orchestrator, + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], ) -> None: - results = InMemoryArrowDatabase() - _ = self.notify_job("a", [1.0, 2.0], results).run(orchestrator=orchestrator) + results = pipeline_store_factory("results") + _ = self.notify_job( + "a", [1.0, 2.0], results, pipeline_store_factory("pipeline") + ).run(orchestrator=orchestrator) assert sorted(delivered) == [1.0, 2.0] delivered.clear() - job = self.notify_job("b", [2.0, 3.0, 1.0], results) + job = self.notify_job( + "b", [2.0, 3.0, 1.0], results, pipeline_store_factory("pipeline") + ) _ = job.run(orchestrator=orchestrator) assert delivered == [3.0] assert rows(job, "notify", "sent") == [1.0, 2.0, 3.0] diff --git a/tests/test_pipeline/test_store_commit_protocol.py b/tests/test_pipeline/test_store_commit_protocol.py new file mode 100644 index 000000000..089fa058e --- /dev/null +++ b/tests/test_pipeline/test_store_commit_protocol.py @@ -0,0 +1,103 @@ +"""Commit guards across every pipeline store, using storable column names.""" + +from collections.abc import Callable + +import pyarrow as pa +import pytest + +from orcapod.errors import InputValidationError +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from tests.pipeline_stores import STORE_KINDS + +RESULTS = ("results", "rows") +RECORDS = ("pipeline", "rows") + + +def _row(value: int) -> pa.Table: + """Two tags and two data columns, including the referenced result ID.""" + return pa.table( + { + "group": pa.array(["a"], type=pa.large_string()), + "tag": [value], + "value": [value * 2], + "result": pa.array([bytes([value])], type=pa.large_binary()), + } + ) + + +def _enqueue( + results: ArrowDatabaseProtocol, pipeline: ArrowDatabaseProtocol, value: int +) -> None: + """Stage a result and a record that may publish only after it commits.""" + result_id = bytes([value]) + row = _row(value) + results.add_record(RESULTS, result_id, row) + pending = results.pending_result(RESULTS, result_id) + assert pending is not None + with pipeline.guard_record(RECORDS, result_id, pending): + pipeline.add_record(RECORDS, result_id, row) + + +@pytest.mark.parametrize("pipeline_store_factory", STORE_KINDS, indirect=True) +@pytest.mark.parametrize("separate", [False, True], ids=["one-store", "two-stores"]) +def test_each_batch_publishes_only_references_to_committed_results( + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], separate: bool +) -> None: + pipeline = pipeline_store_factory("pipeline") + name = "results" if separate else "pipeline" + results = pipeline_store_factory(name) if separate else pipeline + committed: set[bytes] = set() + for batch in ((1, 2), (3, 4), (5,)): + for value in batch: + _enqueue(results, pipeline, value) + + pipeline.flush_batch(RECORDS) + reader = pipeline_store_factory("pipeline") + if reader is not pipeline: + # A fresh handle sees exactly the records from the earlier commits. + visible = reader.get_all_records(RECORDS) + assert ( + set(visible["result"].to_pylist() if visible is not None else ()) + == committed + ) + + results.flush_result_batch(RESULTS, publish_records=True) + pipeline.flush_batch(RECORDS) + + committed.update(bytes([value]) for value in batch) + durable_results = pipeline_store_factory(name).get_all_records(RESULTS) + durable_records = pipeline_store_factory("pipeline").get_all_records(RECORDS) + assert durable_records is not None and durable_results is not None + assert durable_records.num_rows == durable_results.num_rows == len(committed) + assert set(durable_records["result"].to_pylist()) == committed + assert set(durable_results["result"].to_pylist()) == committed + + +@pytest.mark.parametrize("pipeline_store_factory", STORE_KINDS, indirect=True) +@pytest.mark.parametrize("separate", [False, True], ids=["one-store", "two-stores"]) +def test_failed_result_commit_withdraws_guarded_records( + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], separate: bool +) -> None: + pipeline = pipeline_store_factory("pipeline") + name = "results" if separate else "pipeline" + results = pipeline_store_factory(name) if separate else pipeline + + def refuse(_: pa.Schema) -> None: + """Inject a permanent validation failure at the result commit boundary.""" + raise InputValidationError("injected result schema refusal") + + with results.guard_table_schema(RESULTS, refuse): + _enqueue(results, pipeline, 1) + with pytest.raises(InputValidationError, match="injected result schema refusal"): + results.flush_result_batch(RESULTS, publish_records=True) + + pipeline.flush() + assert pipeline_store_factory("pipeline").get_all_records(RECORDS) is None + assert pipeline_store_factory(name).get_all_records(RESULTS) is None + + _enqueue(results, pipeline, 2) + results.flush_result_batch(RESULTS, publish_records=True) + pipeline.flush_batch(RECORDS) + durable_records = pipeline_store_factory("pipeline").get_all_records(RECORDS) + assert durable_records is not None + assert durable_records["result"].to_pylist() == [b"\x02"] diff --git a/tests/test_pipeline/test_sync_async_stored_records.py b/tests/test_pipeline/test_sync_async_stored_records.py index 0130d6c09..69b66b8af 100644 --- a/tests/test_pipeline/test_sync_async_stored_records.py +++ b/tests/test_pipeline/test_sync_async_stored_records.py @@ -8,6 +8,7 @@ from __future__ import annotations +import json from collections.abc import Callable from pathlib import Path from typing import Any @@ -21,14 +22,10 @@ PIPELINE_RUN_ID_COL, ) from orcapod.core.operators import DropDataColumns, SelectDataColumns -from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import ArrowTableSource - -STORES: dict[str, Callable[[Path], Any]] = { - "in_memory": lambda _: InMemoryArrowDatabase(), - "delta": lambda path: DeltaTableDatabase(path), -} +from tests.pipeline_stores import STORE_KINDS, function_store_cases, open_stores # Columns that differ between two runs by design: the output datagram's uuid, the token # that carries it, the result's timestamp, and the entry's recording run and time. @@ -47,17 +44,19 @@ def times_ten(x: int) -> int: return 10 * x -def source() -> ArrowTableSource: - """Tag ``k``; data ``x`` (the pod's input) and ``s``, ``m`` (not its input).""" +def source(reordered: bool = False) -> ArrowTableSource: + """Tags ``k`` and ``session``; data ``x`` (the pod's input) and ``s``, ``m`` (not its input).""" table = pa.table( { "k": ["a", "b", "c"], + "session": [2, 1, 2], "x": [1, 2, 3], "s": ["p", "q", "r"], "m": [0.5, 1.5, 2.5], }, schema=pa.schema( [ + pa.field("session", pa.int64(), nullable=False), pa.field("k", pa.large_string(), nullable=False), pa.field("x", pa.int64(), nullable=False), pa.field("s", pa.large_string(), nullable=False), @@ -65,8 +64,13 @@ def source() -> ArrowTableSource: ] ), ) + if reordered: + table = table.select(["m", "s", "k", "x", "session"]) return ArrowTableSource( - table, tag_columns=["k"], source_id="src", tag_only_columns=True + table, + tag_columns=["session", "k"] if reordered else ["k", "session"], + source_id="src", + tag_only_columns=True, ) @@ -93,12 +97,12 @@ def explicit_drop(src: ArrowTableSource) -> Any: def stored_records( - pipeline: str, orchestrator: str, store_kind: str, directory: Path + pipeline: str, orchestrator: str, store: ArrowDatabaseProtocol, reordered: bool ) -> pa.Table: - """The function node's stored records after a run, rows in tag order.""" - job = PipelineJob(name="itl1040", database=STORES[store_kind](directory)) + """Return the function node's stored records after a run.""" + job = PipelineJob(name="itl1040", database=store) with job: - PIPELINES[pipeline](source()) + PIPELINES[pipeline](source(reordered)) job.run( orchestrator=SyncPipelineOrchestrator() if orchestrator == "sync" @@ -106,33 +110,53 @@ def stored_records( ) records = job.nodes["node"].get_all_records(all_info=True) assert records is not None - return records.sort_by("k") + return records + +def row_set(table: pa.Table) -> set[str]: + """Compare stored row values, including nested values, in any read order.""" + return {json.dumps(row, sort_keys=True, default=repr) for row in table.to_pylist()} -@pytest.mark.parametrize("store_kind", list(STORES)) + +@pytest.mark.parametrize("reordered", [False, True], ids=["mixed", "reordered"]) @pytest.mark.parametrize("pipeline", list(PIPELINES)) +@function_store_cases def test_async_stores_the_records_a_sync_run_stores( - pipeline: str, store_kind: str, tmp_path: Path + pipeline: str, + pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol], + reordered: bool, + tmp_path: Path, ) -> None: - sync = stored_records(pipeline, "sync", store_kind, tmp_path / "sync") - async_ = stored_records(pipeline, "async", store_kind, tmp_path / "async") + sync = stored_records(pipeline, "sync", pipeline_store_factory("sync"), reordered) + async_ = stored_records( + pipeline, "async", pipeline_store_factory("async"), reordered + ) assert async_.schema == sync.schema assert "_source_s" not in async_.column_names assert "_source_m" not in async_.column_names - assert async_.drop_columns(list(PER_RUN_COLUMNS)).equals( - sync.drop_columns(list(PER_RUN_COLUMNS)) - ) + stable_sync = sync.drop_columns(list(PER_RUN_COLUMNS)) + stable_async = async_.drop_columns(list(PER_RUN_COLUMNS)) + assert row_set(stable_async) == row_set(stable_sync) + with open_stores("delta", tmp_path / "reference") as reference: + delta_sync = stored_records(pipeline, "sync", reference("sync"), reordered) + stable_delta = delta_sync.drop_columns(list(PER_RUN_COLUMNS)) + assert stable_sync.schema == stable_delta.schema + assert row_set(stable_sync) == row_set(stable_delta) + +@pytest.mark.parametrize("pipeline_store_factory", STORE_KINDS, indirect=True) @pytest.mark.parametrize("pipeline", ["explicit_select", "explicit_drop"]) def test_the_operator_node_table_is_the_same_on_both_orchestrators( - pipeline: str, + pipeline: str, pipeline_store_factory: Callable[[str], ArrowDatabaseProtocol] ) -> None: """The select or drop node itself shows the same columns after either run.""" tables = [] for orchestrator in (SyncPipelineOrchestrator, AsyncPipelineOrchestrator): - job = PipelineJob(name="itl1040", database=InMemoryArrowDatabase()) + job = PipelineJob( + name="itl1040", database=pipeline_store_factory(orchestrator.__name__) + ) with job: src = source() if pipeline == "explicit_select": @@ -140,6 +164,6 @@ def test_the_operator_node_table_is_the_same_on_both_orchestrators( else: DropDataColumns(["s", "m"])(src, label="op") job.run(orchestrator=orchestrator()) - tables.append(job.nodes["op"].as_table(all_info=True).sort_by("k")) + tables.append(job.nodes["op"].as_table(all_info=True)) assert tables[1].schema == tables[0].schema - assert tables[1].equals(tables[0]) + assert row_set(tables[1]) == row_set(tables[0])