diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 8486cd0c9..d6235d2f3 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -114,6 +114,9 @@ jobs: spiral-integration: runs-on: ubuntu-latest + concurrency: + group: spiral-integration + cancel-in-progress: false # Only run on push/manual trigger — not on PRs — to avoid consuming SpiralDB # resources on every review cycle. Runs only on the development repository: the public # repository has no SpiralDB credentials, so the job is skipped there (ITL-1007). diff --git a/RELEASING.md b/RELEASING.md index 3b19e3115..6a6d30ea0 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -305,9 +305,9 @@ Key) from the environment. It requests no GitHub OIDC token. The job fails at it first step, naming each missing setting, when one of the three below is not set or the key is not a private JWK naming its `kid`. No agent creates, reads or sets any of them. -The tests read through Orcapod and write their fixed tables through spiral-sdk, in the dataset -`orcapod_conformance` of the test project. spiral-sdk cannot drop a keyed table, so they stay; -each run writes the same rows. +The tests read through Orcapod and seed a fixed set of keyed tables through spiral-sdk in +the test project. Later runs reuse the read fixture snapshots. The write tests still exercise +their own fixed tables. On `metamorphic-labs/orcapod-python` and in SpiralDB, the developer sets: diff --git a/tests/test_databases/test_spiraldb_keyed_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py index c6cb5cd09..cbc84bf23 100644 --- a/tests/test_databases/test_spiraldb_keyed_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -6,11 +6,13 @@ set, a missing sign-in fails the tests rather than skipping them. ``SPIRAL_SERVER_URL`` names another address. -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 -fixed writable dataset, overridable with ``ORCAPOD_SPIRAL_DISCOVERY_DATASET``. A repeat run -reuses the stored results and checks that discovery makes no pod calls after the job run. +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`` +to select another dataset for that version. The discovery cases run Orcapod jobs with +fixed names in a fixed writable dataset, overridable with +``ORCAPOD_SPIRAL_DISCOVERY_DATASET``. A repeat run reuses the stored results and checks +that discovery makes no pod calls after the job run. """ from __future__ import annotations @@ -26,7 +28,7 @@ from contextlib import ExitStack from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import Any, Literal from unittest.mock import patch import pyarrow as pa @@ -39,6 +41,7 @@ from orcapod.databases.spiraldb_keyed.connector import SpiralDBTableNotFoundError from orcapod.sources import SpiralDBTableSource from orcapod.types import Condition, col +from orcapod.utils.arrow_utils import normalize_to_large_types from tests.test_core.sources.test_discovered_results import ( assert_discovery_without_function_module, ) @@ -47,7 +50,9 @@ _LIVE = os.environ.get("SPIRAL_INTEGRATION_TESTS") == "1" _PROJECT = os.environ.get("SPIRAL_PROJECT_ID", "") _URL = os.environ.get("SPIRAL_SERVER_URL", "https://api.spiraldb.dev") -_DATASET = os.environ.get("ORCAPOD_SPIRAL_CONFORMANCE_DATASET", "orcapod_conformance") +_DATASET = os.environ.get( + "ORCAPOD_SPIRAL_CONFORMANCE_DATASET", "orcapod_conformance_v2" +) _DISCOVERY_DATASET = os.environ.get( "ORCAPOD_SPIRAL_DISCOVERY_DATASET", "orcapod_discovery_conformance" ) @@ -201,6 +206,11 @@ def _ranges() -> pa.Table: _RANGES = _ranges() +_READ_FIXTURES = ( + ("units", ("k2", "k1"), _ROWS), + ("typed", ("k",), _TYPED), + ("ranges", ("k",), _RANGES), +) @dataclass(frozen=True) @@ -227,30 +237,136 @@ def source(self, name: str, **options: Any) -> SpiralDBTableSource: ) -def _seed(client: Any, place: _Place) -> None: - """Write the tables and, once, their schema rows, through the SDK.""" - project = client.project(place.project) - made = {} - for name, keys, rows in ( - ("units", ["k2", "k1"], _ROWS), - ("typed", ["k"], _TYPED), - ("ranges", ["k"], _RANGES), +def _fixture_type(arrow_type: pa.DataType) -> object: + """Compare types independently of SDK offsets, field order, and nullability.""" + if pa.types.is_struct(arrow_type): + fields = sorted(arrow_type, key=operator.attrgetter("name")) + return ("struct", [(field.name, _fixture_type(field.type)) for field in fields]) + if pa.types.is_fixed_size_list(arrow_type): + return ( + "fixed_size_list", + arrow_type.list_size, + _fixture_type(arrow_type.value_type), + ) + if pa.types.is_list(arrow_type) or pa.types.is_large_list(arrow_type): + return ("list", _fixture_type(arrow_type.value_type)) + return normalize_to_large_types(arrow_type, keep_null=True) + + +def _matches_fixture_schema(actual: pa.Schema, expected: pa.Schema) -> bool: + """Compare stored column types before the scan's values can be cast.""" + return set(actual.names) == set(expected.names) and all( + _fixture_type(actual.field(field.name).type) == _fixture_type(field.type) + for field in expected + ) + + +def _matches_fixture( + actual: pa.Table, expected: pa.Table, keys: tuple[str, ...] +) -> bool: + """Compare scanned rows in key order, treating identical floating-point bits as equal.""" + if actual.num_rows != expected.num_rows or set(actual.column_names) != set( + expected.column_names ): - key_schema = pa.schema([rows.schema.field(k) for k in keys]) - table = project.create_keyed_table( - place.dataset, name, key_schema, exist_ok=True + return False + sort_keys: list[tuple[str, Literal["ascending", "descending"]]] = [ + (key, "ascending") for key in keys + ] + expected = expected.sort_by(sort_keys) + try: + actual = actual.select(expected.column_names).cast(expected.schema) + except (pa.ArrowInvalid, pa.ArrowNotImplementedError): + return False + actual = actual.sort_by(sort_keys) + for scanned, written in zip(actual.columns, expected.columns, strict=True): + if pa.types.is_floating(written.type): + bits = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[ + written.type.bit_width + ] + if ( + not scanned.combine_chunks() + .view(bits) + .equals(written.combine_chunks().view(bits)) + ): + return False + elif not scanned.equals(written): + return False + return True + + +def _require_fixture_snapshots(client: Any, schema_table: Any, scope: st.Scope) -> None: + """Validate the registry and each captured version without scanning data tables.""" + rows, marker = st.read_rows(schema_table.scan().to_table().to_pylist()) + if marker is None: + raise st.TableSchemaError("the schema registry has no completion marker") + st.require_complete(scope.project, scope.dataset, rows, marker) + if marker["plan_digest"] != scope.plan_digest: + raise st.TableSchemaError( + "the completion marker is for a different fixture plan" ) - made[name] = (table.append(rows), rows.schema) + expected_names = sorted(name for name, _, _ in _READ_FIXTURES) + if sorted(row.table_name for row in rows.values()) != expected_names: + raise st.TableSchemaError( + "the completion marker does not cover the expected fixtures" + ) + + by_name = {row.table_name: row for row in rows.values()} + for name, keys, _ in _READ_FIXTURES: + row = by_name[name] + table = connector_module._open_keyed_table( # pyright: ignore[reportPrivateUsage] # use the SDK lookup and its missing-table handling + client, scope.project, scope.dataset, name + ) + if ( + row.key_columns != keys + or table is None + or (table.resource_id, tuple(table.key_columns), int(table.version_id)) + != (row.table_id, keys, row.captured_version) + ): + raise st.TableSchemaError( + f"read fixture {name!r} no longer matches its captured snapshot" + ) + + +def _seed(client: Any, place: _Place) -> None: + """Create the fixed read fixtures once, resuming an interrupted first seed.""" + project = client.project(place.project) schemas = project.create_keyed_table( place.dataset, st.SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=True ) - if st.require_schema_table(schemas): - return + scope = st.Scope(place.project, place.dataset, "0" * 64) + try: + if st.require_schema_table(schemas): + _require_fixture_snapshots(client, schemas, scope) + return + except st.TableSchemaError as exc: + raise st.TableSchemaError( + f"Read fixtures in dataset {place.dataset!r}: {exc.reason}. " + "Please choose a clean dataset using ORCAPOD_SPIRAL_CONFORMANCE_DATASET." + ) from exc + rows = [] - for name, (table, written) in made.items(): + for name, keys, data in _READ_FIXTURES: + key_schema = pa.schema([data.schema.field(k) for k in keys]) + table = project.create_keyed_table( + place.dataset, name, key_schema, exist_ok=True + ) + found = table.schema() + if found.names == list(keys): + table = table.append(data) + found = table.schema() + elif not _matches_fixture_schema(found, data.schema) or not _matches_fixture( + table.scan(limit=data.num_rows + 1).to_table(), data, keys + ): + raise ValueError( + f"Read fixture {name!r} in dataset {place.dataset!r} has an unexpected schema or rows. " + "Please choose a clean dataset using ORCAPOD_SPIRAL_CONFORMANCE_DATASET." + ) + metadata = data.schema.metadata presented = pa.schema( - [_in_order(f, written.field(f.name)) for f in table.schema()], - metadata=written.metadata, + [_in_order(f, data.schema.field(f.name)) for f in found], + metadata={key: value for key, value in metadata.items()} + if metadata + else None, ) rows.append( st.SchemaRow( @@ -262,13 +378,18 @@ def _seed(client: Any, place: _Place) -> None: int(table.version_id), ) ) - scope = st.Scope(place.project, place.dataset, "0" * 64) - for values in (*(r.stored() for r in rows), st.marker_values(scope, rows)): - schemas.append( - pa.Table.from_pylist( - [{"written_at": "", "written_by": "", **values}], schema=st.ROW_SCHEMA - ) + schemas.append( + pa.Table.from_pylist( + [ + {"written_at": "", "written_by": "", **values} + for values in ( + *(row.stored() for row in rows), + st.marker_values(scope, rows), + ) + ], + schema=st.ROW_SCHEMA, ) + ) def _in_order(found: Any, written: Any) -> Any: @@ -310,6 +431,149 @@ def place( yield made +def test_reopening_a_seeded_fixture_keeps_its_snapshots(tmp_path: Path) -> None: + """A second setup reuses the read fixtures without publishing new fragments.""" + with fake.install(tmp_path): + client = fake.FakeClient() + place = _Place("p", _DATASET, None) + _seed(client, place) + names = ("units", "typed", "ranges", st.SCHEMA_TABLE) + versions = [ + client.keyed_table(place.project, place.dataset, name).version_id + for name in names + ] + + scans = list(fake.scan_log) + _seed(client, place) + + assert fake.scan_log == scans + assert [ + client.keyed_table(place.project, place.dataset, name).version_id + for name in names + ] == versions + + +@pytest.mark.parametrize( + ("difference", "reverse_scan"), + [(None, False), ("value", False), (None, True), ("type", False)], + ids=["matching", "mismatched-value", "reversed-scan", "mismatched-type"], +) +def test_resuming_seed_checks_existing_fixture_rows( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + difference: str | None, + reverse_scan: bool, +) -> None: + """Complete an interrupted seed only when the existing rows match.""" + with fake.install(tmp_path): + client = fake.FakeClient() + place = _Place("p", "reused_fixture", None) + project = client.project(place.project) + registry = project.create_keyed_table( + place.dataset, st.SCHEMA_TABLE, st.KEY_SCHEMA + ) + versions = {} + for name, keys, data in _READ_FIXTURES: + if difference is not None and name == "ranges": + index = data.column_names.index("int16") + column = ( + data.column("int16").cast(pa.int32()) + if difference == "type" + else pa.array([42] * data.num_rows, pa.int16()) + ) + data = data.set_column(index, "int16", column) + table = project.create_keyed_table( + place.dataset, name, pa.schema([data.schema.field(key) for key in keys]) + ) + table = table.append(data) + versions[table.resource_id] = table.version_id + + if reverse_scan: + original_to_table = fake.FakeScan.to_table + + def reversed_rows(scan: fake.FakeScan) -> pa.Table: + rows = original_to_table(scan) + indices = pa.array(range(rows.num_rows - 1, -1, -1), pa.int64()) + return rows.take(indices) + + monkeypatch.setattr(fake.FakeScan, "to_table", reversed_rows) + + if difference is not None: + with pytest.raises( + ValueError, match=r"reused_fixture.*choose a clean dataset" + ): + _seed(client, place) + latest = client.keyed_table_by_id(registry.resource_id) + assert latest.version_id == registry.version_id + else: + _seed(client, place) + latest = client.keyed_table_by_id(registry.resource_id) + assert st.require_schema_table(latest) + assert { + table_id: client.keyed_table_by_id(table_id).version_id + for table_id in versions + } == versions + + +@pytest.mark.parametrize( + ("marker", "diagnostic"), + [ + ("missing", "no completion marker"), + ("other-dataset", "was written for dataset"), + ("partial", "does not cover the expected fixtures"), + ], +) +def test_reopening_fixture_requires_a_scoped_completion_marker( + tmp_path: Path, marker: str, diagnostic: str +) -> None: + """The registry must cover every fixture and belong to this dataset.""" + with fake.install(tmp_path): + client = fake.FakeClient() + place = _Place("p", "reused_fixture", None) + table = client.project(place.project).create_keyed_table( + place.dataset, "ranges", pa.schema([_RANGES.schema.field("k")]) + ) + table = table.append(_RANGES) + fake.migrate( + place.project, + {"ranges": table.schema()}, + dataset=place.dataset, + complete=marker == "partial", + ) + if marker == "other-dataset": + registry = client.keyed_table(place.project, place.dataset, st.SCHEMA_TABLE) + rows, _ = st.read_rows(registry.scan().to_table().to_pylist()) + wrong_scope = st.Scope(place.project, "other_fixture", "0" * 64) + registry.append( + pa.Table.from_pylist( + [st.marker_values(wrong_scope, rows.values())], schema=st.ROW_SCHEMA + ) + ) + + with pytest.raises( + st.TableSchemaError, + match=rf"reused_fixture.*{diagnostic}.*choose a clean dataset", + ): + _seed(client, place) + + +def test_reopening_fixture_rejects_rows_appended_after_seeding(tmp_path: Path) -> None: + """A completed fixture must still point at the snapshots captured at seed time.""" + with fake.install(tmp_path): + client = fake.FakeClient() + place = _Place("p", "reused_fixture", None) + _seed(client, place) + table = client.keyed_table(place.project, place.dataset, "ranges") + extra = _RANGES.slice(0, 1).set_column(0, "k", pa.array([100], pa.int64())) + changed = table.append(extra) + + with pytest.raises(ValueError, match=r"ranges.*choose a clean dataset"): + _seed(client, place) + assert ( + client.keyed_table_by_id(table.resource_id).version_id == changed.version_id + ) + + def test_the_listing_holds_the_tables_and_not_the_schema_table(place: _Place) -> None: names = place.connector().get_table_names() assert {"units", "typed"} <= set(names) @@ -429,9 +693,6 @@ def test_an_early_close(place: _Place) -> None: # ---------------------------------------------------------------------------- ranges -# A dataset seeded before ``ranges`` existed records no schema row for it (rows are -# written once): its columns then read as nullable, with a warning; the keys compared -# here are unaffected. _RANGE_OPERATORS = { "<": (operator.lt, pc.less),