Skip to content
Merged
7 changes: 7 additions & 0 deletions changelog.d/ITL-1871.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Fixed

- Connector-backed jobs reject table paths that exceed the configured depth during database attachment, with the node, path, and limit in the error.
- Every run checks, before it takes a writer lease or writes anything, the table paths of each cached source's cache on a connector database (SQLite, PostgreSQL or SpiralDB) and of the result databases of function pods built outside the job; the error names the cached source or stream. A function pod's own `result_database` or `pod_cache_database` is checked when the job attaches its databases, and again by every full run, so a function job node built on its own is refused, naming the node, before its function is called.
- A polling source that declares its Arrow schema gives its declared zero-row table before its first poll, so a caching operator over it refuses an unsupported column when its cache is attached, without polling.
- Writable SpiralDB jobs reject known unsupported column types, including duration and fixed-size binary, before writing rows. Reads reject decimal values outside their declared precision at every supported width, including inside nested columns.
- A job checks storage paths and schemas against proposed source bindings before changing its bindings or node attachments. Identity hashes computed during the check stay in temporary caches. A refused bind can be retried with the same databases after correcting the source.
8 changes: 8 additions & 0 deletions docs/dev/design_issues/ITL-1162-CA3.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ ruling, November 16, 2026). `PostgreSQLConnector` also states which table names
(`UnstorableTableNameError`). The connectors' silent TEXT fallback in `CREATE TABLE` now
raises.

When the pipeline or result database changes and a pipeline database is available,
`PipelineJob.bind()` checks storage paths and schemas on the candidate databases using
the proposed source bindings. The check uses temporary identity and schema memos.
A storage refusal preserves the original bindings and attachments. A source-only bind
can succeed without validating that the replacement can be stored (ITL-1871). Run
preflight checks the depth of an automatic source cache path even when the source has
yet to poll and its column types are unknown.

**Open (the real fix, a later release):** store list and struct columns (for example as JSON
text read back as the same Arrow type) and timestamps on SQLite, and rename SpiralDB's
reserved column names on write and recover them on read, and restore a timestamp's time
Expand Down
36 changes: 35 additions & 1 deletion src/orcapod/contexts/stored.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

import logging
import warnings
from collections.abc import Collection
from collections.abc import Callable, Collection
from dataclasses import dataclass, field
from typing import Any, NamedTuple, Protocol, cast

Expand Down Expand Up @@ -611,3 +611,37 @@ def require_storable(database: object, schema: pa.Schema) -> None:
check = getattr(database, "require_storable", None)
if callable(check):
_ = check(schema)


def require_storable_record_path(
database: object, record_path: Callable[[], tuple[str, ...]]
) -> None:
"""Check a table path on a database that declares a path limit.

A database states its limit with ``require_storable_path`` (a connector database,
whatever its backend); any other database accepts every path. ``record_path`` is
called only when the database declares a limit.

Args:
database: The database the table would be written to.
record_path: Gives the table's path, relative to the database's base path.

Raises:
ValueError: If the full path is deeper than the database's limit.
"""
check = getattr(database, "require_storable_path", None)
if callable(check):
_ = check(record_path())


def require_storable_path(
database: object, record_path: Callable[[], tuple[str, ...]], *, node_label: str
) -> None:
"""Check a node's table path on databases that declare a path limit.

As ``require_storable_record_path``, with the refusal naming the node.
"""
try:
require_storable_record_path(database, record_path)
except ValueError as exc:
raise ValueError(f"Node {node_label!r}: {exc}") from exc
49 changes: 42 additions & 7 deletions src/orcapod/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@

logger = logging.getLogger(__name__)

