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

- `PipelineJob.load` raises `ValueError` when the file's database or result database is a
connector database (SQLite, PostgreSQL, SpiralDB) and it is not given, naming each binding
and the argument to pass (`database=`, `result_database=`). A connector is never rebuilt
from a saved file. It used to log `Unknown database type` and load a job that could read
nothing. (ITL-1391)

### Fixed

- When a saved database or result database cannot be rebuilt, saving the loaded job
preserves the original configuration while that slot remains unbound. If you later
bind a database to that slot, saving writes the newly bound database's configuration.
(ITL-1391)
- The warnings about a saved source, database or result database that could not be rebuilt
name the slot, the kind and the type of the error, and no longer hold the exception text.
(ITL-1391)
7 changes: 5 additions & 2 deletions docs/concepts/function-pods.md
Original file line number Diff line number Diff line change
Expand Up @@ -1123,13 +1123,16 @@ from that database, and no rows under that key is an empty result, not an error.
is refused the same way: wrap its table as a source,
`ArrowTableSource(stream.as_table(), tag_columns=[...])`.
- The results are read from the database recorded in the file. Pass
`PipelineJob.load(path, database=...)` if the database has moved.
`PipelineJob.load(path, database=...)` if the database has moved. A connector database
(SQLite, PostgreSQL, SpiralDB) must always be passed: without it the load raises
`ValueError` naming the argument to pass.
- A job given a separate result database
([Sharing function results between jobs](pipeline-job.md#sharing-function-results-between-jobs))
records it in the file too, and loading rebuilds it the same way; pass
`PipelineJob.load(path, result_database=...)` if it has moved or cannot be rebuilt from
the file. An `InMemoryArrowDatabase` holds nothing after its process ends, so it is never
rebuilt (a new one would be empty), as a connector database is not. When the file names a
rebuilt (a new one would be empty). A connector result database must be passed at load,
as a connector `database` must. When the file names another
result database that is not available and none is given, the loaded job's function nodes
get no database (a warning says what to pass): they are never pointed at the job's own
`_result` location, which holds none of their results. `job.bind(result_database=...)`
Expand Down
6 changes: 5 additions & 1 deletion docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,11 @@ result database's, when one was given) and how each source was configured. `Pipe
Python session. An `InMemoryArrowDatabase` has no location to record, so here the database
is passed again; `PipelineJob.load(path, database=...)` is also how you point a loaded job
at a database that has moved, and `PipelineJob.load(path, result_database=...)` at a result
database. The file records each node's own Arrow types, so saving types
database. A connector database (SQLite, PostgreSQL, SpiralDB) is never rebuilt from the
file: pass it, built over your connector, or the load raises an error that names what to
pass. Saving a loaded job writes the database actually bound, the one you passed, in place of
the recorded one. The recorded one is kept only while nothing is bound in its slot, which
happens when a database of another kind could not be rebuilt and none was passed. The file records each node's own Arrow types, so saving types
every node from its inputs' types, as previewing an empty job does, and costs what that
preview costs: a pipeline whose joins keep many system-tag columns saves as slowly as it
previews.
Expand Down
18 changes: 11 additions & 7 deletions src/orcapod/databases/connector_arrow_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@
normalize_to_large_types,
)

#: The ``type`` of a connector database's saved configuration.
CONNECTOR_DATABASE_TYPE = "connector_arrow_database"


def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]:
"""Convert a PyArrow schema to a list of ColumnInfo."""
Expand Down Expand Up @@ -923,22 +926,23 @@ def get_records_with_column_value(
def to_config(self, db_registry: Any = None) -> dict[str, Any]:
"""Serialize configuration to a JSON-compatible dict."""
return {
"type": "connector_arrow_database",
"type": CONNECTOR_DATABASE_TYPE,
"connector": self._connector.to_config(),
"base_path": list(self._path_prefix),
"max_hierarchy_depth": self.max_hierarchy_depth,
}

@classmethod
def from_config(cls, config: dict[str, Any]) -> ConnectorArrowDatabase:
"""Reconstruct a ConnectorArrowDatabase from config.
"""Refuse: a connector is not rebuilt from a saved configuration (ITL-1391).

The connection is the user's to supply: a loaded job is given its database,
``PipelineJob.load(path, database=ConnectorArrowDatabase(<connector>))``.

Raises:
NotImplementedError: Always — requires a connector registry that
maps ``connector_type`` keys to ``from_config`` classmethods.
Implement alongside connector classes in PLT-1074/1075/1076.
NotImplementedError: Always.
"""
raise NotImplementedError(
"ConnectorArrowDatabase.from_config requires a registered connector "
"factory (connector_type → class). Implement in PLT-1074/1075/1076."
"A connector database is not rebuilt from its saved configuration: build "
"ConnectorArrowDatabase(<connector>) and pass it."
)
67 changes: 54 additions & 13 deletions src/orcapod/pipeline/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ def __init__(
# job's own ``_result`` location, which holds none of their results, and a save
# writes the configuration back as it was (ITL-1408).
self._unresolved_result_database: dict[str, Any] | None = None
# The same for the job's own database: the saved configuration of one that
# could not be rebuilt, written back by a save until one is given (ITL-1391).
self._unresolved_database: dict[str, Any] | None = None
self._execution_context = execution_context
self._auto_compile = auto_compile
# name → bound concrete source (user-facing API: job.sources).
Expand Down Expand Up @@ -535,6 +538,8 @@ def bind(
# the job as it was, its database included (ITL-1112).
self._database = new_database
self._result_database = new_result_database
if database is not None:
self._unresolved_database = None
if result_database_given:
self._unresolved_result_database = None

Expand Down Expand Up @@ -1639,8 +1644,9 @@ def save(self, path: "str | Path") -> None:
else:
sources_block[spec_name] = {"source_type": "unknown"}

# Database config (best-effort)
database_block = None
# Database config (best-effort). A loaded job's database that could not be
# rebuilt is written back as it was saved (ITL-1391).
database_block = self._unresolved_database
if self._database is not None and hasattr(self._database, "to_config"):
database_block = self._database.to_config()
# A separate result database (ITL-1408), saved by the same rule; ``None`` when
Expand Down Expand Up @@ -1741,9 +1747,11 @@ def load(
Args:
path: Path to the JSON file produced by ``save()``.
database: Optional database override. When provided, takes precedence
over any database configuration in the file.
over any database configuration in the file. Required when the file's
database is a connector database.
result_database: Optional override of the separate function-result
database (ITL-1408). When provided, it is used whatever the file
database (ITL-1408), required when the file names a connector
database. When provided, it is used whatever the file
says. Otherwise the one the file names is rebuilt from its saved
configuration, as the job's database is; a file that names none
keeps the results in the job's database (``<name>/_result``). When
Expand All @@ -1761,7 +1769,10 @@ def load(
saved before the database key was renamed (``bindings.store``
instead of ``bindings.database``) and no ``database`` is given.
An explicit ``database`` makes the saved block irrelevant, so
such a file then loads.
such a file then loads. Also if the file's database or result
database is a connector database (SQLite, PostgreSQL, SpiralDB) and
the argument that gives it is missing: a connector is not rebuilt
from a file. The message names each such binding.
"""
import json as _json
import os
Expand All @@ -1777,6 +1788,9 @@ def load(
require_current_format,
require_tag_only_columns,
resolve_source_from_config,
saved_connector_kind,
saved_database_kind,
saved_source_kind,
)

path = _Path(path)
Expand All @@ -1792,6 +1806,26 @@ def load(
exc.add_note(f"Loading the job file {path}")
raise

# A connector is supplied by the user, never rebuilt from the file (ITL-1391):
# refused before anything is rebuilt. Nothing of the saved configuration is
# shown.
missing: list[str] = []
for slot_name, given in (
("database", database),
("result_database", result_database),
):
kind = saved_connector_kind(data.get("bindings", {}).get(slot_name))
if kind is not None and given is None:
missing.append(
f"bindings.{slot_name} is a connector database ({kind}): pass "
f"{slot_name}=ConnectorArrowDatabase(<your connector>)"
)
if missing:
raise ValueError(
f"{path}: a database connector is not rebuilt from a saved job; it "
"must be given to PipelineJob.load. " + "; ".join(missing) + "."
)

# Reconstruct pipeline from embedded blueprint data
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as tmp:
tmp_path = tmp.name
Expand All @@ -1817,7 +1851,6 @@ def load(
for spec_name, src_config in (
data.get("bindings", {}).get("sources", {}).items()
):
source_type = src_config.get("source_type")
# Every source states its plain tags (ITL-1019): a refusal is the file's
# error, not a source that could not be rebuilt.
try:
Expand Down Expand Up @@ -1854,7 +1887,7 @@ def load(
"results are still readable from the database. To read source node "
"%r itself, bind a source: job.bind(sources={%r: <source>}).",
spec_name,
source_type,
saved_source_kind(src_config),
spec_name,
spec_name,
)
Expand All @@ -1870,14 +1903,16 @@ def load(
"To read source node %r itself, bind a source: "
"job.bind(sources={%r: <source>}).",
spec_name,
source_type,
exc,
saved_source_kind(src_config),
# Its type, never its text (ITL-1391).
type(exc).__name__,
spec_name,
spec_name,
)

# Reconstruct database
effective_database = database
unresolved_database: dict[str, Any] | None = None
if effective_database is None:
bindings = data.get("bindings", {})
if bindings.get("store") and "database" not in bindings:
Expand All @@ -1899,11 +1934,15 @@ def load(

effective_database = resolve_database_from_config(store_config)
except Exception as exc:
unresolved_database = store_config
# The exception's type, never its text (ITL-1391).
logger.warning(
"Could not reconstruct the database from its saved config: %s. "
"Could not reconstruct the database from its saved config: "
"bindings.database (%s): %s. "
"Node results cannot be read until a database is given: "
"PipelineJob.load(path, database=...) or job.bind(database=...).",
exc,
saved_database_kind(store_config),
type(exc).__name__,
)

# Reconstruct the job directly without going through to_invocations().
Expand Down Expand Up @@ -1940,11 +1979,12 @@ def load(
unresolved_result_database = result_config
logger.warning(
"Could not reconstruct the job's separate result database "
"(bindings.result_database) from its saved config: %s. The "
"(bindings.result_database) from its saved config (%s): %s. The "
"function nodes' results cannot be read until it is given: "
"PipelineJob.load(path, result_database=...) or "
"job.bind(result_database=...).",
exc,
saved_database_kind(result_config),
type(exc).__name__,
)

job = cls(
Expand All @@ -1953,6 +1993,7 @@ def load(
result_database=effective_result_database,
)
job._unresolved_result_database = unresolved_result_database
job._unresolved_database = unresolved_database
job._loaded = True
job._compiled_pipeline = pipeline
# Mark compiled so save() / compiled_pipeline can be accessed.
Expand Down
79 changes: 77 additions & 2 deletions src/orcapod/pipeline/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,7 @@ def resolve_database_from_config(
return root_db.at(*config["path"])
if db_type not in DATABASE_REGISTRY:
raise ValueError(
f"Unknown database type: {db_type!r}. "
f"Known types: {sorted(DATABASE_REGISTRY.keys())}"
f"Unknown database type. Known types: {sorted(DATABASE_REGISTRY.keys())}"
)
if db_type == "in_memory":
logger.warning(
Expand All @@ -453,6 +452,82 @@ def resolve_database_from_config(
return cls.from_config(config)


#: The kinds of connector a message may name.
_CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb")


def saved_database_kind(config: Any) -> str:
"""The kind of a saved database configuration, for a message: never the saved text.

Args:
config: A saved database configuration.

Returns:
A key of ``DATABASE_REGISTRY``, or ``"unknown database kind"``.
"""
if isinstance(config, dict):
kind = cast("dict[str, Any]", config).get("type")
for known in DATABASE_REGISTRY:
if kind == known:
return known
return "unknown database kind"


def saved_source_kind(config: Any) -> str:
"""The kind of a saved source configuration, for a message: never the saved text.

Args:
config: A saved source configuration.

Returns:
The ``SOURCE_KIND`` of one of Orcapod's sources, or ``"unknown source kind"``.
"""
from orcapod.core.sources.db_table_source import DBTableSource
from orcapod.core.sources.polling_source import PollingSource

if isinstance(config, dict):
kind = cast("dict[str, Any]", config).get("source_type")
for known in (
*SOURCE_REGISTRY,
# Written by a save, rebuilt by no load.
DBTableSource.SOURCE_KIND,
PollingSource.SOURCE_KIND,
):
if kind == known:
return known
return "unknown source kind"


def saved_connector_kind(config: Any) -> str | None:
"""The kind of connector a saved database configuration is over, or ``None``.

A connector is not rebuilt from a saved file: the user supplies it at load
(developer, 2026-11-22, ITL-1391). Never the saved text.

Args:
config: A saved database configuration, or ``None``.

Returns:
``"sqlite"``, ``"postgresql"`` or ``"spiraldb"``, ``"unknown connector kind"``
for anything else the file says, or ``None`` for a database that is not over
a connector.
"""
from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE

if not isinstance(config, dict):
return None
saved = cast("dict[str, Any]", config)
if saved.get("type") != CONNECTOR_DATABASE_TYPE:
return None
connector = saved.get("connector")
if isinstance(connector, dict):
kind = cast("dict[str, Any]", connector).get("connector_type")
for known in _CONNECTOR_KINDS:
if kind == known:
return known
return "unknown connector kind"


def resolve_operator_from_config(config: dict[str, Any]) -> Any:
"""Reconstruct an operator instance from a config dict.

Expand Down
Loading
Loading