diff --git a/changelog.d/ITL-1391.md b/changelog.d/ITL-1391.md new file mode 100644 index 000000000..9497a69a0 --- /dev/null +++ b/changelog.d/ITL-1391.md @@ -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) 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 41a19df1b..a7689bd34 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -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. 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..82f59257c 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,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) @@ -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()" + ) + 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 @@ -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: @@ -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: }).", spec_name, - source_type, + saved_source_kind(src_config), spec_name, spec_name, ) @@ -1870,14 +1903,16 @@ 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, ) # 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,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(). @@ -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( @@ -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. diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index abbebf83d..ffb9228f3 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,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. 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..d1c9e4e08 --- /dev/null +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -0,0 +1,548 @@ +"""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. 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 + +import asyncio +import json +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 + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + PostgreSQLConnector, + SpiralDBConnector, + SQLiteConnector, +) +from orcapod.pipeline.serialization import SOURCE_REGISTRY +from orcapod.sources import ArrowTableSource +from tests.test_databases import fake_spiral_sdk + +KINDS = ("sqlite", "postgresql", "spiraldb") +MARKER = "marker-in-dsn" + + +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:{MARKER}@h/{name}") + ) + return ConnectorArrowDatabase(SpiralDBConnector(name)) + + +@pytest.fixture +def databases(tmp_path: Path) -> Iterator[Databases]: + with ( + fake_spiral_sdk.install(tmp_path / "spiral"), + patch("psycopg.connect") as connect, + ): + connect.return_value = MagicMock() + yield Databases(tmp_path) + + +def _sources( + 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]} + ) + right = pa.table({"b": ["z", "x"], "a": [3, 1], "r": [30, 10], "s": ["u", "v"]}) + tables = {"left": left, "right": right} + return { + name: ArrowTableSource( + tables[name], + tag_columns=list(tag_order), + source_id=name, + tag_only_columns=() if data_tags else True, + ) + for name in order + } + + +def _save( + path: Path, + *, + 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(tag_order=tag_order, data_tags=data_tags) + first, second = input_order + job = PipelineJob(name="j", **databases) + with job: + joined = sources[first].join(sources[second], label="joined") + joined.select_data_columns(selected, 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 == "sqlite": + _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 MARKER 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 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 + + +@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("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]) +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")]) +def test_load_with_the_database_then_load_only( + databases: Databases, + tmp_path: Path, + saved_async: bool, + loaded_async: bool, + bind_order: tuple[str, str], + 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( + path, + 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 + 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")) + first_tag, second_tag = tag_order + loaded.bind( + sources=_sources( + bind_order, tag_order=(second_tag, first_tag), data_tags=data_tags + ) + ) + assert { + 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)) + 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) + 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("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"] + + +TEXT = "marker-text://x" + + +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 (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 (TEXT, [TEXT], {TEXT: TEXT}): + 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: + """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") + _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 _marked_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 "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 ``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}/{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/{TEXT}", + "storage_options": TEXT, + }, + "options of a file": { + "root_uri": f"{blocked}/x", + "storage_options": {"AWS_REGION": TEXT, TEXT: TEXT}, + }, + "an unknown kind": {"type": TEXT}, + } + + +@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 warning no longer holds the exception text.""" + 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 "marker-text" 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"]}], +) +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"\(unknown connector kind\)"): + 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, 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"][slot] = saved + path.write_text(json.dumps(data)) + + loaded = PipelineJob.load(path) + assert getattr(loaded, slot) is None + loaded.save(again) + assert json.loads(again.read_text())["bindings"][slot] == saved + + # Rebinding sources or the other database leaves this slot untouched. + loaded.bind(sources=_sources()) + 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"][slot] == saved + given = DeltaTableDatabase(tmp_path / "given") + if slot == "database": + loaded.bind(database=given) + else: + loaded.bind(result_database=given) + loaded.save(again) + assert json.loads(again.read_text())["bindings"][slot] == 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"], ["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, + 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()) + 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: + 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': })." 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"]