_live_content_hashes: ContextVar[
dict[int, tuple[object, dict[str, ContentHash]]] | None
] = ContextVar("live_content_hashes", default=None)
_HashMemo = dict[int, tuple[object, dict[str, ContentHash]]]
_live_content_hashes: ContextVar[_HashMemo | None] = ContextVar(
"live_content_hashes", default=None
)
_isolated_pipeline_hashes: ContextVar[_HashMemo | None] = ContextVar(
"isolated_pipeline_hashes", default=None
)
_pipeline_hash_probe: ContextVar[object] = ContextVar(
"pipeline_hash_probe", default=None
)
Expand All @@ -33,13 +37,33 @@ def __init__(self, element: PipelineElementBase) -> None:
@contextmanager
def live_content_hashes() -> Iterator[None]:
"""Compute content hashes in a temporary cache for a live binding read."""
if isolating_identity_hashes():
yield
return
token = _live_content_hashes.set({})
try:
yield
finally:
_live_content_hashes.reset(token)


@contextmanager
def isolated_identity_hashes() -> Iterator[None]:
"""Keep all legacy hash memo entries local to a candidate binding check."""
content = _live_content_hashes.set({})
pipeline = _isolated_pipeline_hashes.set({})
try:
yield
finally:
_isolated_pipeline_hashes.reset(pipeline)
_live_content_hashes.reset(content)


def isolating_identity_hashes() -> bool:
"""Whether a candidate binding check is using isolated legacy hash memos."""
return _isolated_pipeline_hashes.get() is not None


# Base classes for Orcapod core components, providing common functionality.


Expand Down Expand Up @@ -212,7 +236,10 @@ def content_hash(self, hasher=None) -> ContentHash:
cache_key = hasher.hasher_id
cache = self._content_hash_cache
live_cache = _live_content_hashes.get()
if live_cache is not None and self._content_hash_depends_on_bindings:
if live_cache is not None and (
self._content_hash_depends_on_bindings
or (isolating_identity_hashes() and cache_key not in cache)
):
# Keep each object alive for the read so its id stays unique.
cache = live_cache.setdefault(id(self), (self, {}))[1]

Expand Down Expand Up @@ -322,7 +349,15 @@ def pipeline_hash(self, hasher=None) -> ContentHash:
if hasher is None:
hasher = self.data_context.semantic_hasher
cache_key = hasher.hasher_id
cached = self._pipeline_hash_cache.get(cache_key)
scoped = _isolated_pipeline_hashes.get()

def cache_for(element: PipelineElementBase) -> dict[str, ContentHash]:
if scoped is not None:
return scoped.setdefault(id(element), (element, {}))[1]
return element._pipeline_hash_cache

cache = cache_for(self)
cached = cache.get(cache_key)
if cached is not None:
return cached
if _pipeline_hash_probe.get() is hasher:
Expand Down Expand Up @@ -355,10 +390,10 @@ def pipeline_resolver(obj: Any) -> ContentHash:
pending.append((upstream, upstream.pipeline_identity_structure()))
active.add(identity)
else:
element._pipeline_hash_cache[cache_key] = digest
cache_for(element)[cache_key] = digest
active.remove(id(element))
pending.pop()
return self._pipeline_hash_cache[cache_key]
return cache[cache_key]

def _invalidate_pipeline_hash_cache(self) -> None:
"""Invalidate the cached pipeline hash.
Expand Down
11 changes: 11 additions & 0 deletions src/orcapod/core/cached_function_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
StaleTables,
data_context_field,
require_storable,
require_storable_record_path,
)
from orcapod.core.result_cache import (
ResultCache,
Expand Down Expand Up @@ -95,6 +96,9 @@ def __init__(
def require_storable_results(self) -> None:
"""Refuse a result database that cannot store this pod's result table (ITL-1162).

