diff --git a/changelog.d/ITL-1980.md b/changelog.d/ITL-1980.md new file mode 100644 index 000000000..11f6a6794 --- /dev/null +++ b/changelog.d/ITL-1980.md @@ -0,0 +1,6 @@ +### Fixed + +- Keyed SpiralDB create and append operations now raise + `SpiralDBWritePermissionError` when the store responds with an opaque 404. The + error reports that write access to the database is likely missing and preserves + the original store error as its cause. diff --git a/docs/api/errors.md b/docs/api/errors.md index 6f519beb4..46491ca50 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -132,6 +132,8 @@ These exceptions and warnings report storage, schema, and connector problems. ::: orcapod.errors.NullabilityRecordMismatchError +::: orcapod.errors.SpiralDBWritePermissionError + ::: orcapod.errors.SpiralDBWriteNotSupportedError ::: orcapod.errors.SpiralDBObserverNotSupportedError diff --git a/src/orcapod/databases/spiraldb_keyed/tables.py b/src/orcapod/databases/spiraldb_keyed/tables.py index df0bba74c..d56be569a 100644 --- a/src/orcapod/databases/spiraldb_keyed/tables.py +++ b/src/orcapod/databases/spiraldb_keyed/tables.py @@ -61,7 +61,7 @@ import orcapod.databases.spiraldb_keyed.identity as identity from orcapod.databases.spiraldb_keyed.identity import SpiralTableCollisionError from orcapod.databases.store_table_names import require_store_path_domain -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, SpiralDBWritePermissionError from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, @@ -79,6 +79,14 @@ logger = logging.getLogger(__name__) +def _sdk_error_message(error: BaseException) -> str | None: + """Read a message for classification without masking the SDK error.""" + try: + return str(error) + except Exception: # noqa: BLE001 # an unprintable error cannot be classified + return None + + @dataclass class _Catalog: """One run's view of a dataset, updated as the run creates and writes tables. @@ -1272,6 +1280,23 @@ def _acquire_lock(self) -> None: assert state is not None # ``write`` runs in a scope state.acquire_lock() + @contextmanager + def _write_call(self, doing: str) -> Iterator[None]: + """Translate the SDK's opaque 404 response to a keyed create or append.""" + try: + with self._service_call(doing): + yield + except self._sdk.SpiralError as err: # pyright: ignore[reportAny] + opaque_404 = "remote service returned an unknown error (status 404)" + if _sdk_error_message(err) not in ( # pyright: ignore[reportAny] + opaque_404, + f"Scandal:Internal (message: {opaque_404})", + ): + raise + raise SpiralDBWritePermissionError( + "The store refused the write (status 404); likely no write access to the database." + ) from err + def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: """The table at a computed name, created now if absent. @@ -1294,10 +1319,10 @@ def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: return table, False key = pa.schema([pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False)]) try: - with self._service_call(f"create {table_name}"): + with self._write_call(f"create {table_name}"): created = self._create_table(table_name, key) except self._sdk.SpiralError as exc: # pyright: ignore[reportAny] - if "status 409" not in str(exc): # pyright: ignore[reportAny] + if "status 409" not in (_sdk_error_message(exc) or ""): # pyright: ignore[reportAny] raise # Made meanwhile: the caller compares it with what it judged. else: @@ -1590,7 +1615,7 @@ def _append( _ = run.rows_by_table.pop(found.table_id, None) run.commits += 1 # odd while the append is in flight try: - with self._service_call("write a database table"): + with self._write_call("write a database table"): _ = table.append(batch) except BaseException: # The service may hold the rows, some, or none: judged again next call. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 9edd5f6c2..673e83e18 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -739,6 +739,10 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: super().__init__(_in_table(f"table schema: {reason}", table)) +class SpiralDBWritePermissionError(PermissionError): + """SpiralDB refused a keyed create or append, suggesting missing write access.""" + + class SpiralDBWriteNotSupportedError(NotImplementedError): """A plain SpiralDB connector was asked to write: it only reads (ITL-1186). diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 4ecc4fbc1..93089d357 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -15,6 +15,7 @@ from orcapod.contexts import get_default_context_key from orcapod.contexts.stored import keep_rows_of_data_context, with_data_context from orcapod.databases._pending_commits import PendingCommit, observe_records +from orcapod.errors import SpiralDBWritePermissionError from orcapod.hashing.labelled_hash import canonical_json from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.source_only_job import SourceOnlyPipelineJob @@ -196,6 +197,8 @@ def publish( Raises: PipelinePublicationConflictError: If another writer stored a different job at the chosen version. + SpiralDBWritePermissionError: If SpiralDB refuses the write with a + response that suggests missing write access. ValueError: If the name is empty, the database discards records, or the job cannot be saved. """ @@ -311,6 +314,11 @@ def record_acceptance( self._database.refresh_table(_TABLE_PATH) rows = self._publication_rows(publication.name, publication.version) except Exception as read_error: + if isinstance(flush_error, SpiralDBWritePermissionError): + flush_error.add_note( + f"Publication readback also failed ({type(read_error).__name__})." + ) + raise flush_error if flush_error is not None: raise flush_error from read_error raise diff --git a/tests/test_databases/test_spiraldb_keyed_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py index cbc84bf23..aed25ecb6 100644 --- a/tests/test_databases/test_spiraldb_keyed_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -6,6 +6,9 @@ set, a missing sign-in fails the tests rather than skipping them. ``SPIRAL_SERVER_URL`` names another address. +The viewer-only check also needs ``SPIRAL_VIEWER_CLIENT_ID`` and +``SPIRAL_VIEWER_KEY_FILE`` for a workload with viewer access to the test project. + Spiral SDK cannot drop keyed tables. The reading cases seed a fixed set of tables once and reuse their snapshots to avoid overlapping fragments on each run. Advance the default dataset version when the seed data changes. Use ``ORCAPOD_SPIRAL_CONFORMANCE_DATASET`` @@ -35,10 +38,16 @@ import pyarrow.compute as pc import pytest -from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector +from orcapod import PipelineRepository +from orcapod.databases import ( + ConnectorArrowDatabase, + InMemoryArrowDatabase, + SpiralDBKeyedConnector, +) from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.databases.spiraldb_keyed.connector import SpiralDBTableNotFoundError +from orcapod.errors import SpiralDBWritePermissionError from orcapod.sources import SpiralDBTableSource from orcapod.types import Condition, col from orcapod.utils.arrow_utils import normalize_to_large_types @@ -46,6 +55,7 @@ assert_discovery_without_function_module, ) from tests.test_databases import fake_spiral_sdk as fake +from tests.test_pipeline.test_pipeline_repository import _run_job _LIVE = os.environ.get("SPIRAL_INTEGRATION_TESTS") == "1" _PROJECT = os.environ.get("SPIRAL_PROJECT_ID", "") @@ -97,6 +107,38 @@ def open_database() -> ConnectorArrowDatabase: ) +@pytest.mark.skipif( + not (_LIVE and _PROJECT), + reason="Set SPIRAL_INTEGRATION_TESTS=1 and SPIRAL_PROJECT_ID", +) +def test_live_viewer_cannot_publish(monkeypatch: pytest.MonkeyPatch) -> None: + """Exercise the store's refusal to create a publication table as a viewer.""" + viewer = os.environ.get("SPIRAL_VIEWER_CLIENT_ID") + key_file = os.environ.get("SPIRAL_VIEWER_KEY_FILE") + if not viewer or not key_file or not Path(key_file).is_file(): + pytest.skip("Set SPIRAL_VIEWER_CLIENT_ID and SPIRAL_VIEWER_KEY_FILE") + monkeypatch.setenv("SPIRAL_CLIENT_ID", viewer) + monkeypatch.setenv("SPIRAL_PRIVATE_KEY", Path(key_file).read_text()) + dataset = f"{_DISCOVERY_DATASET}_{uuid.uuid4().hex}" + overrides = {"server.url": _URL} + with ( + SpiralDBKeyedConnector( + _PROJECT, dataset, overrides, writable=True + ) as connector, + SpiralDBKeyedConnector(_PROJECT, dataset, overrides) as reader, + ): + assert connector.get_publisher_identity() == f"workload:{viewer}" + assert reader.get_table_names() == [] + repository = PipelineRepository(ConnectorArrowDatabase(connector)) + job = _run_job("viewer-check", InMemoryArrowDatabase(), 10, run=False) + with pytest.raises( + SpiralDBWritePermissionError, match="likely no write access" + ) as raised: + repository.publish(job) + assert isinstance(raised.value.__cause__, connector_module.sp.SpiralError) + assert reader.get_table_names() == [] + + _INNER = pa.struct([pa.field("q", pa.int8()), pa.field("b", pa.large_string(), False)]) _UNITS = pa.schema( [ diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 16cd431ba..edc77276f 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -16,6 +16,7 @@ from decimal import Decimal from pathlib import Path from typing import Any, cast +from unittest.mock import patch import pyarrow as pa import pytest @@ -38,6 +39,7 @@ InputValidationError, OrcapodDatabaseReadError, SideEffectLogDataContextError, + SpiralDBWritePermissionError, SpiralDBWriteNotSupportedError, ) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator @@ -127,6 +129,40 @@ def test_rows_round_trip() -> None: assert schema is not None and schema.names == written.schema.names +@pytest.mark.usefixtures("root") +def test_generic_keyed_write_refusal_uses_database_wording() -> None: + refusal = fake.SpiralError("remote service returned an unknown error (status 404)") + with writable_connector() as connector: + database = ConnectorArrowDatabase(connector) + database.add_records(RESULT, rows(["one"]), "__record_id") + with ( + patch.object(fake.FakeProject, "create_keyed_table", side_effect=refusal), + pytest.raises( + SpiralDBWritePermissionError, match="no write access to the database" + ) as raised, + ): + database.flush() + assert raised.value.__cause__ is refusal + + +@pytest.mark.usefixtures("root") +def test_unprintable_sdk_append_failure_preserves_original() -> None: + class Unprintable(fake.SpiralError): + def __str__(self) -> str: + raise RuntimeError("cannot format SDK error") + + refusal = Unprintable() + with writable_connector() as connector: + database = ConnectorArrowDatabase(connector) + database.add_records(RESULT, rows(["one"]), "__record_id") + with ( + patch.object(fake.FakeKeyedTable, "append", side_effect=refusal), + pytest.raises(fake.SpiralError) as raised, + ): + database.flush() + assert raised.value is refusal + + @pytest.mark.usefixtures("root") def test_the_table_is_named_from_its_full_path_and_records_it() -> None: db = ConnectorArrowDatabase(writable_connector()).at("team", "results") diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 9ab6cb739..01999d2e7 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -14,6 +14,7 @@ from typing import cast from unittest.mock import patch +import pyarrow as pa import pytest from orcapod import ( @@ -31,6 +32,7 @@ SpiralDBKeyedConnector, SQLiteConnector, ) +from orcapod.errors import SpiralDBWritePermissionError from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL from orcapod.pipeline.serialization import LoadStatus, reuse_repository_database from orcapod.protocols.database_protocols import ArrowDatabaseProtocol @@ -1066,6 +1068,93 @@ def test_spiral_repository_reads_do_not_write(tmp_path: Path) -> None: spy.assert_not_called() +@pytest.mark.parametrize("seeded", [False, True], ids=["create", "append"]) +def test_spiral_publish_refusal_leaves_repository_unchanged( + tmp_path: Path, seeded: bool +) -> None: + with ( + fake_spiral_sdk.install(tmp_path), + SpiralDBKeyedConnector("p", "pipelines", writable=True) as connector, + ): + database = ConnectorArrowDatabase(connector) + repository = PipelineRepository(database) + results = InMemoryArrowDatabase() + if seeded: + original = repository.publish(_run_job("daily", results, 10)) + expected = [original] + owner, method = fake_spiral_sdk.FakeKeyedTable, "append" + message = ( + "Scandal:Internal (message: remote service returned an unknown error " + "(status 404))" + ) + else: + expected = [] + owner, method = fake_spiral_sdk.FakeProject, "create_keyed_table" + message = "remote service returned an unknown error (status 404)" + + job = _run_job("daily", results, 20) + refusal = fake_spiral_sdk.SpiralError(message) + with ( + patch.object(owner, method, side_effect=refusal) as write, + pytest.raises(PermissionError, match="likely no write access") as raised, + ): + repository.publish(job) + write.assert_called_once() + assert isinstance(raised.value, SpiralDBWritePermissionError) + assert raised.value.__cause__ is refusal + database.flush() + assert repository.list_versions(job.name) == expected + + +@pytest.mark.parametrize("seeded", [False, True], ids=["first", "existing"]) +def test_reconcile_publication_committed_before_opaque_append_reply( + tmp_path: Path, seeded: bool +) -> None: + append = fake_spiral_sdk.FakeKeyedTable.append + + def append_then_fail( + table: fake_spiral_sdk.FakeKeyedTable, batch: pa.Table + ) -> None: + _ = append(table, batch) + raise fake_spiral_sdk.SpiralError( + "Scandal:Internal (message: remote service returned an unknown error " + "(status 404))" + ) + + with ( + fake_spiral_sdk.install(tmp_path), + SpiralDBKeyedConnector("p", "pipelines", writable=True) as connector, + ): + repository = PipelineRepository(ConnectorArrowDatabase(connector)) + results = InMemoryArrowDatabase() + if seeded: + _ = repository.publish(_run_job("daily", results, 10, run=False)) + job = _run_job("daily", results, 20, run=False) + with patch.object(fake_spiral_sdk.FakeKeyedTable, "append", append_then_fail): + entry = repository.publish(job) + assert entry.version == (2 if seeded else 1) + assert repository.list_versions(job.name)[-1] == entry + + +def test_publication_readback_failure_preserves_sdk_cause() -> None: + database = InMemoryArrowDatabase() + repository = PipelineRepository(database) + job = _run_job("daily", database, 10, run=False) + sdk_error = fake_spiral_sdk.SpiralError("opaque 404") + refusal = SpiralDBWritePermissionError("keyed write refused") + refusal.__cause__ = sdk_error + read_error = OSError("readback failed") + with ( + patch.object(database, "flush_batch", side_effect=refusal), + patch.object(database, "get_record_by_id", side_effect=read_error) as readback, + pytest.raises(SpiralDBWritePermissionError) as raised, + ): + repository.publish(job) + readback.assert_called_once() + assert raised.value.__cause__ is sdk_error + assert raised.value.__context__ is read_error + + def test_spiral_repository_records_authenticated_author(tmp_path: Path) -> None: principal = SimpleNamespace( type="workload", workload=SimpleNamespace(workload_id="work_example")