From 1c6547b99fd22b10a70eae7d543b7f6ac7f2d040 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 11:18:32 -0800 Subject: [PATCH 1/8] feat(pipeline): record when and in which run entries were written --- changelog.d/ITL-1433.md | 11 + docs/reference/data-function-types.md | 22 ++ docs/tutorial/08-inspecting-and-tracing.md | 4 +- src/orcapod/core/nodes/function_node.py | 51 ++++ .../test_pipeline_record_metadata.py | 261 ++++++++++++++++++ 5 files changed, 348 insertions(+), 1 deletion(-) create mode 100644 changelog.d/ITL-1433.md create mode 100644 tests/test_pipeline/test_pipeline_record_metadata.py diff --git a/changelog.d/ITL-1433.md b/changelog.d/ITL-1433.md new file mode 100644 index 000000000..d46e336d9 --- /dev/null +++ b/changelog.d/ITL-1433.md @@ -0,0 +1,11 @@ +### Added + +- Function-node pipeline records now include the recording job's run ID + (`__pipeline_run_id`) and the UTC recording time (`__recorded_at`). Standalone + node runs store a null run ID. Recomputing a lost result creates a new entry + with its own recording metadata. + +### Breaking changes and migration + +- Pipeline tables written by 0.4.0rc1 through 0.4.0rc3 lack these columns and + must be rebuilt before appending. The layout remains `pdb_v1`. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 8880c5432..3ba4fd8e4 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -145,6 +145,28 @@ print([name for name in stored.column_names if name.startswith("__pf_var_")]) # ['__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash'] ``` +## The pipeline columns, `pdb_v1` + +A function node's pipeline table stores the input tags and source-info tokens, +the input and output hashes, the referenced result record ID, and bookkeeping +for the entry, including: + +| Column | Arrow type | Nullable | Meaning | +|---|---|---|---| +| `__pipeline_run_id` | `large_string` | yes | The ID of the job run that recorded the entry. A node run outside a job stores null. | +| `__recorded_at` | `timestamp[us, tz=UTC]` | no | The UTC time the node recorded the entry. | + +The node records an entry when it first sees an input, even when the function +result already exists in the result database. Reusing a pipeline entry preserves +its original run ID and recording time. If the result is lost and the node +recomputes it, the new entry has its own run ID and recording time. A load-only +run writes nothing. Neither column enters any hash. + +Read these columns on joined records with +`node.get_all_records(columns={"meta": True})` or `node.get_all_records(all_info=True)`. +Pipeline tables written by 0.4.0rc1 through 0.4.0rc3 lack these columns. Rebuild +those pipeline tables before appending to them. The layout name stays `pdb_v1`. + ## Where it is declared, and how a released declaration is kept The declaration is code: `PYTHON_FUNCTION` in `orcapod.core.data_function`, beside the diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md index 18c3f5dea..6a4ae4e17 100644 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ b/docs/tutorial/08-inspecting-and-tracing.md @@ -157,7 +157,7 @@ call. `get_all_records` returns them; ask for the `meta` columns to see the deta records = pl.from_arrow(job.nodes["rates"].get_all_records(columns={"meta": True})) meta = [c for c in records.columns if c.startswith("__")] print(meta) -# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts'] +# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__pipeline_run_id', '__recorded_at', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts'] ``` The ones you are most likely to want: @@ -169,6 +169,8 @@ The ones you are most likely to want: | `__pf_exec_python_version` | The Python version it ran under | | `__pf_var_git_hash` | The git commit of the code, when run inside a git repository | | `__computed` | `True` if this row was computed, `False` if it reused the result of an identical input | +| `__pipeline_run_id` | The job run that recorded the pipeline entry | +| `__recorded_at` | When the pipeline entry was recorded, in UTC | | `__input_data_hash` | The hash of the input values: the key the result is stored under (Part 6) | ```python diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 2465e89d5..4730450ef 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -25,6 +25,7 @@ from abc import abstractmethod from collections import Counter from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from datetime import datetime, timezone from typing import Any, Literal, NamedTuple, cast import polars as pl @@ -134,6 +135,9 @@ # 0 for the first computation, N+1 for each miss-triggered recompute. _PIPELINE_RECOMPUTATION_INDEX_COL = "__pipeline_recomputation_index" +PIPELINE_RUN_ID_COL = "__pipeline_run_id" +PIPELINE_RECORDED_AT_COL = "__recorded_at" + def _pipeline_meta_schema() -> pa.Schema: """The bookkeeping columns of a function node's pipeline record (``pdb_v1``). @@ -153,6 +157,10 @@ def _pipeline_meta_schema() -> pa.Schema: pa.field(constants.IS_EPHEMERAL_COL, pa.bool_()), pa.field(_PIPELINE_BASE_ENTRY_ID_COL, pa.large_binary()), pa.field(_PIPELINE_RECOMPUTATION_INDEX_COL, pa.int32()), + pa.field(PIPELINE_RUN_ID_COL, pa.large_string()), + pa.field( + PIPELINE_RECORDED_AT_COL, pa.timestamp("us", tz="UTC"), nullable=False + ), ] ) @@ -1409,6 +1417,8 @@ class FunctionJobNode(RunHoldingNode, FunctionNodeBase): _stale_tables_checked: bool = False # Set once the rows of the current tables were counted by data context. _current_tables_checked: bool = False + # Check an attached table before the first potential write, even if it is pdb_v1. + _pipeline_write_schema_checked: bool = False # Set once a database that cannot list its tables was reported. _unlisted_store_reported: bool = False # Base entry ids of the inputs of the last completed run in this process, each with @@ -1694,6 +1704,7 @@ def attach_databases( # Another database has its own tables of other generations to account for. self._stale_tables_checked = False self._current_tables_checked = False + self._pipeline_write_schema_checked = False self._unlisted_store_reported = False self._skipped_rows_reported = False # ... and its own rows to compare with the job file's expected count. @@ -2818,6 +2829,7 @@ def _process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, base_entry_id) + self._require_current_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) if ephemeral_result: @@ -2848,6 +2860,7 @@ def _process_data_internal( computed=result_computed, is_ephemeral=True, output_data_hash=output_data.content_hash(), + run_id=run_id, ) elif self._cached_function_pod is not None: tag_out, output_data = self._cached_function_pod.process_data( @@ -2869,6 +2882,7 @@ def _process_data_internal( data_record_id=output_data.datagram_uuid, computed=result_computed, output_data_hash=output_data.content_hash(), + run_id=run_id, ) else: tag_out, output_data = self._function_pod.process_data( @@ -2956,6 +2970,7 @@ async def _async_process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, base_entry_id) + self._require_current_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) if ephemeral_result: @@ -3111,6 +3126,8 @@ def add_pipeline_record( computed: bool, is_ephemeral: bool = False, output_data_hash: ContentHash | None = None, + *, + run_id: str | None = None, ) -> None: """Add a pipeline record to the database for a processed data. @@ -3131,6 +3148,7 @@ def add_pipeline_record( - Whether the result is stored in the ephemeral database - Input data context key - Whether the result was freshly computed or cached + - The run ID and the UTC recording time - Output data content hash (``OUTPUT_DATA_HASH_COL``) — used by downstream ``EmptyData`` flow-through to look up the downstream result cache. @@ -3145,6 +3163,7 @@ def add_pipeline_record( ``input_data``. When provided, stored as ``OUTPUT_DATA_HASH_COL`` so that downstream ``EmptyData`` flow-through can locate its cached result keyed by the same hash (= the downstream's ``INPUT_DATA_HASH_COL``). + run_id: ID of the run recording the entry, if any. """ self._add_pipeline_record( tag, @@ -3154,6 +3173,7 @@ def add_pipeline_record( computed=computed, is_ephemeral=is_ephemeral, output_data_hash=output_data_hash, + run_id=run_id, ) def _add_pipeline_record( @@ -3165,6 +3185,8 @@ def _add_pipeline_record( computed: bool, is_ephemeral: bool = False, output_data_hash: ContentHash | None = None, + *, + run_id: str | None = None, ) -> None: """``add_pipeline_record`` with the row's base entry id already computed. @@ -3176,6 +3198,7 @@ def _add_pipeline_record( computed: Whether the result was freshly computed. is_ephemeral: Whether the result is stored in the ephemeral database. output_data_hash: Content hash of the output, if any. + run_id: ID of the run recording the entry, if any. """ pipeline_database = self._require_pipeline_database() # The row key combines the input's hash with this node's hasher: an input @@ -3184,6 +3207,7 @@ def _add_pipeline_record( input_data.data_context_key, self._stored_data_context_key ) self._account_for_stale_tables() + self._require_current_pipeline_write_schema() # Determine the next recomputation index by querying all existing rows # for this base_entry_id. No await is used here, so within a single-threaded @@ -3232,6 +3256,8 @@ def _add_pipeline_record( constants.IS_EPHEMERAL_COL: [is_ephemeral], _PIPELINE_BASE_ENTRY_ID_COL: [base_entry_id], _PIPELINE_RECOMPUTATION_INDEX_COL: [new_index], + PIPELINE_RUN_ID_COL: [run_id], + PIPELINE_RECORDED_AT_COL: [datetime.now(timezone.utc)], }, schema=_pipeline_meta_schema(), ) @@ -3262,6 +3288,29 @@ def _add_pipeline_record( tag=tag.as_dict(), ) from exc + def _require_current_pipeline_write_schema(self) -> None: + """Refuse to extend a prerelease pipeline table with the same layout name.""" + database = self._pipeline_database + if self._pipeline_write_schema_checked or database is None: + return + path = self._versioned_pipeline_path + existing = database.get_all_records(path) + if existing is not None: + missing = [ + name + for name in (PIPELINE_RUN_ID_COL, PIPELINE_RECORDED_AT_COL) + if name not in existing.column_names + ] + if missing: + raise OrcapodDatabaseError( + f"Cannot append a pipeline record to the " + f"{describe_database_table(database, path)}: missing bookkeeping " + f"columns {', '.join(missing)}. Rebuild the pipeline table " + "with the current version of Orcapod.", + node_label=self.label, + ) + self._pipeline_write_schema_checked = True + # ------------------------------------------------------------------ # Records and sources # ------------------------------------------------------------------ @@ -4370,6 +4419,7 @@ async def route_inputs() -> None: run_entry_ids.append(base_entry_id) await output.send((cached_tag, cached_data)) else: + self._require_current_pipeline_write_schema() correlation_key = uuid.uuid4().bytes input_store[correlation_key] = ( tag, @@ -4411,6 +4461,7 @@ async def record_and_forward() -> None: computed=result_computed, is_ephemeral=is_ephemeral, output_data_hash=output_data.content_hash(), + run_id=run_id, ) except OrcapodDatabaseError as exc: # This runs outside the pod's per-row handler: name the diff --git a/tests/test_pipeline/test_pipeline_record_metadata.py b/tests/test_pipeline/test_pipeline_record_metadata.py new file mode 100644 index 000000000..95b68fab5 --- /dev/null +++ b/tests/test_pipeline/test_pipeline_record_metadata.py @@ -0,0 +1,261 @@ +"""Pipeline entries retain the run and recording time of their first write.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone +from pathlib import Path +from typing import cast + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.channels import Channel +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import OrcapodDatabaseError, UnstorableColumnError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +from orcapod.sources import DictSource +from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION +from orcapod.types import NodeConfig + +RUN_ID = "__pipeline_run_id" +RECORDED_AT = "__recorded_at" +INDEX = "__pipeline_recomputation_index" +BASE_ENTRY = "__pipeline_base_entry_id" +RECORD_ID = "__record_id" +ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + + +@function_pod(output_keys=("total", "doubled")) +def summarize(x: int, y: int) -> tuple[int, int]: + """Compute two columns from two inputs.""" + return x + y, 2 * y + + +def source(count: int = 2, *, reverse: bool = False) -> DictSource: + """Build rows with two tags and two data columns.""" + rows = [ + {"site": f"site_{i}", "group": f"group_{i % 2}", "x": i, "y": i + 10} + for i in range(count) + ] + return DictSource( + [dict(reversed(tuple(row.items()))) for row in rows] if reverse else rows, + tag_columns=["group", "site"] if reverse else ["site", "group"], + tag_only_columns=True, + source_id="record_metadata_source", + ) + + +def job_and_node( + store: ArrowDatabaseProtocol, + *, + count: int = 2, + reverse: bool = False, + ephemeral: InMemoryArrowDatabase | None = None, +) -> tuple[PipelineJob, FunctionJobNode]: + """Build a fresh job over the same function and pipeline table.""" + job = PipelineJob(name="record_metadata", database=store) + with job: + _ = summarize.pod(source(count, reverse=reverse), label="summarize") + if ephemeral is not None: + job.set_ephemeral_database(ephemeral) + job.apply_node_config(NodeConfig(is_result_ephemeral=True)) + node = job.nodes["summarize"] + assert isinstance(node, FunctionJobNode) + return job, node + + +def pipeline_path(store: ArrowDatabaseProtocol) -> tuple[str, ...]: + """Find this test's one pipeline table.""" + (path,) = [ + path + for path in store.list_table_paths() + if path[-1] == PIPELINE_DB_SCHEMA_VERSION + ] + return path + + +def pipeline_rows(store: ArrowDatabaseProtocol) -> pa.Table: + """Read the pipeline table with stable ordering and its physical row ID.""" + table = store.get_all_records(pipeline_path(store), record_id_column=RECORD_ID) + assert table is not None + return table.sort_by([("site", "ascending"), (INDEX, "ascending")]) + + +class RunObserver(NoOpObserver): + """Capture the same identifier reported to callers at job start.""" + + run_id: str | None = None + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + """Keep the ID of the job run.""" + self.run_id = run_id + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("ephemeral", [False, True], ids=["persistent", "ephemeral"]) +def test_job_records_keep_their_original_metadata( + orchestrator: str, ephemeral: bool +) -> None: + """Fresh writes, reuses, load-only misses and lost results have distinct behavior.""" + store = InMemoryArrowDatabase() + results = InMemoryArrowDatabase() if ephemeral else None + run = ORCHESTRATORS[orchestrator] + first, node = job_and_node(store, ephemeral=results) + observer = RunObserver() + before = datetime.now(timezone.utc) + _ = first.run(orchestrator=run(), observer=observer) + after = datetime.now(timezone.utc) + assert observer.run_id + + original = pipeline_rows(store) + assert original.schema.field(RUN_ID) == pa.field(RUN_ID, pa.large_string()) + assert original.schema.field(RECORDED_AT) == pa.field( + RECORDED_AT, pa.timestamp("us", tz="UTC"), nullable=False + ) + assert original[RUN_ID].to_pylist() == [observer.run_id] * 2 + assert original[INDEX].to_pylist() == [0, 0] + original_times = cast(list[datetime], original[RECORDED_AT].to_pylist()) + assert all(before <= recorded <= after for recorded in original_times) + + joined = node.get_all_records(columns={"meta": True}) + assert joined is not None + assert ( + joined.sort_by("site") + .select([RUN_ID, RECORDED_AT]) + .equals(original.select([RUN_ID, RECORDED_AT])) + ) + assert sorted(zip(joined["total"].to_pylist(), joined["doubled"].to_pylist())) == [ + (10, 20), + (12, 22), + ] + plain = node.get_all_records() + assert plain is not None and RUN_ID not in plain.column_names + + second, _ = job_and_node(store, reverse=True, ephemeral=results) + _ = second.run(orchestrator=run()) + assert pipeline_rows(store).equals(original) + + load, _ = job_and_node(store, count=3, reverse=True, ephemeral=results) + loaded = load.run(orchestrator=run(), load_only=True) + assert loaded.nodes["summarize"].reused == 2 + assert pipeline_rows(store).equals(original) + + if ephemeral: + recompute, _ = job_and_node(store, ephemeral=InMemoryArrowDatabase()) + next_run = RunObserver() + before_recompute = datetime.now(timezone.utc) + _ = recompute.run(orchestrator=run(), observer=next_run) + after_recompute = datetime.now(timezone.utc) + assert next_run.run_id and next_run.run_id != observer.run_id + records = pipeline_rows(store) + assert records.filter(pc.field(INDEX) == 0).equals(original) + new = records.filter(pc.field(INDEX) == 1) + assert new[BASE_ENTRY].to_pylist() == original[BASE_ENTRY].to_pylist() + assert set(new[RECORD_ID].to_pylist()).isdisjoint( + original[RECORD_ID].to_pylist() + ) + assert new[RUN_ID].to_pylist() == [next_run.run_id] * 2 + new_times = cast(list[datetime], new[RECORDED_AT].to_pylist()) + assert all( + before_recompute <= recorded <= after_recompute for recorded in new_times + ) + + +async def execute_standalone_async(node: FunctionJobNode, stream: DictSource) -> None: + """Run the standalone node through its channel interface.""" + inputs = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=2) + outputs = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=2) + for row in stream.iter_data(): + await inputs.writer.send(row) + await inputs.writer.close() + await node.async_execute(inputs.reader, outputs.writer) + assert len([row async for row in outputs.reader]) == 2 + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_standalone_nodes_with_a_separate_result_database(orchestrator: str) -> None: + """Both newly computed and reused results get a null standalone run ID.""" + results = InMemoryArrowDatabase() + pod = summarize.pod + assert isinstance(pod, FunctionPod) + for computed in (True, False): + store = InMemoryArrowDatabase() + stream = source(reverse=not computed) + node = FunctionJobNode( + function_pod=pod, + input_stream=stream, + pipeline_database=store, + result_database=results, + ) + if orchestrator == "async": + asyncio.run(execute_standalone_async(node, stream)) + results.flush() + store.flush() + else: + _ = node.run() + + assert len(results.list_table_paths()) == 1 + table = pipeline_rows(store) + assert table[RUN_ID].to_pylist() == [None, None] + assert table[RECORDED_AT].null_count == 0 + assert table["__computed"].to_pylist() == [computed, computed] + joined = node.get_all_records(all_info=True) + assert joined is not None and joined[RUN_ID].to_pylist() == [None, None] + + +@pytest.mark.parametrize("column", [RUN_ID, RECORDED_AT]) +def test_attach_checks_pipeline_metadata_support(column: str) -> None: + """A pipeline database can refuse either field before the node runs.""" + + class RejectsColumn(InMemoryArrowDatabase): + """Reject writes of one pipeline metadata column.""" + + def require_storable(self, schema: pa.Schema) -> None: + """Raise when the column appears in an attached table's schema.""" + if column in schema.names: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=column, + arrow_type=schema.field(column).type, + reason="unsupported by this test database", + ) + + pod = summarize.pod + assert isinstance(pod, FunctionPod) + node = FunctionJobNode(function_pod=pod, input_stream=source()) + with pytest.raises(UnstorableColumnError) as info: + node.attach_databases(RejectsColumn(), result_database=InMemoryArrowDatabase()) + assert info.value.column == column and info.value.node_label == node.label + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_prerelease_pipeline_table_must_be_rebuilt( + orchestrator: str, tmp_path: Path +) -> None: + """Refuse an append even when the backend allows schema evolution.""" + store = InMemoryArrowDatabase() + job, _ = job_and_node(store) + _ = job.run() + path = pipeline_path(store) + legacy = pipeline_rows(store).drop([RUN_ID, RECORDED_AT]) + destination = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + destination.add_records(path, legacy, record_id_column=RECORD_ID, flush=True) + + writer, _ = job_and_node(destination, count=3) + with pytest.raises((OrcapodDatabaseError, ExceptionGroup)) as info: + _ = writer.run(orchestrator=ORCHESTRATORS[orchestrator]()) + error = info.value + if isinstance(error, ExceptionGroup): + (error,) = OrcapodDatabaseError.in_group(error) + assert "Rebuild the pipeline table" in str(error) + assert RUN_ID in str(error) and RECORDED_AT in str(error) + assert pipeline_rows(destination).equals(legacy) + assert destination.list_table_paths() == [path] From 4b48d97fccd3091abc78c029d6515f594ba3a29a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 11:33:37 -0800 Subject: [PATCH 2/8] fix(pipeline): inspect current schema before appending records --- changelog.d/ITL-1433.md | 10 +- docs/reference/data-function-types.md | 19 ++- src/orcapod/core/nodes/function_node.py | 88 ++++++---- .../databases/connector_arrow_database.py | 11 ++ src/orcapod/databases/delta_lake_databases.py | 16 ++ .../databases/extension_aware_database.py | 4 + src/orcapod/databases/in_memory_databases.py | 5 + src/orcapod/databases/noop_database.py | 4 + src/orcapod/protocols/database_protocols.py | 8 + .../test_mixed_function_commits.py | 4 + .../test_pipeline_record_metadata.py | 150 ++++++++++++++++-- 11 files changed, 264 insertions(+), 55 deletions(-) diff --git a/changelog.d/ITL-1433.md b/changelog.d/ITL-1433.md index d46e336d9..b0b96b0a1 100644 --- a/changelog.d/ITL-1433.md +++ b/changelog.d/ITL-1433.md @@ -2,10 +2,14 @@ - Function-node pipeline records now include the recording job's run ID (`__pipeline_run_id`) and the UTC recording time (`__recorded_at`). Standalone - node runs store a null run ID. Recomputing a lost result creates a new entry - with its own recording metadata. + node runs store a null run ID. Entries require an output. Recomputing a lost + result creates a new entry with its own recording metadata. Within a run, + sync execution reuses the first entry for an identical input without system + tags. Async execution can schedule both copies before either entry is + available and record them separately. ### Breaking changes and migration - Pipeline tables written by 0.4.0rc1 through 0.4.0rc3 lack these columns and - must be rebuilt before appending. The layout remains `pdb_v1`. + must be rebuilt before appending, even if they contain no rows. The layout + remains `pdb_v1`. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 3ba4fd8e4..e214affc1 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -156,16 +156,23 @@ for the entry, including: | `__pipeline_run_id` | `large_string` | yes | The ID of the job run that recorded the entry. A node run outside a job stores null. | | `__recorded_at` | `timestamp[us, tz=UTC]` | no | The UTC time the node recorded the entry. | -The node records an entry when it first sees an input, even when the function -result already exists in the result database. Reusing a pipeline entry preserves -its original run ID and recording time. If the result is lost and the node -recomputes it, the new entry has its own run ID and recording time. A load-only -run writes nothing. Neither column enters any hash. +The node writes a pipeline entry only when processing yields an output. The +output can come from a new function call or from a result already in the result +database. A null value in a declared nullable output still counts as an output. +Reusing a pipeline entry preserves its original run ID and recording +time. If the result is lost and the node recomputes it, the new entry has its +own run ID and recording time. + +During a sync run, a repeated identical input without system tags reuses the +first entry. During an async run, both copies can be scheduled before either +entry is available, producing two entries with successive recomputation indices. +A load-only run writes nothing. Neither recording column enters any hash. Read these columns on joined records with `node.get_all_records(columns={"meta": True})` or `node.get_all_records(all_info=True)`. Pipeline tables written by 0.4.0rc1 through 0.4.0rc3 lack these columns. Rebuild -those pipeline tables before appending to them. The layout name stays `pdb_v1`. +those tables before appending, even if their rows have been deleted. The layout +name stays `pdb_v1`. ## Where it is declared, and how a released declaration is kept diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 4730450ef..55ec23cd4 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -138,6 +138,11 @@ PIPELINE_RUN_ID_COL = "__pipeline_run_id" PIPELINE_RECORDED_AT_COL = "__recorded_at" +_PIPELINE_RECORDING_FIELDS = ( + pa.field(PIPELINE_RUN_ID_COL, pa.large_string()), + pa.field(PIPELINE_RECORDED_AT_COL, pa.timestamp("us", tz="UTC"), nullable=False), +) + def _pipeline_meta_schema() -> pa.Schema: """The bookkeeping columns of a function node's pipeline record (``pdb_v1``). @@ -157,10 +162,7 @@ def _pipeline_meta_schema() -> pa.Schema: pa.field(constants.IS_EPHEMERAL_COL, pa.bool_()), pa.field(_PIPELINE_BASE_ENTRY_ID_COL, pa.large_binary()), pa.field(_PIPELINE_RECOMPUTATION_INDEX_COL, pa.int32()), - pa.field(PIPELINE_RUN_ID_COL, pa.large_string()), - pa.field( - PIPELINE_RECORDED_AT_COL, pa.timestamp("us", tz="UTC"), nullable=False - ), + *_PIPELINE_RECORDING_FIELDS, ] ) @@ -1417,8 +1419,8 @@ class FunctionJobNode(RunHoldingNode, FunctionNodeBase): _stale_tables_checked: bool = False # Set once the rows of the current tables were counted by data context. _current_tables_checked: bool = False - # Check an attached table before the first potential write, even if it is pdb_v1. - _pipeline_write_schema_checked: bool = False + # Preflight the first miss before invoking user code. Each append checks again. + _pipeline_preflight_checked: bool = False # Set once a database that cannot list its tables was reported. _unlisted_store_reported: bool = False # Base entry ids of the inputs of the last completed run in this process, each with @@ -1540,7 +1542,7 @@ def _delivers_side_effects(self) -> bool: ) def _begin_run(self) -> None: - """Make a node that delivers side effects look for older completions again. + """Reset schema preflight and check older completions for side effects. Tables written before v0.3 can appear in a database between two runs of one node object. Such a node must find them before it delivers anything, so it @@ -1551,6 +1553,7 @@ def _begin_run(self) -> None: SideEffectLogDataContextError: If this node delivers side effects and completions it cannot match exist; nothing has been delivered then. """ + self._pipeline_preflight_checked = False if self._delivers_side_effects: self._stale_tables_checked = False self._account_for_stale_tables() @@ -1704,7 +1707,7 @@ def attach_databases( # Another database has its own tables of other generations to account for. self._stale_tables_checked = False self._current_tables_checked = False - self._pipeline_write_schema_checked = False + self._pipeline_preflight_checked = False self._unlisted_store_reported = False self._skipped_rows_reported = False # ... and its own rows to compare with the job file's expected count. @@ -2801,15 +2804,12 @@ def _process_data_internal( When ``node_config.is_result_ephemeral=True``: - Uses ``_ephemeral_cached_pod`` for both compute and storage. - Raises ``RuntimeError`` if no ephemeral database has been set. - - Calls ``add_pipeline_record`` which computes the next recomputation - index (``max_index + 1``) and writes with ``skip_duplicates=True`` - so concurrent coroutines are safely serialised. When ``node_config.is_result_ephemeral=False`` (default): - Uses ``_cached_function_pod`` (persistent DB) or raw function pod. - - Calls ``add_pipeline_record`` which computes the next recomputation - index (``max_index + 1``) and writes with ``skip_duplicates=True`` - so concurrent coroutines are safely serialised. + + When a pipeline database is attached, a result produced here is recorded + at the next recomputation index, using ``skip_duplicates=True``. Returns: A ``(tag, output_data)`` 2-tuple. @@ -2829,7 +2829,7 @@ def _process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, base_entry_id) - self._require_current_pipeline_write_schema() + self._require_current_pipeline_write_schema(before_compute=True) ephemeral_result = bool(self._node_config.is_result_ephemeral) if ephemeral_result: @@ -2970,7 +2970,7 @@ async def _async_process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, base_entry_id) - self._require_current_pipeline_write_schema() + self._require_current_pipeline_write_schema(before_compute=True) ephemeral_result = bool(self._node_config.is_result_ephemeral) if ephemeral_result: @@ -3129,14 +3129,15 @@ def add_pipeline_record( *, run_id: str | None = None, ) -> None: - """Add a pipeline record to the database for a processed data. + """Add a pipeline record for a row that produced output. Computes the next recomputation index by querying existing rows in the pipeline DB that share the same ``base_entry_id``, then writes at - ``max_index + 1``. The write uses ``skip_duplicates=True`` so that - concurrent asyncio coroutines competing for the same versioned entry ID - are safely serialised: the first writer lands, subsequent writers whose - compute happened to produce the same hash are silently no-oped. + ``max_index + 1``. The database skips duplicate versioned entry IDs. + Sync execution ordinarily reuses the first recorded result for an + identical input in the same run. Async execution can schedule both + copies of an identical input without system tags before either entry is + available, and can write separate entries with successive indices. The pipeline record stores: @@ -3288,28 +3289,43 @@ def _add_pipeline_record( tag=tag.as_dict(), ) from exc - def _require_current_pipeline_write_schema(self) -> None: - """Refuse to extend a prerelease pipeline table with the same layout name.""" + def _require_current_pipeline_write_schema( + self, *, before_compute: bool = False + ) -> None: + """Check the stored schema before each append and before the first computation. + + Args: + before_compute: Preflight before executing a function on a cache miss. + Only this early check can reuse a prior check from the same run. + """ database = self._pipeline_database - if self._pipeline_write_schema_checked or database is None: + if database is None or (before_compute and self._pipeline_preflight_checked): return path = self._versioned_pipeline_path - existing = database.get_all_records(path) + existing = database.get_table_schema(path) if existing is not None: - missing = [ - name - for name in (PIPELINE_RUN_ID_COL, PIPELINE_RECORDED_AT_COL) - if name not in existing.column_names - ] - if missing: + issues: list[str] = [] + for expected in _PIPELINE_RECORDING_FIELDS: + index = existing.get_field_index(expected.name) + if index < 0: + issues.append(f"missing {expected.name}") + continue + actual_type = arrow_utils.normalize_to_large_types( + existing.field(index).type, keep_null=True + ) + if actual_type != expected.type: + issues.append( + f"{expected.name} has type {actual_type}, expected {expected.type}" + ) + if issues: raise OrcapodDatabaseError( f"Cannot append a pipeline record to the " - f"{describe_database_table(database, path)}: missing bookkeeping " - f"columns {', '.join(missing)}. Rebuild the pipeline table " + f"{describe_database_table(database, path)}: " + f"{', '.join(issues)}. Rebuild the pipeline table " "with the current version of Orcapod.", node_label=self.label, ) - self._pipeline_write_schema_checked = True + self._pipeline_preflight_checked = True # ------------------------------------------------------------------ # Records and sources @@ -4419,7 +4435,9 @@ async def route_inputs() -> None: run_entry_ids.append(base_entry_id) await output.send((cached_tag, cached_data)) else: - self._require_current_pipeline_write_schema() + self._require_current_pipeline_write_schema( + before_compute=True + ) correlation_key = uuid.uuid4().bytes input_store[correlation_key] = ( tag, diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 134aebe04..81b97eca9 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -315,6 +315,17 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ── Storable columns ────────────────────────────────────────────────────── + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Read the connector's current column definitions without fetching rows.""" + table_name = self._path_to_table_name(self._path_prefix + record_path) + self._require_table_name(table_name) + if table_name not in self._connector.get_table_names(): + return None + return pa.schema( + pa.field(column.name, column.arrow_type, nullable=column.nullable) + for column in self._connector.get_column_info(table_name) + ) + def require_storable(self, schema: pa.Schema) -> None: """Refuse a table schema with a column the connector cannot store (ITL-1162). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index a9ae8ff33..e010f9464 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1589,6 +1589,22 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: self._absent_tables.discard(self._get_record_key(record_path)) return self._get_delta_table(record_path) is not None + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Read the latest Delta schema from the log without loading data files.""" + from deltalake.exceptions import TableNotFoundError + + try: + table = deltalake.DeltaTable( + self._get_table_uri(record_path), + storage_options=self._storage_options or None, + without_files=True, + ) + return pa.schema(_held_columns(table).values()) + except TableNotFoundError: + return None + except Exception as exc: + raise self._read_failed(record_path) from exc + def _ensure_record_id_column( self, arrow_data: pa.Table, record_id: str | bytes ) -> pa.Table: diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 74a4aa218..8a540f2ef 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -76,6 +76,10 @@ def _process(self, table: pa.Table | None) -> pa.Table | None: # ── Read methods ────────────────────────────────────────────────────────── + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Read the current stored schema from the wrapped database.""" + return self._db.get_table_schema(record_path) + def get_record_by_id( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index a85ea6b16..1aea73132 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -548,6 +548,11 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # Read helpers # ------------------------------------------------------------------ + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Return the committed table's schema, if present.""" + table = self._tables.get(self._get_record_key(record_path)) + return None if table is None else table.schema + def _combined_table(self, record_key: str) -> "pa.Table | None": """Return pending + committed data for a key, or None if nothing exists.""" parts = [] diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 3b5b06967..17d2f95ca 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -152,6 +152,10 @@ def base_path(self) -> tuple[str, ...]: """The current relative root of this database view (always () for root instances).""" return self._path_prefix + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Return no schema because this database stores no tables.""" + return None + def at(self, *path_components: str) -> "NoOpArrowDatabase": """Return a new NoOpArrowDatabase scoped to the given sub-path. diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index be9903977..db76de770 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -165,6 +165,14 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: """ ... + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Read the current stored schema, including for an empty table. + + The path is relative to this database view. A missing table gives + ``None``. This operation reads schema metadata without fetching rows. + """ + ... + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 03182fff7..1e98e5a6a 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -436,6 +436,10 @@ def from_config(cls, config: dict[str, Any]) -> Self: class ProtocolDatabase(DatabaseWithoutCommitGuards): """Forward the complete protocol without exposing unrelated backend methods.""" + def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: + """Read the wrapped store's current schema.""" + return self._inner.get_table_schema(record_path) + @property def stores_records(self) -> bool: return self._inner.stores_records diff --git a/tests/test_pipeline/test_pipeline_record_metadata.py b/tests/test_pipeline/test_pipeline_record_metadata.py index 95b68fab5..1679cf8c4 100644 --- a/tests/test_pipeline/test_pipeline_record_metadata.py +++ b/tests/test_pipeline/test_pipeline_record_metadata.py @@ -7,19 +7,23 @@ from pathlib import Path from typing import cast +import deltalake import pyarrow as pa import pyarrow.compute as pc import pytest from orcapod import PipelineJob, function_pod from orcapod.channels import Channel +from orcapod.core.data_function import PythonDataFunction from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.streams import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import OrcapodDatabaseError, UnstorableColumnError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.sources import DictSource from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION @@ -169,15 +173,27 @@ def test_job_records_keep_their_original_metadata( ) -async def execute_standalone_async(node: FunctionJobNode, stream: DictSource) -> None: +async def execute_standalone_async( + node: FunctionJobNode, stream: StreamProtocol +) -> int: """Run the standalone node through its channel interface.""" - inputs = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=2) - outputs = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=2) - for row in stream.iter_data(): + rows = list(stream.iter_data()) + inputs = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=len(rows)) + outputs = Channel[tuple[TagProtocol, DataProtocol]](buffer_size=len(rows)) + for row in rows: await inputs.writer.send(row) await inputs.writer.close() await node.async_execute(inputs.reader, outputs.writer) - assert len([row async for row in outputs.reader]) == 2 + return len([row async for row in outputs.reader]) + + +def execute_standalone( + node: FunctionJobNode, stream: StreamProtocol, orchestrator: str +) -> int: + """Execute over the supplied rows without changing the node's path.""" + if orchestrator == "async": + return asyncio.run(execute_standalone_async(node, stream)) + return len(list(node.execute(stream).iter_data())) @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) @@ -196,7 +212,7 @@ def test_standalone_nodes_with_a_separate_result_database(orchestrator: str) -> result_database=results, ) if orchestrator == "async": - asyncio.run(execute_standalone_async(node, stream)) + assert asyncio.run(execute_standalone_async(node, stream)) == 2 results.flush() store.flush() else: @@ -237,17 +253,36 @@ def require_storable(self, schema: pa.Schema) -> None: @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) -def test_prerelease_pipeline_table_must_be_rebuilt( - orchestrator: str, tmp_path: Path +@pytest.mark.parametrize("variant", ["nonempty", "empty", "wrong-type"]) +def test_pipeline_table_with_incompatible_schema_must_be_rebuilt( + orchestrator: str, variant: str, tmp_path: Path ) -> None: """Refuse an append even when the backend allows schema evolution.""" store = InMemoryArrowDatabase() job, _ = job_and_node(store) _ = job.run() path = pipeline_path(store) - legacy = pipeline_rows(store).drop([RUN_ID, RECORDED_AT]) + current = pipeline_rows(store) + if variant == "wrong-type": + legacy = current.set_column( + current.schema.get_field_index(RECORDED_AT), + pa.field(RECORDED_AT, pa.int64(), nullable=False), + pa.array([0, 1], type=pa.int64()), + ) + else: + legacy = current.drop([RUN_ID, RECORDED_AT]) destination = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) destination.add_records(path, legacy, record_id_column=RECORD_ID, flush=True) + if variant == "empty": + delta = deltalake.DeltaTable(str(tmp_path.joinpath(*path))) + _ = delta.delete() + assert ( + deltalake.DeltaTable(str(tmp_path.joinpath(*path))) + .to_pyarrow_table() + .num_rows + == 0 + ) + destination = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) writer, _ = job_and_node(destination, count=3) with pytest.raises((OrcapodDatabaseError, ExceptionGroup)) as info: @@ -256,6 +291,99 @@ def test_prerelease_pipeline_table_must_be_rebuilt( if isinstance(error, ExceptionGroup): (error,) = OrcapodDatabaseError.in_group(error) assert "Rebuild the pipeline table" in str(error) - assert RUN_ID in str(error) and RECORDED_AT in str(error) - assert pipeline_rows(destination).equals(legacy) + if variant == "wrong-type": + assert f"{RECORDED_AT} has type int64, expected timestamp[us, tz=UTC]" in str( + error + ) + else: + assert RUN_ID in str(error) and RECORDED_AT in str(error) + if variant == "empty": + assert destination.get_all_records(path) is None + else: + assert pipeline_rows(destination).equals(legacy) assert destination.list_table_paths() == [path] + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_the_same_node_refuses_a_restored_prerelease_schema( + orchestrator: str, tmp_path: Path +) -> None: + """Restoring version zero replaces the schema under a live writer.""" + store = InMemoryArrowDatabase() + job, _ = job_and_node(store) + _ = job.run() + path = pipeline_path(store) + current = pipeline_rows(store) + legacy = current.drop([RUN_ID, RECORDED_AT]) + destination = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + destination.add_records(path, legacy, record_id_column=RECORD_ID, flush=True) + + uri = str(tmp_path.joinpath(*path)) + deltalake.write_deltalake(uri, current, mode="overwrite", schema_mode="overwrite") + destination = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + writer, node = job_and_node(destination) + _ = writer.run(orchestrator=ORCHESTRATORS[orchestrator]()) + delta = deltalake.DeltaTable(uri) + _ = delta.restore(0) + + node.clear_cache() + with pytest.raises((OrcapodDatabaseError, ExceptionGroup)) as info: + _ = execute_standalone(node, source(3), orchestrator) + error = info.value + if isinstance(error, ExceptionGroup): + (error,) = OrcapodDatabaseError.in_group(error) + assert "Rebuild the pipeline table" in str(error) + assert RUN_ID in str(error) and RECORDED_AT in str(error) + restored = deltalake.DeltaTable(uri).to_pyarrow_table() + assert restored.num_rows == legacy.num_rows + assert ( + RUN_ID not in restored.column_names and RECORDED_AT not in restored.column_names + ) + + +@function_pod(output_keys="total") +def nullable_total(x: int, y: int) -> int | None: + """Return a null output value for these positive inputs.""" + return x + y if y < 0 else None + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize( + "produces_output", [False, True], ids=["no-output", "null-value"] +) +def test_pipeline_record_requires_an_output( + orchestrator: str, produces_output: bool +) -> None: + """An absent output produces no entry, while a null output value does.""" + store = InMemoryArrowDatabase() + job = PipelineJob(name="record_metadata", database=store) + with job: + _ = nullable_total.pod(source(), label="filtered") + data_function = nullable_total.pod.data_function + assert isinstance(data_function, PythonDataFunction) + data_function.set_active(produces_output) + try: + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + finally: + data_function.set_active() + if produces_output: + assert pipeline_rows(store).num_rows == 2 + else: + assert store.list_table_paths() == [] + + +@pytest.mark.parametrize( + ("orchestrator", "indices"), [("sync", [0]), ("async", [0, 1])] +) +def test_identical_inputs_without_system_tags( + orchestrator: str, indices: list[int] +) -> None: + """Sync reuses the first entry, while async can schedule both copies as misses.""" + table = source().as_table().select(["site", "group", "x", "y"]).take([0, 0]) + stream = ArrowTableStream(table, tag_columns=["site", "group"]) + store = InMemoryArrowDatabase() + pod = summarize.pod + assert isinstance(pod, FunctionPod) + node = FunctionJobNode(pod, stream, pipeline_database=store) + assert execute_standalone(node, stream, orchestrator) == 2 + assert pipeline_rows(store)[INDEX].to_pylist() == indices From 11a6205aaade8b054fe3fc4f3a30a50473ad10f8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:22:53 -0800 Subject: [PATCH 3/8] test(pipeline): account for recording metadata in run comparisons --- tests/test_core/alignment/records.py | 27 ++++++++++++++++--- tests/test_core/test_order_invariance.py | 10 ++++++- .../test_job_run_in_event_loop.py | 21 ++++++++++++--- .../test_sync_async_stored_records.py | 14 ++++++++-- 4 files changed, 61 insertions(+), 11 deletions(-) diff --git a/tests/test_core/alignment/records.py b/tests/test_core/alignment/records.py index 0d01b8e35..0725bf6fd 100644 --- a/tests/test_core/alignment/records.py +++ b/tests/test_core/alignment/records.py @@ -15,10 +15,12 @@ * every input row is stored once: the record ids are source A's, each exactly once; * ``__data_context`` and ``_context_key`` are the data context's key. -The remaining columns are not derived from the row: ``__pod_ts`` is the time the row was -computed; ``__computed``, ``__is_ephemeral``, ``__pf_var_*`` and ``__pf_exec_*`` describe the -function and the run, the same in every row of one run. They are listed by name, so a new -per-row column fails the check until a rule covers it. +The remaining columns describe recording and execution. Each entry has its own UTC +``__recorded_at`` timestamp. Its ``__pipeline_run_id`` names the job run that recorded it +and is the same for every entry written by that run. These fixtures write all their +entries in one run, then optionally read those entries back. ``__pod_ts`` is the result +timestamp. ``__computed``, ``__is_ephemeral``, ``__pf_var_*`` and ``__pf_exec_*`` describe +the function and its execution. A new column fails the check until a rule covers it. """ from __future__ import annotations @@ -28,6 +30,10 @@ import pyarrow as pa from orcapod import PipelineJob +from orcapod.core.nodes.function_node import ( + PIPELINE_RECORDED_AT_COL, + PIPELINE_RUN_ID_COL, +) from orcapod.system_constants import constants from .checker import split_token @@ -102,6 +108,8 @@ def assert_records_aligned( "__input_data_hash_right", "__data_context", constants.CONTEXT_KEY, + PIPELINE_RUN_ID_COL, + PIPELINE_RECORDED_AT_COL, *NOT_ROW_DERIVED, } unknown = [ @@ -111,6 +119,17 @@ def assert_records_aligned( ] assert not unknown, f"no alignment rule covers the record columns {unknown!r}" + run_ids = records.column(PIPELINE_RUN_ID_COL) + assert run_ids.type == pa.large_string(), "recording run IDs must be large strings" + assert run_ids.null_count == 0 and len(run_ids.unique()) == 1, ( + "every entry must name the same recording run" + ) + recorded_at = records.column(PIPELINE_RECORDED_AT_COL) + assert recorded_at.type == pa.timestamp("us", tz="UTC"), ( + "recording timestamps must be UTC microseconds" + ) + assert recorded_at.null_count == 0, "every entry must have a recording timestamp" + # Every row of the node's input stored once: a record missing, or one valid record # stored twice in place of another, passes every per-record check below. stored: Counter[object] = Counter(records.column(record_id_column).to_pylist()) diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index b6c8697d7..d45fa0b05 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -56,9 +56,14 @@ from orcapod import PipelineJob, col, function_pod, operators, sources, streams from orcapod.channels import Channel from orcapod.core.nodes import SourceJobNode +from orcapod.core.nodes.function_node import ( + PIPELINE_RECORDED_AT_COL, + PIPELINE_RUN_ID_COL, +) from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase +from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION from orcapod.types import Condition from orcapod.operators import ( AddTags, @@ -1110,7 +1115,10 @@ def _job( stored = database.get_all_records(path) if stored is None: continue - keep = [c for c in stored.column_names if c not in _VOLATILE] + volatile = _VOLATILE + if path[-1] == PIPELINE_DB_SCHEMA_VERSION: + volatile = volatile | {PIPELINE_RUN_ID_COL, PIPELINE_RECORDED_AT_COL} + keep = [c for c in stored.column_names if c not in volatile] out[f"stored[{'/'.join(path)}]"] = sorted( _masked(sorted(row.items())) for row in stored.select(keep).to_pylist() ) diff --git a/tests/test_pipeline/test_job_run_in_event_loop.py b/tests/test_pipeline/test_job_run_in_event_loop.py index 3dad697b8..5ebc8ac49 100644 --- a/tests/test_pipeline/test_job_run_in_event_loop.py +++ b/tests/test_pipeline/test_job_run_in_event_loop.py @@ -24,6 +24,10 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import ( + PIPELINE_RECORDED_AT_COL, + PIPELINE_RUN_ID_COL, +) from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver @@ -33,6 +37,7 @@ # result's datagram uuid, the output's source-info token (which carries that uuid) and the # time the result was computed. PER_RUN_COLUMNS = ("__data_id", "_source_y", "__pod_ts") +ENTRY_RECORDING_COLUMNS = (PIPELINE_RUN_ID_COL, PIPELINE_RECORDED_AT_COL) STORES: dict[str, Callable[[Path], Any]] = { "in_memory": lambda _: InMemoryArrowDatabase(), @@ -71,10 +76,14 @@ def make_job(store: Any) -> PipelineJob: return job -def stored_rows(job: PipelineJob) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """The node's stored records and its table, minus per-run columns, sorted by tag.""" +def stored_rows( + job: PipelineJob, *, independent_run: bool = False +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Sort comparable rows by tag, keeping entry metadata for same-store rereads.""" records = job.nodes["doubled"].get_all_records(all_info=True) assert records is not None + if independent_run: + records = records.drop_columns(ENTRY_RECORDING_COLUMNS) records = records.drop_columns( [c for c in PER_RUN_COLUMNS if c in records.column_names] ) @@ -99,7 +108,9 @@ def test_run_inside_running_loop_stores_what_a_script_run_stores( notebook_job = make_job(STORES[store_kind](tmp_path / "notebook")) run_inside_running_loop(notebook_job) - assert stored_rows(notebook_job) == stored_rows(script_job) + assert stored_rows(notebook_job, independent_run=True) == stored_rows( + script_job, independent_run=True + ) ys = sorted(notebook_job.nodes["doubled"].as_table().column("y").to_pylist()) assert ys == [0, 2, 4, 6, 8] @@ -178,7 +189,9 @@ async def async_code() -> None: asyncio.run(async_code()) - assert stored_rows(async_job) == stored_rows(script_job) + assert stored_rows(async_job, independent_run=True) == stored_rows( + script_job, independent_run=True + ) def test_run_async_refuses_the_sync_orchestrator() -> None: diff --git a/tests/test_pipeline/test_sync_async_stored_records.py b/tests/test_pipeline/test_sync_async_stored_records.py index 766b00eb4..0130d6c09 100644 --- a/tests/test_pipeline/test_sync_async_stored_records.py +++ b/tests/test_pipeline/test_sync_async_stored_records.py @@ -16,6 +16,10 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import ( + PIPELINE_RECORDED_AT_COL, + PIPELINE_RUN_ID_COL, +) from orcapod.core.operators import DropDataColumns, SelectDataColumns from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator @@ -27,8 +31,14 @@ } # Columns that differ between two runs by design: the output datagram's uuid, the token -# that carries it, and the time the row was computed. -PER_RUN_COLUMNS = ("__data_id", "_source_y", "__pod_ts") +# that carries it, the result's timestamp, and the entry's recording run and time. +PER_RUN_COLUMNS = ( + "__data_id", + "_source_y", + "__pod_ts", + PIPELINE_RUN_ID_COL, + PIPELINE_RECORDED_AT_COL, +) @function_pod(output_keys="y") From 6477b20cd65be83666e2921d6d806b2c34ba41fc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:34:14 -0800 Subject: [PATCH 4/8] fix(pipeline): validate queued schema and recording nullability --- src/orcapod/core/nodes/function_node.py | 15 +++- .../databases/connector_arrow_database.py | 5 +- src/orcapod/databases/delta_lake_databases.py | 5 +- src/orcapod/databases/in_memory_databases.py | 7 +- src/orcapod/protocols/database_protocols.py | 7 +- .../test_pipeline_record_metadata.py | 87 ++++++++++++++++++- 6 files changed, 113 insertions(+), 13 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 55ec23cd4..9f72dc1ad 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3292,7 +3292,7 @@ def _add_pipeline_record( def _require_current_pipeline_write_schema( self, *, before_compute: bool = False ) -> None: - """Check the stored schema before each append and before the first computation. + """Check the table schema before each append and before the first computation. Args: before_compute: Preflight before executing a function on a cache miss. @@ -3310,13 +3310,24 @@ def _require_current_pipeline_write_schema( if index < 0: issues.append(f"missing {expected.name}") continue + actual = existing.field(index) actual_type = arrow_utils.normalize_to_large_types( - existing.field(index).type, keep_null=True + actual.type, keep_null=True ) if actual_type != expected.type: issues.append( f"{expected.name} has type {actual_type}, expected {expected.type}" ) + if actual.nullable != expected.nullable: + actual_nullability = ( + "nullable" if actual.nullable else "non-nullable" + ) + expected_nullability = ( + "nullable" if expected.nullable else "non-nullable" + ) + issues.append( + f"{expected.name} is {actual_nullability}, expected {expected_nullability}" + ) if issues: raise OrcapodDatabaseError( f"Cannot append a pipeline record to the " diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 81b97eca9..b4d0c402d 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -316,11 +316,12 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ── Storable columns ────────────────────────────────────────────────────── def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: - """Read the connector's current column definitions without fetching rows.""" + """Read the committed or queued schema without fetching rows.""" table_name = self._path_to_table_name(self._path_prefix + record_path) self._require_table_name(table_name) if table_name not in self._connector.get_table_names(): - return None + pending = self._pending_batches.get(self._get_record_key(record_path)) + return None if pending is None else pending.schema return pa.schema( pa.field(column.name, column.arrow_type, nullable=column.nullable) for column in self._connector.get_column_info(table_name) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index e010f9464..d3a51cee1 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1590,7 +1590,7 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: return self._get_delta_table(record_path) is not None def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: - """Read the latest Delta schema from the log without loading data files.""" + """Read the latest Delta schema from the log or the table's first batch.""" from deltalake.exceptions import TableNotFoundError try: @@ -1601,7 +1601,8 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: ) return pa.schema(_held_columns(table).values()) except TableNotFoundError: - return None + pending = self._pending_batches.get(self._get_record_key(record_path)) + return None if pending is None else pending.schema except Exception as exc: raise self._read_failed(record_path) from exc diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 1aea73132..8d64dd3ce 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -549,8 +549,11 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ------------------------------------------------------------------ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: - """Return the committed table's schema, if present.""" - table = self._tables.get(self._get_record_key(record_path)) + """Return the committed schema or the schema of a new, queued table.""" + key = self._get_record_key(record_path) + table = self._tables.get(key) + if table is None: + table = self._pending_batches.get(key) return None if table is None else table.schema def _combined_table(self, record_key: str) -> "pa.Table | None": diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index db76de770..9e102695d 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -166,10 +166,11 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: ... def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: - """Read the current stored schema, including for an empty table. + """Read the current table schema, including for an empty table. - The path is relative to this database view. A missing table gives - ``None``. This operation reads schema metadata without fetching rows. + The path is relative to this database view. If the table has only queued + records, use their schema. Return ``None`` if the table has neither a + committed schema nor a queued batch. No rows are fetched. """ ... diff --git a/tests/test_pipeline/test_pipeline_record_metadata.py b/tests/test_pipeline/test_pipeline_record_metadata.py index 1679cf8c4..9bb25a495 100644 --- a/tests/test_pipeline/test_pipeline_record_metadata.py +++ b/tests/test_pipeline/test_pipeline_record_metadata.py @@ -18,7 +18,11 @@ from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.streams import ArrowTableStream -from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, +) from orcapod.errors import OrcapodDatabaseError, UnstorableColumnError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver @@ -28,6 +32,7 @@ from orcapod.sources import DictSource from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION from orcapod.types import NodeConfig +from tests.test_databases.test_connector_arrow_database import MockDBConnector RUN_ID = "__pipeline_run_id" RECORDED_AT = "__recorded_at" @@ -253,7 +258,9 @@ def require_storable(self, schema: pa.Schema) -> None: @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) -@pytest.mark.parametrize("variant", ["nonempty", "empty", "wrong-type"]) +@pytest.mark.parametrize( + "variant", ["nonempty", "empty", "wrong-type", "nullable-time", "required-run-id"] +) def test_pipeline_table_with_incompatible_schema_must_be_rebuilt( orchestrator: str, variant: str, tmp_path: Path ) -> None: @@ -269,6 +276,20 @@ def test_pipeline_table_with_incompatible_schema_must_be_rebuilt( pa.field(RECORDED_AT, pa.int64(), nullable=False), pa.array([0, 1], type=pa.int64()), ) + elif variant == "nullable-time": + time = current.schema.field(RECORDED_AT) + legacy = current.set_column( + current.schema.get_field_index(RECORDED_AT), + time.with_nullable(True), + pa.nulls(current.num_rows, type=time.type), + ) + elif variant == "required-run-id": + run_id = current.schema.field(RUN_ID) + legacy = current.set_column( + current.schema.get_field_index(RUN_ID), + run_id.with_nullable(False), + current[RUN_ID], + ) else: legacy = current.drop([RUN_ID, RECORDED_AT]) destination = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) @@ -295,6 +316,10 @@ def test_pipeline_table_with_incompatible_schema_must_be_rebuilt( assert f"{RECORDED_AT} has type int64, expected timestamp[us, tz=UTC]" in str( error ) + elif variant == "nullable-time": + assert f"{RECORDED_AT} is nullable, expected non-nullable" in str(error) + elif variant == "required-run-id": + assert f"{RUN_ID} is non-nullable, expected nullable" in str(error) else: assert RUN_ID in str(error) and RECORDED_AT in str(error) if variant == "empty": @@ -304,6 +329,64 @@ def test_pipeline_table_with_incompatible_schema_must_be_rebuilt( assert destination.list_table_paths() == [path] +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("flush", [False, True], ids=["queued", "committed"]) +@pytest.mark.parametrize("backend", ["memory", "delta", "connector"]) +def test_legacy_schema_is_refused_before_evaluation( + orchestrator: str, + flush: bool, + backend: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An incompatible schema shared across views prevents calls and result writes.""" + seed = InMemoryArrowDatabase() + pod = summarize.pod + assert isinstance(pod, FunctionPod) + stream = source() + seeder = FunctionJobNode(pod, stream, pipeline_database=seed) + _ = seeder.run() + path = pipeline_path(seed) + legacy = pipeline_rows(seed).drop([RUN_ID, RECORDED_AT]) + + root: ArrowDatabaseProtocol + if backend == "delta": + root = DeltaTableDatabase(tmp_path) + elif backend == "connector": + root = ConnectorArrowDatabase(MockDBConnector()) + else: + root = InMemoryArrowDatabase() + root.at("pipeline").add_records( + path, legacy, record_id_column=RECORD_ID, flush=flush + ) + pipeline = root.at("pipeline") + results = InMemoryArrowDatabase() + writer = FunctionJobNode( + pod, stream, pipeline_database=pipeline, result_database=results + ) + data_function = pod.data_function + + def unexpected_call(*args: object, **kwargs: object) -> None: + """Fail if the schema check lets the function evaluate.""" + pytest.fail("The function evaluated before the pipeline schema was refused") + + monkeypatch.setattr(data_function, "call", unexpected_call) + monkeypatch.setattr(data_function, "async_call", unexpected_call) + with pytest.raises((OrcapodDatabaseError, ExceptionGroup)) as info: + _ = execute_standalone(writer, stream, orchestrator) + error = info.value + if isinstance(error, ExceptionGroup): + (error,) = OrcapodDatabaseError.in_group(error) + assert "Rebuild the pipeline table" in str(error) + assert RUN_ID in str(error) and RECORDED_AT in str(error) + assert results.list_table_paths() == [] + retained = pipeline.get_all_records(path, record_id_column=RECORD_ID) + assert retained is not None + assert retained.sort_by([("site", "ascending"), (INDEX, "ascending")]).equals( + legacy + ) + + @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) def test_the_same_node_refuses_a_restored_prerelease_schema( orchestrator: str, tmp_path: Path From 68f0d0463133c02caaf9ff4297530dcc364bfc4a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 12:44:15 -0800 Subject: [PATCH 5/8] fix(pipeline): validate recording schema at commit --- src/orcapod/core/nodes/function_node.py | 110 +++++++++--------- src/orcapod/databases/_pending_commits.py | 20 ++++ .../databases/connector_arrow_database.py | 19 ++- src/orcapod/databases/delta_lake_databases.py | 36 ++++-- .../databases/extension_aware_database.py | 6 + src/orcapod/databases/in_memory_databases.py | 13 ++- src/orcapod/databases/noop_database.py | 8 +- src/orcapod/errors.py | 4 + src/orcapod/protocols/database_protocols.py | 8 +- .../test_mixed_function_commits.py | 7 ++ .../test_pipeline_record_metadata.py | 84 +++++++++++++ 11 files changed, 250 insertions(+), 65 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9f72dc1ad..c3c1d3751 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -26,6 +26,7 @@ from collections import Counter from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from datetime import datetime, timezone +from functools import partial from typing import Any, Literal, NamedTuple, cast import polars as pl @@ -74,6 +75,7 @@ OrcapodDatabaseError, TypeIdentityError, OrcapodDatabaseWriteError, + StoredTableSchemaError, UnstorableColumnError, ) from orcapod.contexts.stored import ( @@ -1419,7 +1421,7 @@ class FunctionJobNode(RunHoldingNode, FunctionNodeBase): _stale_tables_checked: bool = False # Set once the rows of the current tables were counted by data context. _current_tables_checked: bool = False - # Preflight the first miss before invoking user code. Each append checks again. + # Preflight the first miss before invoking user code. Each commit checks again. _pipeline_preflight_checked: bool = False # Set once a database that cannot list its tables was reported. _unlisted_store_reported: bool = False @@ -2420,6 +2422,7 @@ def _write_pipeline_record( database = self._require_pipeline_database() path = self._versioned_pipeline_path pod = self._ephemeral_cached_pod if is_ephemeral else self._cached_function_pod + dependency = None if self._commit_every_rows is not None and isinstance(pod, CachedFunctionPod): result_database = pod.result_database try: @@ -2433,11 +2436,14 @@ def _write_pipeline_record( flush=True, table_flush=True, ) from exc - if dependency is not None: - with database.guard_record(path, record_id, dependency): - database.add_record(path, record_id, record, skip_duplicates=True) - return - database.add_record(path, record_id, record, skip_duplicates=True) + check = partial(self._check_pipeline_write_schema, database, path) + result_guard = ( + contextlib.nullcontext() + if dependency is None + else database.guard_record(path, record_id, dependency) + ) + with database.guard_table_schema(path, check), result_guard: + database.add_record(path, record_id, record, skip_duplicates=True) def _row_processed(self) -> None: """Count a processed row; commit once a batch is full (only inside a job run).""" @@ -2829,7 +2835,7 @@ def _process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, base_entry_id) - self._require_current_pipeline_write_schema(before_compute=True) + self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) if ephemeral_result: @@ -2970,7 +2976,7 @@ async def _async_process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, base_entry_id) - self._require_current_pipeline_write_schema(before_compute=True) + self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) if ephemeral_result: @@ -3208,7 +3214,7 @@ def _add_pipeline_record( input_data.data_context_key, self._stored_data_context_key ) self._account_for_stale_tables() - self._require_current_pipeline_write_schema() + self._preflight_pipeline_write_schema() # Determine the next recomputation index by querying all existing rows # for this base_entry_id. No await is used here, so within a single-threaded @@ -3289,54 +3295,54 @@ def _add_pipeline_record( tag=tag.as_dict(), ) from exc - def _require_current_pipeline_write_schema( - self, *, before_compute: bool = False - ) -> None: - """Check the table schema before each append and before the first computation. - - Args: - before_compute: Preflight before executing a function on a cache miss. - Only this early check can reuse a prior check from the same run. - """ + def _preflight_pipeline_write_schema(self) -> None: + """Refuse an incompatible table before the first computation in this run.""" database = self._pipeline_database - if database is None or (before_compute and self._pipeline_preflight_checked): + if database is None or self._pipeline_preflight_checked: return path = self._versioned_pipeline_path existing = database.get_table_schema(path) if existing is not None: - issues: list[str] = [] - for expected in _PIPELINE_RECORDING_FIELDS: - index = existing.get_field_index(expected.name) - if index < 0: - issues.append(f"missing {expected.name}") - continue - actual = existing.field(index) - actual_type = arrow_utils.normalize_to_large_types( - actual.type, keep_null=True + self._check_pipeline_write_schema(database, path, existing) + self._pipeline_preflight_checked = True + + def _check_pipeline_write_schema( + self, + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + schema: pa.Schema, + ) -> None: + """Report missing or incompatible recording columns and name their table.""" + issues: list[str] = [] + for expected in _PIPELINE_RECORDING_FIELDS: + index = schema.get_field_index(expected.name) + if index < 0: + issues.append(f"missing {expected.name}") + continue + actual = schema.field(index) + actual_type = arrow_utils.normalize_to_large_types( + actual.type, keep_null=True + ) + if actual_type != expected.type: + issues.append( + f"{expected.name} has type {actual_type}, expected {expected.type}" ) - if actual_type != expected.type: - issues.append( - f"{expected.name} has type {actual_type}, expected {expected.type}" - ) - if actual.nullable != expected.nullable: - actual_nullability = ( - "nullable" if actual.nullable else "non-nullable" - ) - expected_nullability = ( - "nullable" if expected.nullable else "non-nullable" - ) - issues.append( - f"{expected.name} is {actual_nullability}, expected {expected_nullability}" - ) - if issues: - raise OrcapodDatabaseError( - f"Cannot append a pipeline record to the " - f"{describe_database_table(database, path)}: " - f"{', '.join(issues)}. Rebuild the pipeline table " - "with the current version of Orcapod.", - node_label=self.label, + if actual.nullable != expected.nullable: + actual_nullability = "nullable" if actual.nullable else "non-nullable" + expected_nullability = ( + "nullable" if expected.nullable else "non-nullable" ) - self._pipeline_preflight_checked = True + issues.append( + f"{expected.name} is {actual_nullability}, expected {expected_nullability}" + ) + if issues: + raise StoredTableSchemaError( + f"Cannot append a pipeline record to the " + f"{describe_database_table(database, path)}: " + f"{', '.join(issues)}. Rebuild the pipeline table " + "with the current version of Orcapod.", + node_label=self.label, + ) # ------------------------------------------------------------------ # Records and sources @@ -4446,9 +4452,7 @@ async def route_inputs() -> None: run_entry_ids.append(base_entry_id) await output.send((cached_tag, cached_data)) else: - self._require_current_pipeline_write_schema( - before_compute=True - ) + self._preflight_pipeline_write_schema() correlation_key = uuid.uuid4().bytes input_store[correlation_key] = ( tag, diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 80a3f9e06..a3891705f 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -45,6 +45,23 @@ def __init__( self._on_empty = on_empty self._attempts: dict[str, PendingCommit] = {} self._guards: dict[str, dict[bytes, PendingCommit]] = {} + self._schema_checks: dict[str, Callable[[pa.Schema], None]] = {} + + @contextmanager + def guard_schema( + self, key: str, check: Callable[[pa.Schema], None] + ) -> Iterator[None]: + """Keep a schema check with the batch through buffering and retries.""" + self._schema_checks.setdefault(key, check) + try: + yield + finally: + if key not in self._batches: + self._schema_checks.pop(key, None) + + def schema_check(self, key: str) -> Callable[[pa.Schema], None] | None: + """Get the check for a batch being committed.""" + return self._schema_checks.get(key) def attempt(self, key: str) -> PendingCommit: """Get the attempt shared by all rows currently pending for a table.""" @@ -89,6 +106,7 @@ def discard(self, key: str, ids: set[bytes], attempt: PendingCommit) -> None: else: self._batches.pop(key) self._ids.pop(key) + self._schema_checks.pop(key, None) if self._on_empty is not None: self._on_empty(key) @@ -119,6 +137,8 @@ def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: def forget(self, key: str, ids: set[bytes]) -> None: """Forget dependencies for records that are leaving the queue.""" + if key not in self._batches: + self._schema_checks.pop(key, None) guards = self._guards.get(key) if guards is not None: for record_id in ids: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b4d0c402d..376e7e5a6 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -20,7 +20,7 @@ import re from collections import defaultdict -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from typing import Any, cast @@ -547,7 +547,11 @@ def _stored_columns(self, table_name: str) -> "list[pa.Field[Any]] | None": if table_name not in self._connector.get_table_names(): return None return [ - pa.field(c.name, normalize_to_large_types(c.arrow_type, keep_null=True)) + pa.field( + c.name, + normalize_to_large_types(c.arrow_type, keep_null=True), + nullable=c.nullable, + ) for c in self._connector.get_column_info(table_name) ] @@ -692,6 +696,14 @@ def guard_record( self._get_record_key(record_path), record_id, dependency ) + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + """Check the schema at the connector's commit.""" + return self._pending_commits.guard_schema( + self._get_record_key(record_path), check + ) + def flush(self) -> None: """Commit all pending batches to the connector via upsert.""" for record_key in list(self._pending_batches): @@ -730,6 +742,9 @@ def _flush_by_key(self, record_key: str) -> None: # Looked up now, as the check needs: nothing about the stored table is # trusted from an earlier call (ITL-1367). existing = self._stored_columns(table_name) + check = self._pending_commits.schema_check(record_key) + if check is not None: + check(pending.schema if existing is None else pa.schema(existing)) if existing is not None: # A connector reads text and binary back in their large variants, # which are the same types (ITL-1162). diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index d3a51cee1..57359e1d4 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -53,6 +53,7 @@ ) from orcapod.errors import ( InputValidationError, + StoredTableSchemaError, OrcapodDatabaseReadError, TableListingNotSupportedError, TypeIdentityError, @@ -2866,6 +2867,14 @@ def flush_result_batch( """Commit a durable result table even if no pipeline records are stored.""" self.flush_batch(record_path) + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + """Check the schema in the snapshot opened at commit.""" + return self._pending_commits.guard_schema( + self._get_record_key(record_path), check + ) + def flush_batch(self, record_path: tuple[str, ...]) -> None: """ Flush pending batch for a specific source path. @@ -2933,6 +2942,14 @@ def _flush_by_key(self, record_key: str) -> None: table_uri, abs_path_components ) from load_error + check = self._pending_commits.schema_check(record_key) + if check is not None: + check( + pending_batch.schema + if delta_table is None + else pa.schema(_held_columns(delta_table).values()) + ) + # Set when the rows were appended through ``delta_table``, which the # writer then moves to the version it committed (ITL-1173). appended = False @@ -2941,7 +2958,7 @@ def _flush_by_key(self, record_key: str) -> None: deltalake.write_deltalake( table_uri, combined_table, - mode="overwrite", + mode="overwrite" if check is None else "error", schema_mode="merge" if self.allow_schema_evolution else "overwrite", storage_options=self._storage_options or None, # Name the statistics columns once, at creation (ITL-1187). @@ -3007,7 +3024,7 @@ def _flush_by_key(self, record_key: str) -> None: f"Appended batch of {len(combined_table)} records to {record_key}" ) - except InputValidationError as e: + except (InputValidationError, StoredTableSchemaError) as e: # The stored table refuses these rows (``_append_refusal``, # ``_conformed_to_stored``): they would be refused by every later flush # too, so they leave the queue, as rows refused when added never enter @@ -3020,14 +3037,19 @@ def _flush_by_key(self, record_key: str) -> None: # The discard notice is part of the message, so it survives wherever the # error is reported: the log, and the note ``flush`` puts on another # batch's error when that one is raised instead. - refused = InputValidationError( - f"{e} The {pending_batch.num_rows} rows queued for table " - f"{record_key!r} were not written and are no longer queued: correct " - "them and add them again." + discarded = ( + f"The {pending_batch.num_rows} rows queued for table " + f"{record_key!r} were not written and are no longer queued." ) self._pending_commits.forget(record_key, pending_ids) self._pending_commits.finish(record_key, committed=False) - logger.error(f"Refused batch for {record_key}: {refused}") + logger.error("Refused batch for %s: %s %s", record_key, e, discarded) + if isinstance(e, StoredTableSchemaError): + e.add_note(discarded) + raise + refused = InputValidationError( + f"{e} {discarded.removesuffix('.')}: correct them and add them again." + ) raise refused from e except BaseException as exc: logger.error(f"Error flushing batch for {record_key}: {exc}") diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 8a540f2ef..129cc1c19 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -235,6 +235,12 @@ def guard_record( """Guard a queued record in the wrapped database.""" return self._db.guard_record(record_path, record_id, dependency) + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + """Delegate the schema check to the database that commits the batch.""" + return self._db.guard_table_schema(record_path, check) + @property def stores_records(self) -> bool: """Return whether the wrapped database retains records.""" diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 8d64dd3ce..cc19c61e8 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -2,7 +2,7 @@ import logging from collections import defaultdict -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any, cast @@ -375,6 +375,14 @@ def guard_record( self._get_record_key(record_path), record_id, dependency ) + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + """Check the table schema when a batch queued here is promoted.""" + return self._pending_commits.guard_schema( + self._get_record_key(record_path), check + ) + def flush(self) -> None: """Promote the ready batches in the shared queue.""" for record_key in list(self._pending_batches): @@ -420,6 +428,9 @@ def _flush_by_key(self, record_key: str) -> None: def _promote(self, record_key: str, pending: "pa.Table") -> None: """Append the ready rows and update the committed indexes.""" committed = self._tables.get(record_key) + check = self._pending_commits.schema_check(record_key) + if check is not None: + check((pending if committed is None else committed).schema) if committed is None: self._tables[record_key] = pending.combine_chunks() return diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 17d2f95ca..53ab435aa 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager, nullcontext from typing import TYPE_CHECKING, Any @@ -124,6 +124,12 @@ def guard_record( """Accept the bookkeeping dependency without retaining the pipeline record.""" return nullcontext() + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + """Discard records without committing a table.""" + return nullcontext() + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """Return no path: this no-op implementation never stores a table. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 3b7a93fb7..d701464e7 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -971,6 +971,10 @@ def add_context( self.tag = dict(tag) +class StoredTableSchemaError(OrcapodDatabaseError): + """A table's layout does not permit committing the queued records.""" + + class OrcapodDatabaseWriteError(OrcapodDatabaseError): """Raised when a node's results or records could not be written to the database. diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index 9e102695d..258c2813b 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable @@ -38,6 +38,12 @@ def guard_record( """Bind a record to its result's token before enqueue can publish it.""" ... + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + """Keep the check with queued records and apply it to the schema at commit.""" + ... + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: """Withdraw records dependent on a failed result attempt.""" ... diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 1e98e5a6a..50721aab7 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -2,6 +2,8 @@ from __future__ import annotations +from collections.abc import Callable + import asyncio from collections import defaultdict from contextlib import AbstractContextManager @@ -454,6 +456,11 @@ def guard_record( ) -> AbstractContextManager[None]: return self._inner.guard_record(record_path, record_id, dependency) + def guard_table_schema( + self, record_path: tuple[str, ...], check: Callable[[pa.Schema], None] + ) -> AbstractContextManager[None]: + return self._inner.guard_table_schema(record_path, check) + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: self._inner.fail_pending_result(record_path) diff --git a/tests/test_pipeline/test_pipeline_record_metadata.py b/tests/test_pipeline/test_pipeline_record_metadata.py index 9bb25a495..3b41dcbeb 100644 --- a/tests/test_pipeline/test_pipeline_record_metadata.py +++ b/tests/test_pipeline/test_pipeline_record_metadata.py @@ -424,6 +424,90 @@ def test_the_same_node_refuses_a_restored_prerelease_schema( ) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("backend", ["memory", "delta"]) +def test_commit_refuses_legacy_schema_restored_after_queueing( + orchestrator: str, backend: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The commit checks the table it publishes to, even after a successful preflight.""" + seed = InMemoryArrowDatabase() + first, _ = job_and_node(seed) + _ = first.run() + path = pipeline_path(seed) + current = pipeline_rows(seed) + legacy = current.drop([RUN_ID, RECORDED_AT]) + if backend == "delta": + store: ArrowDatabaseProtocol = DeltaTableDatabase(tmp_path) + store.add_records(path, legacy, record_id_column=RECORD_ID, flush=True) + uri = str(tmp_path.joinpath(*path)) + deltalake.write_deltalake( + uri, current, mode="overwrite", schema_mode="overwrite" + ) + for result_path in seed.list_table_paths(): + if result_path != path: + results = seed.get_all_records(result_path, record_id_column=RECORD_ID) + assert results is not None + store.add_records( + result_path, results, record_id_column=RECORD_ID, flush=True + ) + else: + store = seed + + writer, node = job_and_node(store, count=3) + assert writer.nodes["summarize"] is node + assert execute_standalone(node, source(3), orchestrator) == 3 + assert pipeline_rows(store).num_rows == 3 + if backend == "delta": + delta = deltalake.DeltaTable(str(tmp_path.joinpath(*path))) + assert delta.to_pyarrow_table().num_rows == 2 + _ = delta.restore(0) + else: + monkeypatch.setitem( + seed._tables, + "/".join(path), + legacy, # pyright: ignore[reportPrivateUsage] # simulate replacing a table underneath the queue + ) + + with pytest.raises(OrcapodDatabaseError, match="Rebuild the pipeline table"): + store.flush_batch(path) + assert pipeline_rows(store).equals(legacy) + store.flush_batch(path) # The refused batch must not be retried. + assert pipeline_rows(store).equals(legacy) + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("existing", [False, True], ids=["new", "existing"]) +def test_pipeline_schema_opens_do_not_grow_with_rows( + orchestrator: str, existing: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Preflight opens one metadata snapshot and the flush uses its own snapshot.""" + original = deltalake.DeltaTable.__init__ + counts: list[tuple[int, int]] = [] + for count in (3, 63): + store = DeltaTableDatabase(tmp_path / str(count)) + if existing: + initial, _ = job_and_node(store) + _ = initial.run() + job, node = job_and_node(store, count=count) + opens: list[bool] = [] + + def observe(table: deltalake.DeltaTable, uri: str, **options: object) -> None: + """Count pipeline log opens, distinguishing preflight from reads and commits.""" + if Path(uri).name == PIPELINE_DB_SCHEMA_VERSION: + opens.append(options.get("without_files") is True) + original(table, uri, **options) # pyright: ignore[reportArgumentType] # forward Delta's unchanged keyword arguments + + with monkeypatch.context() as patch: + patch.setattr(deltalake.DeltaTable, "__init__", observe) + _ = job.run( + orchestrator=ORCHESTRATORS[orchestrator](), commit_every_rows=100 + ) + assert node.as_table().num_rows == count + counts.append((sum(opens), len(opens))) + assert counts[0][0] == counts[1][0] == 1 + assert counts[0][1] == counts[1][1] + + @function_pod(output_keys="total") def nullable_total(x: int, y: int) -> int | None: """Return a null output value for these positive inputs.""" From 62f1d8f2e5835bbe9e952b1943a461978d84c01c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 13:25:22 -0800 Subject: [PATCH 6/8] fix(database): preserve stored schema refusals on Delta flush --- src/orcapod/databases/delta_lake_databases.py | 17 ++++- .../test_pipeline_record_metadata.py | 74 +++++++++++++++++-- 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 018d9533f..72bc85e00 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1164,16 +1164,21 @@ def _database_error_to_raise(errors: list[Exception]) -> Exception | None: A ``OrcapodDatabaseReadError`` is preferred, because it is the error that fails a run whatever the orchestrator's ``error_policy``; failing that, an - ``InputValidationError`` from a refused append. + ``InputValidationError`` from a refused append, then a + ``StoredTableSchemaError`` from a schema guard. Args: errors: The error of every batch that failed, in flush order. Returns: - The first ``OrcapodDatabaseReadError``, else the first ``InputValidationError``, or - ``None`` when no batch failed with a database error. + The first error of the highest-priority type listed above, or + ``None`` when no batch failed with one of those types. """ - for kind in (OrcapodDatabaseReadError, InputValidationError): + for kind in ( + OrcapodDatabaseReadError, + InputValidationError, + StoredTableSchemaError, + ): chosen = next((e for e in errors if isinstance(e, kind)), None) if chosen is not None: return chosen @@ -2794,6 +2799,8 @@ def flush(self) -> None: (``_append_refusal``). The batch is dropped from the queue, since every later flush would refuse it too; the error says how many rows were not written. Correct the rows and add them again (ITL-1334). + - Refused by a schema guard (``StoredTableSchemaError``): the stored table + must be rebuilt before appending. The refused batch leaves the queue. - Any other failure (a table that cannot be loaded, a failed write): the batch stays queued, so a later flush tries it again. @@ -2804,6 +2811,8 @@ def flush(self) -> None: InputValidationError: If no batch failed with ``OrcapodDatabaseReadError`` but a batch was refused by its stored table (dropped from the queue, above). Other failed batches are added to it as notes. + StoredTableSchemaError: If a schema guard refused an append and no batch + failed with either error above. Other failed batches are added as notes. RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ diff --git a/tests/test_pipeline/test_pipeline_record_metadata.py b/tests/test_pipeline/test_pipeline_record_metadata.py index 3b41dcbeb..e87550b48 100644 --- a/tests/test_pipeline/test_pipeline_record_metadata.py +++ b/tests/test_pipeline/test_pipeline_record_metadata.py @@ -23,14 +23,21 @@ DeltaTableDatabase, InMemoryArrowDatabase, ) -from orcapod.errors import OrcapodDatabaseError, UnstorableColumnError +from orcapod.errors import ( + OrcapodDatabaseError, + StoredTableSchemaError, + UnstorableColumnError, +) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.sources import DictSource -from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION +from orcapod.system_constants import ( + PIPELINE_DB_SCHEMA_VERSION, + RESULT_DB_SCHEMA_VERSION, +) from orcapod.types import NodeConfig from tests.test_databases.test_connector_arrow_database import MockDBConnector @@ -68,9 +75,12 @@ def job_and_node( count: int = 2, reverse: bool = False, ephemeral: InMemoryArrowDatabase | None = None, + result_database: ArrowDatabaseProtocol | None = None, ) -> tuple[PipelineJob, FunctionJobNode]: """Build a fresh job over the same function and pipeline table.""" - job = PipelineJob(name="record_metadata", database=store) + job = PipelineJob( + name="record_metadata", database=store, result_database=result_database + ) with job: _ = summarize.pod(source(count, reverse=reverse), label="summarize") if ephemeral is not None: @@ -108,6 +118,44 @@ def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: self.run_id = run_id +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_separate_result_store_keeps_recording_metadata_in_the_pipeline( + orchestrator: str, +) -> None: + """Two jobs sharing results each record the ID of their own run.""" + results = InMemoryArrowDatabase() + first_run_id = None + original_result = None + for computed in (True, False): + store = InMemoryArrowDatabase() + job, node = job_and_node(store, result_database=results) + observer = RunObserver() + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator](), observer=observer) + assert observer.run_id and observer.run_id != first_run_id + (path,) = store.list_table_paths() + assert path[-1] == PIPELINE_DB_SCHEMA_VERSION + entries = pipeline_rows(store) + assert entries[RUN_ID].to_pylist() == [observer.run_id] * 2 + assert entries[RECORDED_AT].null_count == 0 + assert entries["__computed"].to_pylist() == [computed] * 2 + joined = node.get_all_records(columns={"meta": True}) + assert joined is not None + assert joined[RUN_ID].to_pylist() == [observer.run_id] * 2 + + (result_path,) = results.list_table_paths() + assert result_path[-1] == RESULT_DB_SCHEMA_VERSION + result = results.get_all_records(result_path) + assert result is not None and result.num_rows == 2 + assert ( + RUN_ID not in result.column_names and RECORDED_AT not in result.column_names + ) + if computed: + first_run_id = observer.run_id + original_result = result + else: + assert original_result is not None and result.equals(original_result) + + @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) @pytest.mark.parametrize("ephemeral", [False, True], ids=["persistent", "ephemeral"]) def test_job_records_keep_their_original_metadata( @@ -426,8 +474,13 @@ def test_the_same_node_refuses_a_restored_prerelease_schema( @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) @pytest.mark.parametrize("backend", ["memory", "delta"]) +@pytest.mark.parametrize("full_flush", [False, True], ids=["batch", "full"]) def test_commit_refuses_legacy_schema_restored_after_queueing( - orchestrator: str, backend: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + orchestrator: str, + backend: str, + full_flush: bool, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, ) -> None: """The commit checks the table it publishes to, even after a successful preflight.""" seed = InMemoryArrowDatabase() @@ -468,10 +521,17 @@ def test_commit_refuses_legacy_schema_restored_after_queueing( legacy, # pyright: ignore[reportPrivateUsage] # simulate replacing a table underneath the queue ) - with pytest.raises(OrcapodDatabaseError, match="Rebuild the pipeline table"): - store.flush_batch(path) + def flush() -> None: + """Exercise both a table-scoped commit and a flush of the whole database.""" + if full_flush: + store.flush() + else: + store.flush_batch(path) + + with pytest.raises(StoredTableSchemaError, match="Rebuild the pipeline table"): + flush() assert pipeline_rows(store).equals(legacy) - store.flush_batch(path) # The refused batch must not be retried. + flush() # The refused batch must not be retried. assert pipeline_rows(store).equals(legacy) From d034f356cb90fde631580bd9e3d112b99db728d1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 13:57:20 -0800 Subject: [PATCH 7/8] fix(database): retain schema validation on Delta retry --- src/orcapod/databases/delta_lake_databases.py | 8 ++- .../test_delta_append_preflight.py | 58 ++++++++++++++++++- 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 72bc85e00..5ec9ef9ae 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -3094,8 +3094,12 @@ def _flush_by_key(self, record_key: str) -> None: raise refused from e except BaseException as exc: logger.error(f"Error flushing batch for {record_key}: {exc}") - self._pending_commits.finish(record_key, committed=False) - self._pending_commits.restore(record_key, pending_batch, pending_ids) + # Requeue the ready rows before withdrawing dependents. Withdrawing + # the last blocked row would otherwise discard the table's schema check. + try: + self._pending_commits.restore(record_key, pending_batch, pending_ids) + finally: + self._pending_commits.finish(record_key, committed=False) raise # The rows are committed: nothing below may put them back in the queue. diff --git a/tests/test_databases/test_delta_append_preflight.py b/tests/test_databases/test_delta_append_preflight.py index d37919f53..85fc6298d 100644 --- a/tests/test_databases/test_delta_append_preflight.py +++ b/tests/test_databases/test_delta_append_preflight.py @@ -13,11 +13,16 @@ from pathlib import Path from typing import Any, cast +import deltalake import pyarrow as pa import pytest from orcapod.databases import DeltaTableDatabase -from orcapod.errors import InputValidationError, UnstorableColumnError +from orcapod.errors import ( + InputValidationError, + StoredTableSchemaError, + UnstorableColumnError, +) from tests.test_databases.type_matrix import map_of_fields PATH = ("t",) @@ -43,6 +48,57 @@ def _struct(*fields: Any) -> Any: return pa.struct(list(fields)) +def test_retry_keeps_schema_check_when_a_dependent_row_is_withdrawn( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Retry the ready row after failure cancels the blocked row in the same table.""" + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + legacy = _rows([b"stored"], v=(I64, [0])) + db.add_records(PATH, legacy, record_id_column="id", flush=True) + uri = str(tmp_path.joinpath(*PATH)) + current = _rows([b"stored"], v=(I64, [0]), x=(I64, [10])) + deltalake.write_deltalake( + uri, + current.rename_columns({"id": "__record_id"}), + mode="overwrite", + schema_mode="overwrite", + ) + db = DeltaTableDatabase(tmp_path, allow_schema_evolution=True) + + def require_x(schema: pa.Schema) -> None: + """Refuse the legacy schema if a restore removes the recording field.""" + if "x" not in schema.names: + raise StoredTableSchemaError("Rebuild the pipeline table") + + with db.guard_table_schema(PATH, require_x): + ready = _rows([b"ready"], v=(I64, [1]), x=(I64, [11])) + db.add_records(PATH, ready, record_id_column="id") + attempt = db.pending_result(PATH, b"ready") + assert attempt is not None + blocked = _rows([b"blocked"], v=(I64, [2]), x=(I64, [12])) + with db.guard_record(PATH, b"blocked", attempt): + db.add_records(PATH, blocked, record_id_column="id") + + def fail_write(*args: object, **kwargs: object) -> None: + """Fail the commit before publishing the ready row.""" + raise OSError("temporary write failure") + + with monkeypatch.context() as patch: + patch.setattr(deltalake, "write_deltalake", fail_write) + with pytest.raises(OSError, match="temporary write failure"): + db.flush_batch(PATH) + queued = db.get_all_records(PATH, record_id_column="id") + assert queued is not None + assert sorted(cast(list[bytes], queued["id"].to_pylist())) == [b"ready", b"stored"] + + _ = deltalake.DeltaTable(uri).restore(0) + with pytest.raises(StoredTableSchemaError, match="Rebuild the pipeline table"): + db.flush_batch(PATH) + db.flush_batch(PATH) + stored = db.get_all_records(PATH, record_id_column="id") + assert stored is not None and stored.equals(legacy) + + A_NOT_NULL = pa.field("a", I64, nullable=False) B = pa.field("b", I64) From 29824fbf526a73eda1d5ffe687c1a0a9bf2b6e27 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 16:43:20 -0800 Subject: [PATCH 8/8] fix(database): surface connector schema lookup failures --- .../databases/connector_arrow_database.py | 30 +++++++++---- .../test_pipeline_record_metadata.py | 44 +++++++++++++++++++ 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 7234266db..6ae7f757c 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -36,6 +36,8 @@ ) from orcapod.errors import ( InputValidationError, + OrcapodDatabaseError, + OrcapodDatabaseReadError, UnstorableColumnError, UnstorableTableNameError, ) @@ -316,16 +318,26 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ── Storable columns ────────────────────────────────────────────────────── def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: - """Read the committed or queued schema without fetching rows.""" - table_name = self._path_to_table_name(self._path_prefix + record_path) + """Read the committed or queued schema without fetching rows. + + Raises: + OrcapodDatabaseReadError: If the connector cannot inspect the schema. + """ + full_path = self._path_prefix + record_path + table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) - if table_name not in self._connector.get_table_names(): - pending = self._pending_batches.get(self._get_record_key(record_path)) - return None if pending is None else pending.schema - return pa.schema( - pa.field(column.name, column.arrow_type, nullable=column.nullable) - for column in self._connector.get_column_info(table_name) - ) + try: + if table_name not in self._connector.get_table_names(): + pending = self._pending_batches.get(self._get_record_key(record_path)) + return None if pending is None else pending.schema + return pa.schema( + pa.field(column.name, column.arrow_type, nullable=column.nullable) + for column in self._connector.get_column_info(table_name) + ) + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseReadError(table_name, full_path) from exc def require_storable(self, schema: pa.Schema) -> None: """Refuse a table schema with a column the connector cannot store (ITL-1162). diff --git a/tests/test_pipeline/test_pipeline_record_metadata.py b/tests/test_pipeline/test_pipeline_record_metadata.py index 216a55d3d..fae454006 100644 --- a/tests/test_pipeline/test_pipeline_record_metadata.py +++ b/tests/test_pipeline/test_pipeline_record_metadata.py @@ -25,6 +25,7 @@ ) from orcapod.errors import ( OrcapodDatabaseError, + OrcapodDatabaseReadError, StoredTableSchemaError, UnstorableColumnError, ) @@ -118,6 +119,49 @@ def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: self.run_id = run_id +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("operation", ["get_table_names", "get_column_info"]) +def test_connector_schema_lookup_failure_stops_run_under_continue( + orchestrator: str, operation: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unavailable connector during preflight must fail the run.""" + connector = MockDBConnector() + store = ConnectorArrowDatabase(connector) + results = InMemoryArrowDatabase() + initial, _ = job_and_node(store, result_database=results) + _ = initial.run() + (result_path,) = results.list_table_paths() + original_results = results.get_all_records(result_path) + assert original_results is not None + + writer, node = job_and_node(store, count=3, result_database=results) + original_lookup = ConnectorArrowDatabase.get_table_schema + + def disconnected(*args: object, **kwargs: object) -> None: + """Fail schema introspection for this lookup.""" + raise ConnectionError("connector unavailable") + + def lookup(view: ConnectorArrowDatabase, path: tuple[str, ...]) -> pa.Schema | None: + """Inject failure only at schema preflight, after cached rows can be read.""" + with monkeypatch.context() as patch: + patch.setattr(connector, operation, disconnected) + return original_lookup(view, path) + + monkeypatch.setattr(ConnectorArrowDatabase, "get_table_schema", lookup) + with pytest.raises(OrcapodDatabaseReadError, match="connector unavailable") as info: + _ = writer.run( + orchestrator=ORCHESTRATORS[orchestrator](error_policy="continue") + ) + assert info.value.record_path == ( + "record_metadata", + *node.node_identity_path, + PIPELINE_DB_SCHEMA_VERSION, + ) + assert isinstance(info.value.__cause__, ConnectionError) + remaining = results.get_all_records(result_path) + assert remaining is not None and remaining.equals(original_results) + + @pytest.mark.parametrize("orchestrator", ORCHESTRATORS) def test_separate_result_store_keeps_recording_metadata_in_the_pipeline( orchestrator: str,