From 27a7af4834372955c2c5e23379d49462a194a6bc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 09:34:43 -0800 Subject: [PATCH 1/7] fix(pipeline): a saved connector database is supplied at load (ITL-1391) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1391.md | 12 + docs/concepts/function-pods.md | 7 +- docs/concepts/pipeline-job.md | 4 +- .../databases/connector_arrow_database.py | 18 +- src/orcapod/pipeline/job.py | 45 ++- src/orcapod/pipeline/serialization.py | 28 ++ .../test_load_connector_database.py | 265 ++++++++++++++++++ 7 files changed, 364 insertions(+), 15 deletions(-) create mode 100644 changelog.d/ITL-1391.md create mode 100644 tests/test_pipeline/loaded_job/test_load_connector_database.py diff --git a/changelog.d/ITL-1391.md b/changelog.d/ITL-1391.md new file mode 100644 index 000000000..b7d5ce463 --- /dev/null +++ b/changelog.d/ITL-1391.md @@ -0,0 +1,12 @@ +### 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 + +- Saving a loaded job whose database could not be rebuilt writes the saved database + configuration back as it was, instead of `null`. (ITL-1391) diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 8aebfb95f..ec9f982a6 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -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=...)` diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 83bf7acf3..40099f0c7 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -466,7 +466,9 @@ 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. 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. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 6ae7f757c..6e7bd8a63 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -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.""" @@ -923,7 +926,7 @@ 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, @@ -931,14 +934,15 @@ def to_config(self, db_registry: Any = None) -> dict[str, Any]: @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())``. 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() and pass it." ) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 2f80d1fa0..8ef064282 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -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). @@ -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 @@ -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 @@ -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 (``/_result``). When @@ -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 @@ -1777,6 +1788,7 @@ def load( require_current_format, require_tag_only_columns, resolve_source_from_config, + saved_connector_type, ) path = _Path(path) @@ -1792,6 +1804,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. Only the connector's kind is named; its + # saved connection may hold a credential. + missing: list[str] = [] + for slot_name, given in ( + ("database", database), + ("result_database", result_database), + ): + kind = saved_connector_type(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()" + ) + 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 @@ -1878,6 +1910,7 @@ def load( # 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: @@ -1899,6 +1932,7 @@ def load( effective_database = resolve_database_from_config(store_config) except Exception as exc: + unresolved_database = store_config logger.warning( "Could not reconstruct the database from its saved config: %s. " "Node results cannot be read until a database is given: " @@ -1953,6 +1987,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. diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index abbebf83d..07c0bfc9d 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -453,6 +453,34 @@ def resolve_database_from_config( return cls.from_config(config) +def saved_connector_type(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). Only the kind (``"sqlite"``) is read, never the + connection, which may hold a credential. + + Args: + config: A saved database configuration, or ``None``. + + Returns: + The connector's kind (``"unknown"`` when the file does not say), 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 not isinstance(connector, dict): + return "unknown" + kind = cast("dict[str, Any]", connector).get("connector_type") + return kind if isinstance(kind, str) else "unknown" + + def resolve_operator_from_config(config: dict[str, Any]) -> Any: """Reconstruct an operator instance from a config dict. diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py new file mode 100644 index 000000000..03951ee0e --- /dev/null +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -0,0 +1,265 @@ +"""A saved connector database is supplied at load, never rebuilt (ITL-1391). + +The connectors cannot hold a function node's tables (entry CA3, ITL-1162), so the jobs +here hold operators only. PostgreSQL cannot hold an operator node's tables either (a +table name is cut at 63 bytes), so a file naming it as the job's database is made by +putting its configuration into a saved file; as a result database it is saved directly. +""" + +from __future__ import annotations + +import asyncio +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + PostgreSQLConnector, + SpiralDBConnector, + SQLiteConnector, +) +from orcapod.sources import ArrowTableSource +from tests.test_databases import fake_pyspiral + +KINDS = ("sqlite", "postgresql", "spiraldb") +# The kinds an operator-only job runs on. +RUNNABLE = ("sqlite", "spiraldb") +# Not a real credential. +PASSWORD = "synthetic-pass-word" + + +class Databases: + """Connector databases of each kind, each over its own place per name.""" + + def __init__(self, root: Path) -> None: + self.root = root + + def make(self, kind: str, name: str) -> ConnectorArrowDatabase: + if kind == "sqlite": + return ConnectorArrowDatabase( + SQLiteConnector(str(self.root / f"{name}.sqlite")) + ) + if kind == "postgresql": + return ConnectorArrowDatabase( + PostgreSQLConnector(f"postgresql://u:{PASSWORD}@h/{name}") + ) + fake_pyspiral.FakeSpiral().project(name) + return ConnectorArrowDatabase(SpiralDBConnector(name)) + + +@pytest.fixture +def databases(tmp_path: Path) -> Iterator[Databases]: + with ( + fake_pyspiral.install(tmp_path / "spiral"), + patch("psycopg.connect") as connect, + ): + connect.return_value = MagicMock() + yield Databases(tmp_path) + + +def _sources() -> dict[str, Any]: + left = pa.table( + {"a": [1, 2, 3], "b": ["x", "y", "z"], "p": [1.0, 2.0, 3.0], "q": [4, 5, 6]} + ) + right = pa.table({"b": ["z", "x"], "a": [3, 1], "r": [30, 10], "s": ["u", "v"]}) + return { + name: ArrowTableSource( + table, tag_columns=["a", "b"], source_id=name, tag_only_columns=True + ) + for name, table in (("left", left), ("right", right)) + } + + +def _save( + path: Path, *, run_async: bool = False, **databases: Any +) -> tuple[PipelineJob, dict[str, Any]]: + """An operator-only job, run and saved, and its file's bindings.""" + sources = _sources() + job = PipelineJob(name="j", **databases) + with job: + joined = sources["left"].join(sources["right"], label="joined") + joined.select_data_columns(["s", "p"], label="picked") + if run_async: + asyncio.run(job.run_async()) + else: + job.run() + job.save(path) + return job, json.loads(path.read_text())["bindings"] + + +def _save_over(path: Path, databases: Databases, kind: str, **given: Any) -> None: + """A saved job file whose database is of ``kind`` (see the module docstring).""" + if kind in RUNNABLE: + _save(path, database=databases.make(kind, "a"), **given) + return + _save(path, database=databases.make("sqlite", "a"), **given) + data = json.loads(path.read_text()) + data["bindings"]["database"] = databases.make(kind, "a").to_config() + path.write_text(json.dumps(data)) + + +def _values(job: PipelineJob) -> list[dict[str, Any]]: + rows = job.nodes["picked"].as_table().select(["a", "b", "s", "p"]).to_pylist() + return sorted(rows, key=lambda row: row["a"]) + + +EXPECTED = [ + {"a": 1, "b": "x", "s": "v", "p": 1.0}, + {"a": 3, "b": "z", "s": "u", "p": 3.0}, +] + + +@pytest.mark.parametrize("kind", KINDS) +def test_load_without_the_database_names_the_slot_and_what_to_pass( + databases: Databases, tmp_path: Path, kind: str +) -> None: + path = tmp_path / "job.json" + _save_over(path, databases, kind) + with pytest.raises(ValueError) as refused: + PipelineJob.load(path) + message = str(refused.value) + assert f"bindings.database is a connector database ({kind})" in message + assert "pass database=ConnectorArrowDatabase(" in message + assert "result_database" not in message + assert "Unknown database type" not in message + # The saved connection is never shown. + assert PASSWORD not in message + + +@pytest.mark.parametrize("kind", KINDS) +@pytest.mark.parametrize("result_kind", KINDS) +def test_every_missing_slot_is_named( + databases: Databases, tmp_path: Path, kind: str, result_kind: str +) -> None: + path = tmp_path / "job.json" + results = databases.make(result_kind, "b") + _save_over(path, databases, kind, result_database=results) + # Any given database fills a slot: one the job's operators can be stored in. + database = databases.make("sqlite", "a") + wanted = { + "database": f"bindings.database is a connector database ({kind})", + "result_database": ( + f"bindings.result_database is a connector database ({result_kind})" + ), + } + for given in ({}, {"database": database}, {"result_database": results}): + with pytest.raises(ValueError) as refused: + PipelineJob.load(path, **given) + for slot, text in wanted.items(): + assert (text in str(refused.value)) is (slot not in given) + assert PASSWORD not in str(refused.value) + loaded = PipelineJob.load(path, result_database=results, database=database) + assert loaded.database is database + assert loaded.result_database is results + + +@pytest.mark.parametrize("kind", KINDS) +def test_a_connector_result_database_beside_a_delta_database( + databases: Databases, tmp_path: Path, kind: str +) -> None: + path = tmp_path / "job.json" + results = databases.make(kind, "b") + _save( + path, + database=DeltaTableDatabase(tmp_path / "delta"), + result_database=results, + ) + with pytest.raises(ValueError, match="pass result_database="): + PipelineJob.load(path) + loaded = PipelineJob.load(path, result_database=results) + assert isinstance(loaded.database, DeltaTableDatabase) + + +@pytest.mark.parametrize("kind", RUNNABLE) +@pytest.mark.parametrize("saved_async", [False, True]) +@pytest.mark.parametrize("loaded_async", [False, True]) +def test_load_with_the_database_then_load_only( + databases: Databases, + tmp_path: Path, + kind: str, + saved_async: bool, + loaded_async: bool, +) -> None: + path = tmp_path / "job.json" + job, bindings = _save( + path, run_async=saved_async, database=databases.make(kind, "a") + ) + assert _values(job) == EXPECTED + hashes = {label: n.content_hash().to_string() for label, n in job.nodes.items()} + + # A new handle over the same place, as another process would make. + loaded = PipelineJob.load(path, database=databases.make(kind, "a")) + loaded.bind(sources=_sources()) + assert { + label: n.content_hash().to_string() for label, n in loaded.nodes.items() + } == hashes + if loaded_async: + asyncio.run(loaded.run_async(load_only=True)) + else: + loaded.run(load_only=True) + assert _values(loaded) == EXPECTED + + again = tmp_path / "again.json" + loaded.save(again) + assert ( + json.loads(again.read_text())["bindings"]["database"] == (bindings["database"]) + ) + with pytest.raises(ValueError, match="pass database="): + PipelineJob.load(again) + + +@pytest.mark.parametrize("kind", KINDS) +def test_any_given_database_is_used_whatever_connector_was_saved( + databases: Databases, tmp_path: Path, kind: str +) -> None: + path = tmp_path / "job.json" + _save_over(path, databases, kind) + given = DeltaTableDatabase(tmp_path / "delta") + assert PipelineJob.load(path, database=given).database is given + + +@pytest.mark.parametrize("connector", [None, {}, {"connector_type": 3}, "text"]) +def test_a_connector_the_file_does_not_name_is_refused_too( + databases: Databases, tmp_path: Path, connector: Any +) -> None: + path = tmp_path / "job.json" + _save(path, database=databases.make("sqlite", "a")) + data = json.loads(path.read_text()) + data["bindings"]["database"]["connector"] = connector + path.write_text(json.dumps(data)) + with pytest.raises(ValueError, match=r"connector database \(unknown\)"): + PipelineJob.load(path) + + +def test_saving_a_loaded_job_keeps_a_database_that_could_not_be_rebuilt( + tmp_path: Path, +) -> None: + path, again = tmp_path / "job.json", tmp_path / "again.json" + _save(path, database=DeltaTableDatabase(tmp_path / "delta")) + data = json.loads(path.read_text()) + saved = {"type": "no_such_database", "place": ["x", "y"]} + data["bindings"]["database"] = saved + path.write_text(json.dumps(data)) + + loaded = PipelineJob.load(path) + assert loaded.database is None + loaded.save(again) + assert json.loads(again.read_text())["bindings"]["database"] == saved + + # A bind of sources or a result database leaves it; a bound database replaces it. + loaded.bind(sources=_sources()) + loaded.bind(result_database=DeltaTableDatabase(tmp_path / "results")) + loaded.save(again) + assert json.loads(again.read_text())["bindings"]["database"] == saved + given = DeltaTableDatabase(tmp_path / "given") + loaded.bind(database=given) + loaded.save(again) + assert json.loads(again.read_text())["bindings"]["database"] == given.to_config() From ecafdf69bbf41051c70178cafe94246816e68421 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:02:51 -0800 Subject: [PATCH 2/7] fix(pipeline): show no saved text of a connector database; pin what a re-save writes (ITL-1391) Co-Authored-By: Claude Opus 5.5 --- docs/concepts/pipeline-job.md | 4 +- src/orcapod/pipeline/job.py | 10 +-- src/orcapod/pipeline/serialization.py | 29 ++++--- .../test_load_connector_database.py | 84 ++++++++++++++++++- 4 files changed, 108 insertions(+), 19 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 40099f0c7..f6906e47e 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -468,7 +468,9 @@ is passed again; `PipelineJob.load(path, database=...)` is also how you point a at a database that has moved, and `PipelineJob.load(path, result_database=...)` at a result 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. The file records each node's own Arrow types, so saving types +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. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 8ef064282..ba017d103 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1788,7 +1788,7 @@ def load( require_current_format, require_tag_only_columns, resolve_source_from_config, - saved_connector_type, + saved_connector_kind, ) path = _Path(path) @@ -1805,18 +1805,18 @@ def load( raise # A connector is supplied by the user, never rebuilt from the file (ITL-1391): - # refused before anything is rebuilt. Only the connector's kind is named; its - # saved connection may hold a credential. + # refused before anything is rebuilt. Nothing of the saved configuration is + # shown: it may hold a credential. missing: list[str] = [] for slot_name, given in ( ("database", database), ("result_database", result_database), ): - kind = saved_connector_type(data.get("bindings", {}).get(slot_name)) + 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()" + f"{slot_name}=ConnectorArrowDatabase()" ) if missing: raise ValueError( diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 07c0bfc9d..6ff99d4eb 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -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( @@ -453,19 +452,25 @@ def resolve_database_from_config( return cls.from_config(config) -def saved_connector_type(config: Any) -> str | None: +#: The kinds of connector a message may name: a saved kind outside this list is never +#: shown, since an odd file can hold a credential there. +_CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb") + + +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). Only the kind (``"sqlite"``) is read, never the - connection, which may hold a credential. + (developer, 2026-11-22, ITL-1391). Nothing of the saved text is returned: it may + hold a credential. Args: config: A saved database configuration, or ``None``. Returns: - The connector's kind (``"unknown"`` when the file does not say), or ``None`` - for a database that is not over a connector. + ``"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 @@ -475,10 +480,12 @@ def saved_connector_type(config: Any) -> str | None: if saved.get("type") != CONNECTOR_DATABASE_TYPE: return None connector = saved.get("connector") - if not isinstance(connector, dict): - return "unknown" - kind = cast("dict[str, Any]", connector).get("connector_type") - return kind if isinstance(kind, str) else "unknown" + 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: diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index 03951ee0e..b1ccfa7f0 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -10,6 +10,8 @@ import asyncio import json +import logging +import traceback from collections.abc import Iterator from pathlib import Path from typing import Any @@ -226,7 +228,85 @@ def test_any_given_database_is_used_whatever_connector_was_saved( assert PipelineJob.load(path, database=given).database is given -@pytest.mark.parametrize("connector", [None, {}, {"connector_type": 3}, "text"]) +@pytest.mark.parametrize("kind", KINDS) +def test_a_resave_writes_the_databases_actually_bound( + databases: Databases, tmp_path: Path, kind: str +) -> None: + """Databases given at load replace the recorded ones in a later save, in both slots.""" + path, again = tmp_path / "job.json", tmp_path / "again.json" + results = databases.make(kind, "b") + _save_over(path, databases, kind, result_database=results) + recorded = json.loads(path.read_text())["bindings"] + moved = databases.make("sqlite", "moved-a") + moved_results = databases.make(kind, "moved-b") + loaded = PipelineJob.load(path, database=moved, result_database=moved_results) + loaded.save(again) + bindings = json.loads(again.read_text())["bindings"] + assert bindings["database"] == moved.to_config() != recorded["database"] + assert bindings["result_database"] == moved_results.to_config() + assert bindings["result_database"] != recorded["result_database"] + + +SECRET = "postgresql://u:synthetic-credential@h/d" + + +def _secret_files(recorded: dict[str, Any], slot: str) -> Iterator[dict[str, Any]]: + """The saved bindings with ``SECRET`` put in each field of ``slot`` in turn.""" + for field in recorded[slot]: + for value in (SECRET, [SECRET], {SECRET: SECRET}): + changed = json.loads(json.dumps(recorded)) + changed[slot][field] = value + yield changed + for field in [*recorded[slot]["connector"], "another"]: + for value in (SECRET, [SECRET], {SECRET: SECRET}): + changed = json.loads(json.dumps(recorded)) + changed[slot]["connector"][field] = value + yield changed + + +@pytest.mark.parametrize("kind", KINDS) +@pytest.mark.parametrize("slot", ["database", "result_database"]) +@pytest.mark.filterwarnings("always") +def test_no_saved_text_is_shown_by_a_load( + databases: Databases, + tmp_path: Path, + kind: str, + slot: str, + caplog: pytest.LogCaptureFixture, + recwarn: pytest.WarningsRecorder, +) -> None: + """A credential in any field of a saved connector database reaches no exception (a + chained one included), log or warning, whether or not the other slot is given.""" + path = tmp_path / "job.json" + results = databases.make(kind, "b") + _save_over(path, databases, kind, result_database=results) + data = json.loads(path.read_text()) + given = { + "database": databases.make("sqlite", "a"), + "result_database": results, + } + del given[slot] + caplog.set_level(logging.DEBUG) + shown: list[str] = [] + for bindings in _secret_files(data["bindings"], slot): + path.write_text(json.dumps({**data, "bindings": bindings})) + for databases_given in ({}, given): + try: + PipelineJob.load(path, **databases_given) + except Exception as exc: + # The whole chain, causes and contexts included. + shown.append("".join(traceback.format_exception(exc))) + shown.append(repr(exc)) + assert shown + text = "\n".join([*shown, caplog.text, *(str(w.message) for w in recwarn)]) + assert "synthetic-credential" not in text + assert SECRET not in text + + +@pytest.mark.parametrize( + "connector", + [None, {}, {"connector_type": 3}, "text", {"connector_type": ["sqlite"]}], +) def test_a_connector_the_file_does_not_name_is_refused_too( databases: Databases, tmp_path: Path, connector: Any ) -> None: @@ -235,7 +315,7 @@ def test_a_connector_the_file_does_not_name_is_refused_too( data = json.loads(path.read_text()) data["bindings"]["database"]["connector"] = connector path.write_text(json.dumps(data)) - with pytest.raises(ValueError, match=r"connector database \(unknown\)"): + with pytest.raises(ValueError, match=r"\(unknown connector kind\)"): PipelineJob.load(path) From 9e0aff8b5f27cf96913ae9d80a4cdb3854ec6387 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:36:26 -0800 Subject: [PATCH 3/7] fix(pipeline): log only the slot, kind and error type of a database that cannot be rebuilt (ITL-1391) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1391.md | 3 + src/orcapod/pipeline/job.py | 14 ++-- src/orcapod/pipeline/serialization.py | 19 +++++ .../test_load_connector_database.py | 71 +++++++++++++++++++ 4 files changed, 103 insertions(+), 4 deletions(-) diff --git a/changelog.d/ITL-1391.md b/changelog.d/ITL-1391.md index b7d5ce463..491ec5462 100644 --- a/changelog.d/ITL-1391.md +++ b/changelog.d/ITL-1391.md @@ -10,3 +10,6 @@ - Saving a loaded job whose database could not be rebuilt writes the saved database configuration back as it was, instead of `null`. (ITL-1391) +- The warnings about a saved database or result database that could not be rebuilt name the + slot, the kind of database and the type of the error, never the error's text, which could + hold a saved path, URI or storage option and a credential in it. (ITL-1391) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ba017d103..460e680a9 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1789,6 +1789,7 @@ def load( require_tag_only_columns, resolve_source_from_config, saved_connector_kind, + saved_database_kind, ) path = _Path(path) @@ -1933,11 +1934,15 @@ def load( effective_database = resolve_database_from_config(store_config) except Exception as exc: unresolved_database = store_config + # The exception's text can hold a saved path, URI or option, and + # with it a credential: only its type is logged (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(). @@ -1974,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( diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 6ff99d4eb..b4d04d804 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -457,6 +457,25 @@ def resolve_database_from_config( _CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb") +def saved_database_kind(config: Any) -> str: + """The kind of a saved database configuration, for a message. + + Nothing of the saved text is returned: it may hold a credential. + + 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_connector_kind(config: Any) -> str | None: """The kind of connector a saved database configuration is over, or ``None``. diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index b1ccfa7f0..edcc658d2 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -13,6 +13,7 @@ import logging import traceback from collections.abc import Iterator +from contextlib import ExitStack from pathlib import Path from typing import Any from unittest.mock import MagicMock, patch @@ -303,6 +304,76 @@ def test_no_saved_text_is_shown_by_a_load( assert SECRET not in text +def _delta_changes(root: Path) -> dict[str, dict[str, Any]]: + """Delta configurations that fail to rebuild, with ``SECRET`` in what they hold.""" + blocked = root / "a-file" + blocked.write_text("not a directory") + return { + "a path that cannot be made": {"root_uri": f"{blocked}/{SECRET}"}, + "a URI that is not supported": {"root_uri": f"{SECRET}::x"}, + "a URI that is not text": {"root_uri": {SECRET: SECRET}}, + "options that are not a mapping": { + "root_uri": f"s3://bucket/{SECRET}", + "storage_options": SECRET, + }, + "options with a credential": { + "root_uri": f"{blocked}/x", + "storage_options": {"AWS_SECRET_ACCESS_KEY": SECRET, SECRET: SECRET}, + }, + "an unknown kind": {"type": SECRET}, + } + + +@pytest.mark.parametrize("slot", ["database", "result_database"]) +@pytest.mark.parametrize("fails", ["as the database does", "with the whole config"]) +def test_a_failed_delta_rebuild_logs_the_slot_kind_and_exception_type_only( + tmp_path: Path, + slot: str, + fails: str, + caplog: pytest.LogCaptureFixture, + recwarn: pytest.WarningsRecorder, +) -> None: + """Review of PR 540: the exception's text can hold a saved path, URI or option.""" + path = tmp_path / "job.json" + _save( + path, + database=DeltaTableDatabase(tmp_path / "delta"), + result_database=DeltaTableDatabase(tmp_path / "results"), + ) + data = json.loads(path.read_text()) + caplog.set_level(logging.DEBUG) + for name, change in _delta_changes(tmp_path).items(): + changed = json.loads(json.dumps(data)) + changed["bindings"][slot].update(change) + path.write_text(json.dumps(changed)) + caplog.clear() + + def refuse(config: dict[str, Any]) -> Any: + raise OSError(f"cannot open {config}") + + with ExitStack() as stack: + if fails == "with the whole config": + stack.enter_context( + patch.object(DeltaTableDatabase, "from_config", refuse) + ) + # The other slot is given, so only the changed one is rebuilt. + other = "result_database" if slot == "database" else "database" + given: dict[str, Any] = {other: DeltaTableDatabase(tmp_path / "given")} + shown = "" + try: + PipelineJob.load(path, **given) + except Exception as exc: + shown = "".join(traceback.format_exception(exc)) + text = "\n".join([shown, caplog.text, *(str(w.message) for w in recwarn)]) + assert "synthetic-credential" not in text, name + if fails == "with the whole config": + assert f"bindings.{slot}" in caplog.text + if name == "an unknown kind": + assert "(unknown database kind): ValueError." in caplog.text + else: + assert "(delta_table): OSError." in caplog.text + + @pytest.mark.parametrize( "connector", [None, {}, {"connector_type": 3}, "text", {"connector_type": ["sqlite"]}], From f592f7e3b150b7acd3f10f772087329c47fae70d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 11:22:50 -0800 Subject: [PATCH 4/7] fix(pipeline): the warning no longer holds the exception text (ITL-1391) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1391.md | 6 +- src/orcapod/pipeline/job.py | 14 +- src/orcapod/pipeline/serialization.py | 35 ++++- .../test_load_connector_database.py | 125 ++++++++++++++---- .../loaded_job/test_loaded_job_readback.py | 3 +- 5 files changed, 140 insertions(+), 43 deletions(-) diff --git a/changelog.d/ITL-1391.md b/changelog.d/ITL-1391.md index 491ec5462..3fec163dc 100644 --- a/changelog.d/ITL-1391.md +++ b/changelog.d/ITL-1391.md @@ -10,6 +10,6 @@ - Saving a loaded job whose database could not be rebuilt writes the saved database configuration back as it was, instead of `null`. (ITL-1391) -- The warnings about a saved database or result database that could not be rebuilt name the - slot, the kind of database and the type of the error, never the error's text, which could - hold a saved path, URI or storage option and a credential in it. (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) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 460e680a9..82f59257c 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1790,6 +1790,7 @@ def load( resolve_source_from_config, saved_connector_kind, saved_database_kind, + saved_source_kind, ) path = _Path(path) @@ -1807,7 +1808,7 @@ def load( # 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: it may hold a credential. + # shown. missing: list[str] = [] for slot_name, given in ( ("database", database), @@ -1850,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: @@ -1887,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: }).", spec_name, - source_type, + saved_source_kind(src_config), spec_name, spec_name, ) @@ -1903,8 +1903,9 @@ def load( "To read source node %r itself, bind a source: " "job.bind(sources={%r: }).", spec_name, - source_type, - exc, + saved_source_kind(src_config), + # Its type, never its text (ITL-1391). + type(exc).__name__, spec_name, spec_name, ) @@ -1934,8 +1935,7 @@ def load( effective_database = resolve_database_from_config(store_config) except Exception as exc: unresolved_database = store_config - # The exception's text can hold a saved path, URI or option, and - # with it a credential: only its type is logged (ITL-1391). + # The exception's type, never its text (ITL-1391). logger.warning( "Could not reconstruct the database from its saved config: " "bindings.database (%s): %s. " diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index b4d04d804..ffb9228f3 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -452,15 +452,12 @@ def resolve_database_from_config( return cls.from_config(config) -#: The kinds of connector a message may name: a saved kind outside this list is never -#: shown, since an odd file can hold a credential there. +#: 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. - - Nothing of the saved text is returned: it may hold a credential. + """The kind of a saved database configuration, for a message: never the saved text. Args: config: A saved database configuration. @@ -476,12 +473,36 @@ def saved_database_kind(config: Any) -> str: 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). Nothing of the saved text is returned: it may - hold a credential. + (developer, 2026-11-22, ITL-1391). Never the saved text. Args: config: A saved database configuration, or ``None``. diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index edcc658d2..2345bf8f1 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -29,14 +29,14 @@ SpiralDBConnector, SQLiteConnector, ) +from orcapod.pipeline.serialization import SOURCE_REGISTRY from orcapod.sources import ArrowTableSource from tests.test_databases import fake_pyspiral KINDS = ("sqlite", "postgresql", "spiraldb") # The kinds an operator-only job runs on. RUNNABLE = ("sqlite", "spiraldb") -# Not a real credential. -PASSWORD = "synthetic-pass-word" +MARKER = "marker-in-dsn" class Databases: @@ -52,7 +52,7 @@ def make(self, kind: str, name: str) -> ConnectorArrowDatabase: ) if kind == "postgresql": return ConnectorArrowDatabase( - PostgreSQLConnector(f"postgresql://u:{PASSWORD}@h/{name}") + PostgreSQLConnector(f"postgresql://u:{MARKER}@h/{name}") ) fake_pyspiral.FakeSpiral().project(name) return ConnectorArrowDatabase(SpiralDBConnector(name)) @@ -134,7 +134,7 @@ def test_load_without_the_database_names_the_slot_and_what_to_pass( assert "result_database" not in message assert "Unknown database type" not in message # The saved connection is never shown. - assert PASSWORD not in message + assert MARKER not in message @pytest.mark.parametrize("kind", KINDS) @@ -158,7 +158,7 @@ def test_every_missing_slot_is_named( PipelineJob.load(path, **given) for slot, text in wanted.items(): assert (text in str(refused.value)) is (slot not in given) - assert PASSWORD not in str(refused.value) + assert MARKER not in str(refused.value) loaded = PipelineJob.load(path, result_database=results, database=database) assert loaded.database is database assert loaded.result_database is results @@ -248,18 +248,18 @@ def test_a_resave_writes_the_databases_actually_bound( assert bindings["result_database"] != recorded["result_database"] -SECRET = "postgresql://u:synthetic-credential@h/d" +TEXT = "marker-text://x" -def _secret_files(recorded: dict[str, Any], slot: str) -> Iterator[dict[str, Any]]: - """The saved bindings with ``SECRET`` put in each field of ``slot`` in turn.""" +def _marked_files(recorded: dict[str, Any], slot: str) -> Iterator[dict[str, Any]]: + """The saved bindings with ``TEXT`` put in each field of ``slot`` in turn.""" for field in recorded[slot]: - for value in (SECRET, [SECRET], {SECRET: SECRET}): + for value in (TEXT, [TEXT], {TEXT: TEXT}): changed = json.loads(json.dumps(recorded)) changed[slot][field] = value yield changed for field in [*recorded[slot]["connector"], "another"]: - for value in (SECRET, [SECRET], {SECRET: SECRET}): + for value in (TEXT, [TEXT], {TEXT: TEXT}): changed = json.loads(json.dumps(recorded)) changed[slot]["connector"][field] = value yield changed @@ -276,7 +276,7 @@ def test_no_saved_text_is_shown_by_a_load( caplog: pytest.LogCaptureFixture, recwarn: pytest.WarningsRecorder, ) -> None: - """A credential in any field of a saved connector database reaches no exception (a + """Text in any field of a saved connector database reaches no exception (a chained one included), log or warning, whether or not the other slot is given.""" path = tmp_path / "job.json" results = databases.make(kind, "b") @@ -289,7 +289,7 @@ def test_no_saved_text_is_shown_by_a_load( del given[slot] caplog.set_level(logging.DEBUG) shown: list[str] = [] - for bindings in _secret_files(data["bindings"], slot): + for bindings in _marked_files(data["bindings"], slot): path.write_text(json.dumps({**data, "bindings": bindings})) for databases_given in ({}, given): try: @@ -300,27 +300,27 @@ def test_no_saved_text_is_shown_by_a_load( shown.append(repr(exc)) assert shown text = "\n".join([*shown, caplog.text, *(str(w.message) for w in recwarn)]) - assert "synthetic-credential" not in text - assert SECRET not in text + assert "marker-text" not in text + assert TEXT not in text def _delta_changes(root: Path) -> dict[str, dict[str, Any]]: - """Delta configurations that fail to rebuild, with ``SECRET`` in what they hold.""" + """Delta configurations that fail to rebuild, with ``TEXT`` in what they hold.""" blocked = root / "a-file" blocked.write_text("not a directory") return { - "a path that cannot be made": {"root_uri": f"{blocked}/{SECRET}"}, - "a URI that is not supported": {"root_uri": f"{SECRET}::x"}, - "a URI that is not text": {"root_uri": {SECRET: SECRET}}, + "a path that cannot be made": {"root_uri": f"{blocked}/{TEXT}"}, + "a URI that is not supported": {"root_uri": f"{TEXT}::x"}, + "a URI that is not text": {"root_uri": {TEXT: TEXT}}, "options that are not a mapping": { - "root_uri": f"s3://bucket/{SECRET}", - "storage_options": SECRET, + "root_uri": f"s3://bucket/{TEXT}", + "storage_options": TEXT, }, - "options with a credential": { + "options of a file": { "root_uri": f"{blocked}/x", - "storage_options": {"AWS_SECRET_ACCESS_KEY": SECRET, SECRET: SECRET}, + "storage_options": {"AWS_REGION": TEXT, TEXT: TEXT}, }, - "an unknown kind": {"type": SECRET}, + "an unknown kind": {"type": TEXT}, } @@ -333,7 +333,7 @@ def test_a_failed_delta_rebuild_logs_the_slot_kind_and_exception_type_only( caplog: pytest.LogCaptureFixture, recwarn: pytest.WarningsRecorder, ) -> None: - """Review of PR 540: the exception's text can hold a saved path, URI or option.""" + """Review of PR 540: the warning no longer holds the exception text.""" path = tmp_path / "job.json" _save( path, @@ -365,7 +365,7 @@ def refuse(config: dict[str, Any]) -> Any: except Exception as exc: shown = "".join(traceback.format_exception(exc)) text = "\n".join([shown, caplog.text, *(str(w.message) for w in recwarn)]) - assert "synthetic-credential" not in text, name + assert "marker-text" not in text, name if fails == "with the whole config": assert f"bindings.{slot}" in caplog.text if name == "an unknown kind": @@ -414,3 +414,78 @@ def test_saving_a_loaded_job_keeps_a_database_that_could_not_be_rebuilt( loaded.bind(database=given) loaded.save(again) assert json.loads(again.read_text())["bindings"]["database"] == given.to_config() + + +SAVED_SOURCE_KINDS = (*sorted(SOURCE_REGISTRY), "db_table", "polling_source", TEXT) + + +def _raise_chained(config: dict[str, Any], **_: Any) -> Any: + """A rebuild that fails with ``TEXT`` in the error, its cause and its context.""" + try: + try: + raise KeyError(f"first {TEXT}") + except KeyError: + raise OSError(f"second {TEXT}") + except OSError as exc: + raise RuntimeError(f"third {TEXT} {config}") from exc + + +@pytest.mark.parametrize("kind", SAVED_SOURCE_KINDS) +@pytest.mark.parametrize("slots", [["left"], ["right", "left"]]) +def test_a_source_that_cannot_be_rebuilt_logs_the_slot_kind_and_error_type_only( + tmp_path: Path, + kind: str, + slots: list[str], + caplog: pytest.LogCaptureFixture, + recwarn: pytest.WarningsRecorder, +) -> None: + """The warning no longer holds the exception text, for every source kind.""" + path = tmp_path / "job.json" + _save(path, database=DeltaTableDatabase(tmp_path / "delta")) + data = json.loads(path.read_text()) + for slot in slots: + data["bindings"]["sources"][slot].update(source_type=kind, entry=TEXT) + path.write_text(json.dumps(data)) + caplog.set_level(logging.DEBUG) + with ExitStack() as stack: + if kind in SOURCE_REGISTRY: + stack.enter_context( + patch.object(SOURCE_REGISTRY[kind], "from_config", _raise_chained) + ) + loaded = PipelineJob.load(path) + assert set(slots) <= set(loaded.unbound_sources) + for slot in slots: + shown = "unknown source kind" if kind == TEXT else kind + error = "RuntimeError" if kind in SOURCE_REGISTRY else "ValueError" + records = [ + r + for r in caplog.records + if r.getMessage().startswith( + f"Could not reconstruct source {slot!r} ({shown}) from its saved " + f"config: {error}. " + ) + ] + assert len(records) == 1 + assert records[0].levelno == logging.WARNING + assert records[0].exc_info is None + text = "\n".join([caplog.text, *(str(w.message) for w in recwarn)]) + assert "marker-text" not in text + + +@pytest.mark.parametrize("value", [TEXT, [TEXT], {TEXT: TEXT}]) +def test_a_source_kind_of_a_file_is_never_shown( + tmp_path: Path, value: Any, caplog: pytest.LogCaptureFixture +) -> None: + path = tmp_path / "job.json" + _save(path, database=DeltaTableDatabase(tmp_path / "delta")) + data = json.loads(path.read_text()) + data["bindings"]["sources"]["left"]["source_type"] = value + path.write_text(json.dumps(data)) + caplog.set_level(logging.DEBUG) + shown = "" + try: + PipelineJob.load(path) + except Exception as exc: + # A kind that is not text is refused by the file's own checks. + shown = "".join(traceback.format_exception(exc)) + assert "marker-text" not in shown + caplog.text diff --git a/tests/test_pipeline/loaded_job/test_loaded_job_readback.py b/tests/test_pipeline/loaded_job/test_loaded_job_readback.py index 765488705..fffb0b5e9 100644 --- a/tests/test_pipeline/loaded_job/test_loaded_job_readback.py +++ b/tests/test_pipeline/loaded_job/test_loaded_job_readback.py @@ -930,7 +930,8 @@ def move_csv(data: dict[str, Any]) -> None: assert warnings[0].startswith( "Could not reconstruct source 'csrc' (csv) from its saved config: " ) - assert "gone.csv" in warnings[0] + # The type of the error, never its text (ITL-1391). + assert "gone.csv" not in warnings[0] assert warnings[0].endswith( "Stored function-node results are still readable from the database. To read " "source node 'csrc' itself, bind a source: job.bind(sources={'csrc': })." From aa549ec60c0cdd6e118383c09de5a469c619585e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 11:45:11 -0800 Subject: [PATCH 5/7] test(pipeline): the warning no longer holds the exception text (ITL-1391) Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_bind_narrower_source.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_pipeline/test_bind_narrower_source.py b/tests/test_pipeline/test_bind_narrower_source.py index 2c79be9e2..345f9b7d1 100644 --- a/tests/test_pipeline/test_bind_narrower_source.py +++ b/tests/test_pipeline/test_bind_narrower_source.py @@ -396,7 +396,7 @@ def test_loaded_csv_of_another_type_is_left_unbound( with caplog.at_level(logging.WARNING): job = PipelineJob.load(path) assert any( - "'csv'" in r.getMessage() and "declared int" in r.getMessage() + "'csv' (csv)" in r.getMessage() and "SourceSpecMismatchError" in r.getMessage() for r in caplog.records ) assert job.unbound_sources == ["csv"] From 1401ae813ab976a08383a92751fa8dc413b393f7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:25:59 -0800 Subject: [PATCH 6/7] test(pipeline): cover connector load review cases --- changelog.d/ITL-1391.md | 6 +- .../test_load_connector_database.py | 104 ++++++++++++------ 2 files changed, 75 insertions(+), 35 deletions(-) diff --git a/changelog.d/ITL-1391.md b/changelog.d/ITL-1391.md index 3fec163dc..9497a69a0 100644 --- a/changelog.d/ITL-1391.md +++ b/changelog.d/ITL-1391.md @@ -8,8 +8,10 @@ ### Fixed -- Saving a loaded job whose database could not be rebuilt writes the saved database - configuration back as it was, instead of `null`. (ITL-1391) +- 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) diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index 2345bf8f1..2f25b699a 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -1,9 +1,9 @@ """A saved connector database is supplied at load, never rebuilt (ITL-1391). The connectors cannot hold a function node's tables (entry CA3, ITL-1162), so the jobs -here hold operators only. PostgreSQL cannot hold an operator node's tables either (a -table name is cut at 63 bytes), so a file naming it as the job's database is made by -putting its configuration into a saved file; as a result database it is saved directly. +here hold operators only. SQLite can store their tables. For PostgreSQL, which limits +table names to 63 bytes, and read-only SpiralDB, the test inserts the connector's +configuration into a saved file. All three can be saved directly as a result database. """ from __future__ import annotations @@ -31,11 +31,9 @@ ) from orcapod.pipeline.serialization import SOURCE_REGISTRY from orcapod.sources import ArrowTableSource -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk KINDS = ("sqlite", "postgresql", "spiraldb") -# The kinds an operator-only job runs on. -RUNNABLE = ("sqlite", "spiraldb") MARKER = "marker-in-dsn" @@ -54,42 +52,54 @@ def make(self, kind: str, name: str) -> ConnectorArrowDatabase: return ConnectorArrowDatabase( PostgreSQLConnector(f"postgresql://u:{MARKER}@h/{name}") ) - fake_pyspiral.FakeSpiral().project(name) return ConnectorArrowDatabase(SpiralDBConnector(name)) @pytest.fixture def databases(tmp_path: Path) -> Iterator[Databases]: with ( - fake_pyspiral.install(tmp_path / "spiral"), + fake_spiral_sdk.install(tmp_path / "spiral"), patch("psycopg.connect") as connect, ): connect.return_value = MagicMock() yield Databases(tmp_path) -def _sources() -> dict[str, Any]: +def _sources( + order: tuple[str, str] = ("left", "right"), *, data_tags: bool = False +) -> dict[str, Any]: left = pa.table( {"a": [1, 2, 3], "b": ["x", "y", "z"], "p": [1.0, 2.0, 3.0], "q": [4, 5, 6]} ) right = pa.table({"b": ["z", "x"], "a": [3, 1], "r": [30, 10], "s": ["u", "v"]}) + tables = {"left": left, "right": right} return { name: ArrowTableSource( - table, tag_columns=["a", "b"], source_id=name, tag_only_columns=True + tables[name], + tag_columns=["a", "b"], + source_id=name, + tag_only_columns=() if data_tags else True, ) - for name, table in (("left", left), ("right", right)) + for name in order } def _save( - path: Path, *, run_async: bool = False, **databases: Any + path: Path, + *, + run_async: bool = False, + input_order: tuple[str, str] = ("left", "right"), + selected: tuple[str, str] = ("s", "p"), + data_tags: bool = False, + **databases: Any, ) -> tuple[PipelineJob, dict[str, Any]]: """An operator-only job, run and saved, and its file's bindings.""" - sources = _sources() + sources = _sources(data_tags=data_tags) + first, second = input_order job = PipelineJob(name="j", **databases) with job: - joined = sources["left"].join(sources["right"], label="joined") - joined.select_data_columns(["s", "p"], label="picked") + joined = sources[first].join(sources[second], label="joined") + joined.select_data_columns(selected, label="picked") if run_async: asyncio.run(job.run_async()) else: @@ -100,7 +110,7 @@ def _save( def _save_over(path: Path, databases: Databases, kind: str, **given: Any) -> None: """A saved job file whose database is of ``kind`` (see the module docstring).""" - if kind in RUNNABLE: + if kind == "sqlite": _save(path, database=databases.make(kind, "a"), **given) return _save(path, database=databases.make("sqlite", "a"), **given) @@ -181,26 +191,39 @@ def test_a_connector_result_database_beside_a_delta_database( assert isinstance(loaded.database, DeltaTableDatabase) -@pytest.mark.parametrize("kind", RUNNABLE) @pytest.mark.parametrize("saved_async", [False, True]) @pytest.mark.parametrize("loaded_async", [False, True]) +@pytest.mark.parametrize("bind_order", [("left", "right"), ("right", "left")]) +@pytest.mark.parametrize( + ("input_order", "selected"), + [(("left", "right"), ("s", "p")), (("right", "left"), ("p", "s"))], +) +@pytest.mark.parametrize("data_tags", [False, True]) def test_load_with_the_database_then_load_only( databases: Databases, tmp_path: Path, - kind: str, saved_async: bool, loaded_async: bool, + bind_order: tuple[str, str], + input_order: tuple[str, str], + selected: tuple[str, str], + data_tags: bool, ) -> None: path = tmp_path / "job.json" job, bindings = _save( - path, run_async=saved_async, database=databases.make(kind, "a") + path, + run_async=saved_async, + input_order=input_order, + selected=selected, + data_tags=data_tags, + database=databases.make("sqlite", "a"), ) assert _values(job) == EXPECTED hashes = {label: n.content_hash().to_string() for label, n in job.nodes.items()} # A new handle over the same place, as another process would make. - loaded = PipelineJob.load(path, database=databases.make(kind, "a")) - loaded.bind(sources=_sources()) + loaded = PipelineJob.load(path, database=databases.make("sqlite", "a")) + loaded.bind(sources=_sources(bind_order, data_tags=data_tags)) assert { label: n.content_hash().to_string() for label, n in loaded.nodes.items() } == hashes @@ -209,6 +232,11 @@ def test_load_with_the_database_then_load_only( else: loaded.run(load_only=True) assert _values(loaded) == EXPECTED + assert loaded.nodes["picked"].as_table().column_names == ( + job.nodes["picked"].as_table().column_names + ) + _, joined_data = loaded.nodes["joined"].output_schema() + assert {"a", "b"}.issubset(joined_data) is data_tags again = tmp_path / "again.json" loaded.save(again) @@ -390,30 +418,38 @@ def test_a_connector_the_file_does_not_name_is_refused_too( PipelineJob.load(path) +@pytest.mark.parametrize("slot", ["database", "result_database"]) def test_saving_a_loaded_job_keeps_a_database_that_could_not_be_rebuilt( - tmp_path: Path, + tmp_path: Path, slot: str ) -> None: path, again = tmp_path / "job.json", tmp_path / "again.json" _save(path, database=DeltaTableDatabase(tmp_path / "delta")) data = json.loads(path.read_text()) saved = {"type": "no_such_database", "place": ["x", "y"]} - data["bindings"]["database"] = saved + data["bindings"][slot] = saved path.write_text(json.dumps(data)) loaded = PipelineJob.load(path) - assert loaded.database is None + assert getattr(loaded, slot) is None loaded.save(again) - assert json.loads(again.read_text())["bindings"]["database"] == saved + assert json.loads(again.read_text())["bindings"][slot] == saved - # A bind of sources or a result database leaves it; a bound database replaces it. + # Rebinding sources or the other database leaves this slot untouched. loaded.bind(sources=_sources()) - loaded.bind(result_database=DeltaTableDatabase(tmp_path / "results")) + other_database = DeltaTableDatabase(tmp_path / "other") + if slot == "database": + loaded.bind(result_database=other_database) + else: + loaded.bind(database=other_database) loaded.save(again) - assert json.loads(again.read_text())["bindings"]["database"] == saved + assert json.loads(again.read_text())["bindings"][slot] == saved given = DeltaTableDatabase(tmp_path / "given") - loaded.bind(database=given) + if slot == "database": + loaded.bind(database=given) + else: + loaded.bind(result_database=given) loaded.save(again) - assert json.loads(again.read_text())["bindings"]["database"] == given.to_config() + assert json.loads(again.read_text())["bindings"][slot] == given.to_config() SAVED_SOURCE_KINDS = (*sorted(SOURCE_REGISTRY), "db_table", "polling_source", TEXT) @@ -431,7 +467,7 @@ def _raise_chained(config: dict[str, Any], **_: Any) -> Any: @pytest.mark.parametrize("kind", SAVED_SOURCE_KINDS) -@pytest.mark.parametrize("slots", [["left"], ["right", "left"]]) +@pytest.mark.parametrize("slots", [["left"], ["left", "right"], ["right", "left"]]) def test_a_source_that_cannot_be_rebuilt_logs_the_slot_kind_and_error_type_only( tmp_path: Path, kind: str, @@ -443,8 +479,10 @@ def test_a_source_that_cannot_be_rebuilt_logs_the_slot_kind_and_error_type_only( path = tmp_path / "job.json" _save(path, database=DeltaTableDatabase(tmp_path / "delta")) data = json.loads(path.read_text()) - for slot in slots: - data["bindings"]["sources"][slot].update(source_type=kind, entry=TEXT) + sources = data["bindings"]["sources"] + data["bindings"]["sources"] = { + slot: {**sources[slot], "source_type": kind, "entry": TEXT} for slot in slots + } | {slot: value for slot, value in sources.items() if slot not in slots} path.write_text(json.dumps(data)) caplog.set_level(logging.DEBUG) with ExitStack() as stack: From bf23b198dcafaf24ae6b8e2455abc2dc26f52892 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:53:21 -0800 Subject: [PATCH 7/7] test(pipeline): vary declared tag order on connector load --- .../test_load_connector_database.py | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index 2f25b699a..d1c9e4e08 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -66,7 +66,10 @@ def databases(tmp_path: Path) -> Iterator[Databases]: def _sources( - order: tuple[str, str] = ("left", "right"), *, data_tags: bool = False + order: tuple[str, str] = ("left", "right"), + *, + tag_order: tuple[str, str] = ("a", "b"), + data_tags: bool = False, ) -> dict[str, Any]: left = pa.table( {"a": [1, 2, 3], "b": ["x", "y", "z"], "p": [1.0, 2.0, 3.0], "q": [4, 5, 6]} @@ -76,7 +79,7 @@ def _sources( return { name: ArrowTableSource( tables[name], - tag_columns=["a", "b"], + tag_columns=list(tag_order), source_id=name, tag_only_columns=() if data_tags else True, ) @@ -90,11 +93,12 @@ def _save( run_async: bool = False, input_order: tuple[str, str] = ("left", "right"), selected: tuple[str, str] = ("s", "p"), + tag_order: tuple[str, str] = ("a", "b"), data_tags: bool = False, **databases: Any, ) -> tuple[PipelineJob, dict[str, Any]]: """An operator-only job, run and saved, and its file's bindings.""" - sources = _sources(data_tags=data_tags) + sources = _sources(tag_order=tag_order, data_tags=data_tags) first, second = input_order job = PipelineJob(name="j", **databases) with job: @@ -199,6 +203,7 @@ def test_a_connector_result_database_beside_a_delta_database( [(("left", "right"), ("s", "p")), (("right", "left"), ("p", "s"))], ) @pytest.mark.parametrize("data_tags", [False, True]) +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")]) def test_load_with_the_database_then_load_only( databases: Databases, tmp_path: Path, @@ -208,6 +213,7 @@ def test_load_with_the_database_then_load_only( input_order: tuple[str, str], selected: tuple[str, str], data_tags: bool, + tag_order: tuple[str, str], ) -> None: path = tmp_path / "job.json" job, bindings = _save( @@ -215,17 +221,30 @@ def test_load_with_the_database_then_load_only( run_async=saved_async, input_order=input_order, selected=selected, + tag_order=tag_order, data_tags=data_tags, database=databases.make("sqlite", "a"), ) assert _values(job) == EXPECTED - hashes = {label: n.content_hash().to_string() for label, n in job.nodes.items()} + assert { + name: config["tag_columns"] for name, config in bindings["sources"].items() + } == {"left": list(tag_order), "right": list(tag_order)} + hashes = { + label: (node.pipeline_hash(), node.content_hash()) + for label, node in job.nodes.items() + } # A new handle over the same place, as another process would make. loaded = PipelineJob.load(path, database=databases.make("sqlite", "a")) - loaded.bind(sources=_sources(bind_order, data_tags=data_tags)) + first_tag, second_tag = tag_order + loaded.bind( + sources=_sources( + bind_order, tag_order=(second_tag, first_tag), data_tags=data_tags + ) + ) assert { - label: n.content_hash().to_string() for label, n in loaded.nodes.items() + label: (node.pipeline_hash(), node.content_hash()) + for label, node in loaded.nodes.items() } == hashes if loaded_async: asyncio.run(loaded.run_async(load_only=True))