Each result database the pod writes (its own, its function's
``function_pod(result_database=)``, a wrapped pod's ``pod_cache_database``)
is checked for the depth of the table's path (ITL-1871) and for its columns.
The result table holds the input data hash, the function's variation and
execution columns (``__pf_var_*``, ``__pf_exec_*``), its output columns,
the ``__pod_ts`` timestamp and ``__data_context``, typed from their declared
Expand All @@ -103,11 +107,18 @@ def require_storable_results(self) -> None:
refuses here, before the function runs; any other database accepts.

Raises:
ValueError: If a result table's path is deeper than its database allows.
UnstorableColumnError: If the result database cannot store a column.
"""
import pyarrow as pa

pf = self._function_pod.data_function
require_storable_record_path(
self._cache.result_database, lambda: self.record_path
)
if isinstance(pf, CachedDataFunction):
require_storable_record_path(pf.result_database, lambda: pf.record_path)

python_schema = {
**{
f"{constants.PF_VARIATION_PREFIX}{name}": hint
Expand Down
28 changes: 26 additions & 2 deletions src/orcapod/core/identity_chains.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@
NODE_HASH_LABEL = "node_hash_v1"

_reading_chains: ContextVar[bool] = ContextVar("reading_identity_chains", default=False)
_scoped_chains: ContextVar[dict[tuple[int, str, bool, bool], IdentityChains] | None] = (
ContextVar("scoped_identity_chains", default=None)
)


@contextmanager
def isolated_identity_chains() -> Iterator[None]:
"""Compute candidate identities without reading or changing the live chain cache."""
token = _scoped_chains.set({})
try:
yield
finally:
_scoped_chains.reset(token)


@contextmanager
Expand Down Expand Up @@ -142,6 +155,8 @@ def __init__(

def depend_on(self, element: IdentityChainsMixin) -> None:
"""Record a dependency for the node whose chains are being evaluated."""
if _scoped_chains.get() is not None:
return
consumer = self._consumer
if consumer is not None and consumer is not element:
element._identity_dependents[id(consumer)] = consumer
Expand Down Expand Up @@ -422,6 +437,8 @@ def _identity_hash(
preimage: tuple[object, ...] | None = None,
) -> ContentHash:
"""Reuse hashes across chain reads and unchanged name inputs."""
if _scoped_chains.get() is not None:
return _hash(label, key_parts if preimage is None else preimage)
if label in (SOURCE_CHAIN_HASH_LABEL, CONTENT_HASH_LABEL):
if self._identity_source_hashes is None:
self._identity_source_hashes = {}
Expand Down Expand Up @@ -491,10 +508,17 @@ def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains:
A full memo can satisfy a name-only walk. A name-only memo cannot
satisfy a walk that includes sources.
"""
if self._identity_cache is None:
self._identity_cache = {}
hasher_id = walk.hasher.hasher_id
guarded = reading_identity_chains()
scoped = _scoped_chains.get()
if scoped is not None:
scoped_key = (id(self), hasher_id, walk.include_sources, guarded)
if scoped_key not in scoped:
scoped[scoped_key] = self._compute_identity_chains(walk)
return scoped[scoped_key]

if self._identity_cache is None:
self._identity_cache = {}
full_key = (hasher_id, True, guarded)
if not walk.include_sources and full_key in self._identity_cache:
return self._identity_cache[full_key]
Expand Down
46 changes: 36 additions & 10 deletions src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import pyarrow as pa

from orcapod import contexts
from orcapod.core.base import isolating_identity_hashes
from orcapod.core.result_cache import read_stored_result_table
from orcapod.core.output_bindings import (
OutputBindings,
Expand Down Expand Up @@ -64,7 +65,9 @@
ZERO_ROW_INPUT_COLUMNS,
StreamBase,
check_head_size,
schema_requires_io,
short_stream_repr,
typed_arrow_schemas,
)
from orcapod.core.streams.view import (
BLUEPRINT_NOTE,
Expand Down Expand Up @@ -104,6 +107,7 @@
report_rows_of_other_data_contexts,
report_unexpected_row_count,
require_storable,
require_storable_path,
)
from orcapod.utils.database_errors import (
commit_best_effort,
Expand Down Expand Up @@ -716,14 +720,16 @@ def node_identity_path(self) -> tuple[str, ...]:
f"instance:{self.content_hash().to_hex()}",
)
return self._stored_pipeline_path
if self._node_identity_path_cache is not None:
isolated = isolating_identity_hashes()
if not isolated and self._node_identity_path_cache is not None:
return self._node_identity_path_cache
pf = self._function_pod
# Hashes inside a path are bare hex digests: a label never enters a name.
path = pf.uri + (f"schema:{self.pipeline_hash().to_hex()}",)
if self._table_scope != "pipeline_hash":
return path + (f"instance:{self.content_hash().to_hex()}",)
self._node_identity_path_cache = path
if not isolated:
self._node_identity_path_cache = path
return path

@property
Expand Down Expand Up @@ -1001,6 +1007,9 @@ def require_storable_results(self, result_database: ArrowDatabaseProtocol) -> No
persistent result database or an ephemeral one).

