From aa2307096f7e39b87a50601c9e5e9199115a4d75 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 08:10:29 -0800 Subject: [PATCH 1/2] fix(spiraldb): explain refused keyed writes --- changelog.d/ITL-1980.md | 6 +++ docs/api/errors.md | 2 + .../databases/spiraldb_keyed/tables.py | 24 ++++++++-- src/orcapod/errors.py | 4 ++ src/orcapod/pipeline/repository.py | 5 +++ ...st_spiraldb_keyed_connector_integration.py | 44 ++++++++++++++++++- .../test_pipeline/test_pipeline_repository.py | 39 ++++++++++++++++ 7 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 changelog.d/ITL-1980.md diff --git a/changelog.d/ITL-1980.md b/changelog.d/ITL-1980.md new file mode 100644 index 000000000..f296c6f06 --- /dev/null +++ b/changelog.d/ITL-1980.md @@ -0,0 +1,6 @@ +### Fixed + +- Publishing to a keyed SpiralDB repository now raises + `SpiralDBWritePermissionError` when the store refuses the write with an opaque + 404. The error reports that write access 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..bd408b179 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, @@ -1272,6 +1272,24 @@ 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 str(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 repository's 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,7 +1312,7 @@ 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] @@ -1590,7 +1608,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..23e2a8d72 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 write in a way that suggests 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 1d23aca86..95a0fde72 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. """ @@ -295,6 +298,8 @@ def record_acceptance( ) accepted = True self._database.flush_batch(_TABLE_PATH) + except SpiralDBWritePermissionError: + raise except Exception as exc: if not accepted: raise diff --git a/tests/test_databases/test_spiraldb_keyed_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py index c6cb5cd09..ba248b637 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 use fixed tables, with ``ORCAPOD_SPIRAL_CONFORMANCE_DATASET`` overriding their dataset, and seed the same rows through the SDK on every run. The discovery cases run Orcapod jobs with fixed names in a @@ -33,16 +36,23 @@ 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 tests.test_core.sources.test_discovered_results import ( 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", "") @@ -92,6 +102,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_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 277319e92..0121fe9d1 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -31,6 +31,7 @@ SpiralDBKeyedConnector, SQLiteConnector, ) +from orcapod.errors import SpiralDBWritePermissionError from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import DictSource @@ -838,6 +839,44 @@ 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 + + def test_spiral_repository_records_authenticated_author(tmp_path: Path) -> None: principal = SimpleNamespace( type="workload", workload=SimpleNamespace(workload_id="work_example") From 1ba797f5349d9bf22e33fa312f38285101d3bff7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 08:18:57 -0800 Subject: [PATCH 2/2] fix(spiraldb): reconcile ambiguous keyed writes --- changelog.d/ITL-1980.md | 8 +-- .../databases/spiraldb_keyed/tables.py | 15 ++++-- src/orcapod/errors.py | 2 +- src/orcapod/pipeline/repository.py | 7 ++- .../test_spiraldb_writable_mode.py | 36 +++++++++++++ .../test_pipeline/test_pipeline_repository.py | 50 +++++++++++++++++++ 6 files changed, 107 insertions(+), 11 deletions(-) diff --git a/changelog.d/ITL-1980.md b/changelog.d/ITL-1980.md index f296c6f06..11f6a6794 100644 --- a/changelog.d/ITL-1980.md +++ b/changelog.d/ITL-1980.md @@ -1,6 +1,6 @@ ### Fixed -- Publishing to a keyed SpiralDB repository now raises - `SpiralDBWritePermissionError` when the store refuses the write with an opaque - 404. The error reports that write access is likely missing and preserves the - original store error as its cause. +- 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/src/orcapod/databases/spiraldb_keyed/tables.py b/src/orcapod/databases/spiraldb_keyed/tables.py index bd408b179..d56be569a 100644 --- a/src/orcapod/databases/spiraldb_keyed/tables.py +++ b/src/orcapod/databases/spiraldb_keyed/tables.py @@ -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. @@ -1280,14 +1288,13 @@ def _write_call(self, doing: str) -> Iterator[None]: yield except self._sdk.SpiralError as err: # pyright: ignore[reportAny] opaque_404 = "remote service returned an unknown error (status 404)" - if str(err) not in ( # pyright: ignore[reportAny] + 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 repository's database." + "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]: @@ -1315,7 +1322,7 @@ def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: 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: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 23e2a8d72..673e83e18 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -740,7 +740,7 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: class SpiralDBWritePermissionError(PermissionError): - """SpiralDB refused a keyed write in a way that suggests missing write access.""" + """SpiralDB refused a keyed create or append, suggesting missing write access.""" class SpiralDBWriteNotSupportedError(NotImplementedError): diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 95a0fde72..26e6439ad 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -298,8 +298,6 @@ def record_acceptance( ) accepted = True self._database.flush_batch(_TABLE_PATH) - except SpiralDBWritePermissionError: - raise except Exception as exc: if not accepted: raise @@ -316,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_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 0121fe9d1..5bbfc11e4 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 ( @@ -877,6 +878,55 @@ def test_spiral_publish_refusal_leaves_repository_unchanged( 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")