Raises:
ValueError: If a result table's path (in ``result_database`` or a
function's own result database) is deeper than its database allows,
naming this node.
UnstorableColumnError: If the database cannot store a column, naming
this node.
"""
Expand All @@ -1013,6 +1022,9 @@ def require_storable_results(self, result_database: ArrowDatabaseProtocol) -> No
except UnstorableColumnError as exc:
exc.add_context(node_label=self.label)
raise
except ValueError as exc:
# A result table's path deeper than its database allows (ITL-1871).
raise ValueError(f"Node {self.label!r}: {exc}") from exc

@abstractmethod
def set_ephemeral_database(self, database: "ArrowDatabaseProtocol | None") -> None:
Expand Down Expand Up @@ -1740,6 +1752,11 @@ def require_storable_tables(
"""
if self._function_pod is None:
return
require_storable_path(
pipeline_database,
lambda: self._versioned_pipeline_path,
node_label=self.label,
)
# A table must state its data-tags (ITL-1019): a database that cannot
# is refused first, with the two ways out, as ``attach_databases`` refuses it.
require_database_keeps_marker(
Expand All @@ -1748,8 +1765,15 @@ def require_storable_tables(
if result_database is None:
result_database = pipeline_database.at("_result")
self.require_storable_results(result_database)
from orcapod.databases.spiraldb_write_scope import writable_connectors

try:
require_storable(pipeline_database, _pipeline_meta_schema())
if writable_connectors((pipeline_database,)) and not schema_requires_io(
self._input_stream, ColumnConfig()
):
tags, _ = typed_arrow_schemas(self._input_stream)
require_storable(pipeline_database, tags)
except UnstorableColumnError as exc:
exc.add_context(node_label=self.label)
raise
Expand Down Expand Up @@ -1796,6 +1820,16 @@ def attach_databases(
self.require_storable_tables(pipeline_database, result_database)
if ephemeral_database is not None:
self.require_storable_results(ephemeral_database)
self._attach_databases(pipeline_database, result_database)
if ephemeral_database is not None:
self.set_ephemeral_database(ephemeral_database)

def _attach_databases(
self,
pipeline_database: ArrowDatabaseProtocol | None,
result_database: ArrowDatabaseProtocol | None,
) -> None:
"""Install the validated pipeline and result databases."""
# Another database has its own tables of other generations to account for.
self._stale_tables_checked = False
self._current_tables_checked = False
Expand All @@ -1812,11 +1846,6 @@ def attach_databases(
result_database = pipeline_database.at("_result")

if self._function_pod is not None:
# A table must state its data-tags: refuse a database that
# cannot, before anything is written (ITL-1019).
require_database_keeps_marker(
pipeline_database, fall_through_tags(self._function_pod)
)
# Normal path: wrap in CachedFunctionPod for compute + cache.
# A fall-through pod's results are its plain pod's (ITL-1023).
self._cached_function_pod = CachedFunctionPod(
Expand Down Expand Up @@ -1845,9 +1874,6 @@ def attach_databases(
self._invalidate_content_hash_cache()
self._invalidate_pipeline_hash_cache()

if ephemeral_database is not None:
self.set_ephemeral_database(ephemeral_database)

# ------------------------------------------------------------------
# from_descriptor — read-only stub for loaded jobs
# ------------------------------------------------------------------
Expand Down
Loading
Loading