diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index c2f72dcc7..b2f8ed0ae 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -27176,7 +27176,7 @@ } } ], - "./src/orcapod/databases/spiraldb_connector.py": [ + "./src/orcapod/databases/spiraldb_keyed/connector.py": [ { "code": "reportMissingImports", "range": { @@ -184110,7 +184110,7 @@ } } ], - "./tests/test_databases/test_spiraldb_connector_integration.py": [ + "./tests/test_databases/test_spiraldb_keyed_connector_integration.py": [ { "code": "reportUnknownParameterType", "range": { diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 483be75e2..8486cd0c9 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -191,7 +191,7 @@ jobs: SPIRAL_CLIENT_ID: ${{ secrets.SPIRAL_CLIENT_ID }} SPIRAL_PRIVATE_KEY: ${{ secrets.SPIRAL_PRIVATE_KEY }} # Serial (-n 0): the integration tests share one SpiralDB project (ITL-1181). - run: uv run --python "3.11" pytest -n 0 tests/test_databases/test_spiraldb_connector_integration.py -v + run: uv run --python "3.11" pytest -n 0 tests/test_databases/test_spiraldb_keyed_connector_integration.py -v license-check: uses: ./.github/workflows/_license-check.yml diff --git a/.zed/rules b/.zed/rules index 56894ec55..5ccd4aa78 100644 --- a/.zed/rules +++ b/.zed/rules @@ -61,6 +61,10 @@ This is a greenfield project pre-v0.1.0. Do NOT add backward-compatibility shims re-exports, aliases, or deprecation wrappers when making design or implementation changes. Just change the code and update all references directly. +The keyed backend is SpiralDBKeyedConnector (databases/spiraldb_keyed/). A saved +job uses connector_type: spiraldb_keyed. Loading the retired spiraldb connector +type raises an error naming spiraldb_keyed. The source kind stays spiraldb_table. + ## No sys.modules hacks Never manipulate sys.modules directly (e.g. sys.modules.setdefault). If a subpackage diff --git a/CLAUDE.md b/CLAUDE.md index 72aaebf59..21e096d38 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,6 +65,10 @@ This is a greenfield project pre-v0.1.0. Do **not** add backward-compatibility s re-exports, aliases, or deprecation wrappers when making design or implementation changes. Just change the code and update all references directly. +The keyed backend is `SpiralDBKeyedConnector` (`databases/spiraldb_keyed/`). A saved +job uses `connector_type: spiraldb_keyed`. Loading the retired `spiraldb` connector +type raises an error naming `spiraldb_keyed`. The source kind stays `spiraldb_table`. + ## No `sys.modules` hacks Never manipulate `sys.modules` directly (e.g. `sys.modules.setdefault`). If a subpackage diff --git a/RELEASING.md b/RELEASING.md index 296c294c0..3b19e3115 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -363,10 +363,10 @@ job runs the connector conformance tests on a separate test project. releases daily, of which Orcapod uses two attributes that are not public API (`Client._native.api_url` and `Client._native.access_token`, for the documented table listing). To move the pin: change it there, run `uv lock`, and run the conformance tests live -(`tests/test_databases/test_spiraldb_connector_integration.py`, see its docstring). A refusal or a +(`tests/test_databases/test_spiraldb_keyed_connector_integration.py`, see its docstring). A refusal or a value that changed is a change of `tests/test_databases/fake_spiral_sdk.py` (its `RULES`) first. From 0.16.79 spiral-sdk warns on every keyed-table open; Orcapod's connector ignores that one -message for its own opens (`spiraldb_connector._ignore_keyed_table_deprecation`), and +message for its own opens (`spiraldb_keyed.connector._ignore_keyed_table_deprecation`), and `tests/test_databases/test_spiraldb_keyed_table_deprecation.py` fails if a new release changes the message, the category or the module it is attributed to. The move off keyed tables is ITL-1846. diff --git a/changelog.d/ITL-1023.md b/changelog.d/ITL-1023.md index d66345a0f..9e8ac9bfa 100644 --- a/changelog.d/ITL-1023.md +++ b/changelog.d/ITL-1023.md @@ -85,7 +85,7 @@ - `FieldMetadataKeepingDatabaseProtocol` (`orcapod.protocols.database_protocols`): a database states with `keeps_field_metadata` whether it keeps Arrow field metadata. `InMemoryArrowDatabase`, `DeltaTableDatabase` and a `ConnectorArrowDatabase` over - `SpiralDBConnector` state `True`. The SQLite and PostgreSQL connector databases and + `SpiralDBKeyedConnector` state `True`. The SQLite and PostgreSQL connector databases and `NoOpArrowDatabase` state `False`. `ExtensionAwareDatabase` states what the database it wraps states, and a connector database what its connector states. A database without the member is treated as not keeping field metadata. diff --git a/changelog.d/ITL-1186.md b/changelog.d/ITL-1186.md index d7c59cc94..7c961545b 100644 --- a/changelog.d/ITL-1186.md +++ b/changelog.d/ITL-1186.md @@ -1,7 +1,7 @@ ### Breaking changes and migration - SpiralDB is read through `spiral-sdk` (the `spiraldb` extra pins `spiral-sdk==0.16.74`), and `pyspiral` is gone. Both packages provide a module named `spiral`: install into an environment without `pyspiral`. -- A plain `SpiralDBConnector` only reads. Every write of a plain connector (`create_table_if_not_exists`, `upsert_records`, `delete_table`) and every job whose database is on one raises `SpiralDBWriteNotSupportedError`, before anything is buffered or run. A job keeps its tables in SpiralDB through a writable SpiralDB database, `SpiralDBConnector(..., writable=True)` (ITL-1844). +- A plain `SpiralDBKeyedConnector` only reads. Every write of a plain connector (`create_table_if_not_exists`, `upsert_records`, `delete_table`) and every job whose database is on one raises `SpiralDBWriteNotSupportedError`, before anything is buffered or run. A job keeps its tables in SpiralDB through a writable SpiralDB database, `SpiralDBKeyedConnector(..., writable=True)` (ITL-1844). - A table's non-nullable columns and Arrow metadata are read from its dataset's schema table, `__orcapod_schemas__`, not from the table's metadata. Datasets written by an earlier release must be migrated once with `scripts/migrate_spiral_schemas.py` (`RELEASING.md`); then schemas, hashes and source ids are as before. Until then their tables read with every column nullable, with `UnrecordedTableSchemaWarning`, and their hashes differ. - `read_nullability_record` and `write_nullability_record` are removed, and `NullabilityRecordError` is replaced by `TableSchemaError`. - Row counts are counted from the keys: `row_count_estimate` is exact and reads every key, the `max_rows` check reads at most `max_rows + 1` keys, and a preview of more than 100,000 rows shows no total. @@ -21,4 +21,4 @@ ### Known limitations - A saved SpiralDB login that has expired is not detected: the client may print a sign-in prompt and wait. Run `uv run spiral login` again. -- A `SpiralDBConnector` cannot be used in a forked process (`spawn` works); it is refused there. +- A `SpiralDBKeyedConnector` cannot be used in a forked process (`spawn` works); it is refused there. diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index 8c05dec81..74a2edd7c 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -35,7 +35,7 @@ aggregate) reads every column nullable. (ITL-1276) - **`SQLiteConnector` refuses a `double` column holding a NaN or `-0.0`:** SQLite reads a NaN back as NULL and `-0.0` as `0.0`. (ITL-1334) -- **`SpiralDBConnector` refuses a logical (extension) type:** `File`, `Directory`, +- **`SpiralDBKeyedConnector` refuses a logical (extension) type:** `File`, `Directory`, `Path`, `UPath`, `UUID`, `list[T]` and `set[T]` of them, user classes and the library value types read back from SpiralDB as their plain storage type (SpiralDB drops the field metadata that names them). They are refused with `UnstorableColumnError` before @@ -76,7 +76,7 @@ an append makes nullable reads back nullable. (ITL-1334) - **`DeltaTableDatabase` refuses a struct with no fields at any depth:** a Parquet file stores values in leaf columns only, so the flush failed. (ITL-1334) -- **`SpiralDBConnector` refuses field metadata below a map, and Arrow's canonical extension +- **`SpiralDBKeyedConnector` refuses field metadata below a map, and Arrow's canonical extension types:** its metadata record does not descend into a map, so metadata on a map's key or item, or inside them, read back dropped. A `uuid` or `json` column (Arrow's own extension types) read back as its storage type. (ITL-1334) @@ -108,7 +108,7 @@ the recorded type or a logical column's extension name, so afterwards a list read back with its item named `element`, and a logical list (`set[int]`, `list[Path]`) as its plain storage type. (ITL-1334) -- **`SpiralDBConnector` reads back a fixed-size list with non-null items and a null row:** +- **`SpiralDBKeyedConnector` reads back a fixed-size list with non-null items and a null row:** the read cast every column to the restored schema, and pyarrow refuses that cast when a null row hides null item slots; only columns whose type changes are cast now. (ITL-1334) diff --git a/changelog.d/ITL-1350.md b/changelog.d/ITL-1350.md index 964573c20..8f6c3ee2c 100644 --- a/changelog.d/ITL-1350.md +++ b/changelog.d/ITL-1350.md @@ -3,7 +3,7 @@ - A `SpiralDBTableSource` looks its table up once when it is built and once per new-data check (ITL-1350). Every lookup of a table by name is a round trip to SpiralDB; the source used to look the table up for each item it needed (key, id, schema and - version: four lookups to build, three per check). `SpiralDBConnector.lookup_table` + version: four lookups to build, three per check). `SpiralDBKeyedConnector.lookup_table` returns the table once, with its id and key columns, and reads its schema and version when asked, in the same order and under the same conditions as before, so a check still finds a table dropped and created again since. Measured on a live project: diff --git a/changelog.d/ITL-1840.md b/changelog.d/ITL-1840.md index 5eec33a4a..cda19f732 100644 --- a/changelog.d/ITL-1840.md +++ b/changelog.d/ITL-1840.md @@ -1,6 +1,6 @@ ### Known limitations -- A writable SpiralDB database (`SpiralDBConnector(..., writable=True)`, ITL-1844) keeps every stored +- A writable SpiralDB database (`SpiralDBKeyedConnector(..., writable=True)`, ITL-1844) keeps every stored table kind through `ConnectorArrowDatabase`: one table per path, its identity and manifest in the table's metadata. Its format is provisional, outside the 0.4.0 freeze. (ITL-1840) diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md index 5ccf68e3b..a7c7174a4 100644 --- a/changelog.d/ITL-1844.md +++ b/changelog.d/ITL-1844.md @@ -1,30 +1,20 @@ ### Added - A SpiralDB dataset can be a job's database: a writable SpiralDB database, - `SpiralDBConnector(project_id, dataset, writable=True)` under `ConnectorArrowDatabase`, stores every table a job writes (function results and + `SpiralDBKeyedConnector(project_id, dataset, writable=True)` under `ConnectorArrowDatabase`, stores every table a job writes (function results and pipeline records, operator caches, cached sources, side-effect logs), also as a separate - result database. Provisional in 0.4.0: the database's table format and its writer lease may - change in a later version, which may not read tables written now. Nothing of the - database enters a hash. See "SpiralDB as a Job's Database" in the concepts. -- One writer per writable SpiralDB database: `job.run()`, `job.run_async()` and a job node's `run()` - take the dataset's writer lease before checking a source or writing anything, and release - it when they end, also when they fail. A second writer is refused then with - `LeaseBusyError`, before anything of its run happens. A stale lease is cleared by its - project, dataset and table id with - `spiraldb_lease.clear(client, project_id, dataset, table_id, confirm_writer_stopped=True)`. + result database. The table format is provisional in 0.4.0 and later versions may + be unable to read tables written now. Nothing of the database enters a hash. + See [Keyed SpiralDB as a Job's Database](docs/concepts/spiraldb-keyed-database.md). - A job saved on a writable SpiralDB database records `writable: true` and no credential; `PipelineJob.load` takes the connector again and refuses a SpiralDB connector of the other kind. ### Known limitations -- Only a job run writes a writable SpiralDB database, through the writable connectors it - holds the lease with: a write through any other writable connector (a cached source read outside a run, a - `ConnectorArrowDatabase` over a connector of its own flushed directly) raises - `SpiralDBLeaseRequiredError`, also while a run holds the lease. A write through a - running job's own databases from outside the run is not told apart from the run's own. - A way to hold the lease outside a run is later work (ITL-1849). -- The writer lease is refuse-only: no waiting, no takeover, no expiry. Each run leaves one - small lease table in the dataset, which is kept. +- Writable SpiralDB databases assume one writer process per keyed dataset at a time. + The caller manages cross-process exclusion. The default `NoWriteLock` performs + no cross-process coordination. A direct write outside a run opens a write scope + for that call. - A writable SpiralDB database reads a table's whole key column to tell which rows it holds, and whole tables to read stored rows, so a run's cost grows with the tables' history. - The database does not take over tables it did not write, and status and logging observers diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md index 1c45fddfb..e1b1ec99e 100644 --- a/changelog.d/ITL-1899.md +++ b/changelog.d/ITL-1899.md @@ -15,7 +15,7 @@ ### Added -- Writable `SpiralDBConnector` accepts a `WriteLock` provider from +- Writable `SpiralDBKeyedConnector` accepts a `WriteLock` provider from `orcapod.databases.write_lock`. The default `NoWriteLock` performs no cross-process coordination. A scope acquires its lock before the first write or side effect and releases its handle when the diff --git a/changelog.d/ITL-1903.md b/changelog.d/ITL-1903.md new file mode 100644 index 000000000..78dd42d2d --- /dev/null +++ b/changelog.d/ITL-1903.md @@ -0,0 +1,11 @@ +### Added + +- `orcapod.databases.SpiralDatabase(project_id, dataset, ...)` opens a writable SpiralDB + database for a job. Saved jobs record the concrete backend and its configuration. + +### Changed + +- The keyed backend is now `SpiralDBKeyedConnector`. Saved jobs now use the + `spiraldb_keyed` connector type. Loading the retired `spiraldb` type raises an + error naming `spiraldb_keyed`. The `spiraldb_table` source kind and source IDs + stay the same. diff --git a/changelog.d/ITL-998.md b/changelog.d/ITL-998.md index be1ad55a4..7ad3d205c 100644 --- a/changelog.d/ITL-998.md +++ b/changelog.d/ITL-998.md @@ -18,7 +18,7 @@ a=2)` and `where(a=2, b=1)` save the same bytes. Saved jobs and configs written before load to the same condition; their bytes change only when two or more columns had been given out of that order. No hash, stored path or identity reads a saved condition. -- The `where` parameter of `SpiralDBConnector.scan_batches` is PROVISIONAL and takes a +- The `where` parameter of `SpiralDBKeyedConnector.scan_batches` is PROVISIONAL and takes a `Condition` (equalities and ranges). To pass a mapping, wrap it in `Condition.of(...)`. - For now, `SpiralDBTableSource.where(...)` and `where=` refuse an equality of a float column to `-0.0` or a NaN (`TypeError`, pointing to `filter`). SpiralDB matches them by their bits, diff --git a/docs/api/databases.md b/docs/api/databases.md index 045e29661..27d945ffb 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -6,10 +6,10 @@ introduction. Every signature and docstring on the published page comes from the code. See site/README.md. --> -Database backends store pipeline results. The SQLite and PostgreSQL connectors support -reads and writes through `ConnectorArrowDatabase`. The SpiralDB connector reads, and writes -only when opened writable (`writable=True`, provisional; see -[SpiralDB as a Job's Database](../concepts/spiraldb-database.md)). +Database backends store pipeline results. `SpiralDatabase` opens a writable database on +Orcapod's default SpiralDB backend. See +[Keyed SpiralDB as a Job's Database](../concepts/spiraldb-keyed-database.md). +The SQLite and PostgreSQL connectors support reads and writes through `ConnectorArrowDatabase`. **Provisional.** `ExtensionAwareDatabase` is expected to be integrated more closely with the underlying database classes (ITL-1539), so its public form may change. @@ -20,6 +20,8 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.NoOpArrowDatabase +::: orcapod.databases.SpiralDatabase + ::: orcapod.databases.ConnectorArrowDatabase ::: orcapod.databases.ExtensionAwareDatabase @@ -28,7 +30,7 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.PostgreSQLConnector -::: orcapod.databases.SpiralDBConnector +::: orcapod.databases.SpiralDBKeyedConnector ::: orcapod.databases.write_lock.WriteLock diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index a5e036d6a..003b3f72b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -277,10 +277,8 @@ structs, dates or timestamps on SQLite, narrower integers and floats, logical ty refused. PostgreSQL also refuses column names and explicit table identifiers longer than 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). SQLite and PostgreSQL stores generate table names within 63 bytes from the node's -path, using a readable hint and a digest of the full path. A database on -`SpiralDBConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened -writable, `SpiralDBConnector(..., writable=True)`: see -[SpiralDB as a Job's Database](spiraldb-database.md). The full list, +path, using a readable hint and a digest of the full path. Use `SpiralDatabase` to +store job tables in SpiralDB. See [Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). The full list, type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 9609ee8a2..08d08b8d2 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -581,19 +581,19 @@ again only when the version moved. A changed environment or saved login, or a cl whose calls failed, gives the next new source a new client. Closing a source affects no other; the client goes with the last source that uses it, and a forked process starts with none. -A plain `SpiralDBConnector` only reads: a write through it (or a job whose database is on -one) raises `SpiralDBWriteNotSupportedError`. A job can keep its tables in SpiralDB through -a writable SpiralDB database, `SpiralDBConnector(..., writable=True)`: see -[SpiralDB as a Job's Database](spiraldb-database.md). +A plain `SpiralDBKeyedConnector` only reads: a write through it (or a job whose database is on +one) raises `SpiralDBWriteNotSupportedError`. Use `SpiralDatabase` to store job tables +in SpiralDB. See +[Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). Replace the example project, dataset and table names with identifiers you can access. To find the tables of a dataset and their key columns: ```python -from orcapod.databases import SpiralDBConnector +from orcapod.databases import SpiralDBKeyedConnector -with SpiralDBConnector("my-project-123456", dataset="my_dataset") as spiral: +with SpiralDBKeyedConnector("my-project-123456", dataset="my_dataset") as spiral: print(spiral.get_table_names()) print(spiral.get_pk_columns("sensor_reading")) ``` @@ -907,7 +907,7 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **One mechanism.** `where()` adds to the conditions given with `where=` (a mapping or a `Condition`) when the source was built (`Condition.combined`), and SpiralDB applies them - in the scan. If you call `SpiralDBConnector.scan_batches` directly, its PROVISIONAL + in the scan. If you call `SpiralDBKeyedConnector.scan_batches` directly, its PROVISIONAL `where` parameter takes a `Condition`. Use `Condition.of(...)` to wrap a mapping. A column already restricted to another value is refused, as is a column the table does not have, `None` (a null equals nothing) and diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-keyed-database.md similarity index 73% rename from docs/concepts/spiraldb-database.md rename to docs/concepts/spiraldb-keyed-database.md index 332c7d138..b9114faf6 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-keyed-database.md @@ -1,4 +1,4 @@ -# SpiralDB as a Job's Database +# Keyed SpiralDB as a Job's Database A job can keep everything it stores in a SpiralDB dataset: function results, pipeline records, operator caches, cached sources and side-effect logs. Open the dataset as a @@ -13,24 +13,51 @@ records, operator caches, cached sources and side-effect logs. Open the dataset ## Opening the SpiralDB database -`SpiralDBConnector(project_id, dataset, writable=True)` opens one dataset as a writable -SpiralDB database. Wrap it in `ConnectorArrowDatabase` and use it as the job's database, its separate result -database, or a cached source's database: +Use `SpiralDatabase(project_id, dataset)` to open a writable database for a job, its +separate result database, or a cached source. Install `orcapod[spiraldb]` and sign in +through spiral-sdk before opening the database. - ```python from orcapod import PipelineJob -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import SpiralDatabase + + +def make_job(project_id: str, dataset: str) -> PipelineJob: + return PipelineJob(name="experiment", database=SpiralDatabase(project_id, dataset)) +``` + +Call `make_job` with a project identifier and dataset you can write to, then bind +the steps the job will run. + + +```python +from orcapod import function_pod +from orcapod.sources import DictSource + -database = ConnectorArrowDatabase( - SpiralDBConnector("my-project-123456", "pipeline_results", writable=True) +@function_pod(output_keys="double") +def double_reading(reading: int) -> int: + return reading * 2 + + +readings = DictSource( + data=[{"sample_id": "s1", "reading": 3}], + tag_columns=["sample_id"], + tag_only_columns=True, + source_id="readings", ) -job = PipelineJob(name="experiment", database=database) +job = make_job("my-project-123456", "pipeline_results") +with job: + double_reading.pod(readings, label="double") ``` -Signing in is spiral-sdk's: the `SPIRAL_*` environment variables, or a saved -`spiral login`. Without `writable=True`, a `SpiralDBConnector` reads existing keyed tables -(a `SpiralDBTableSource`) and writes nothing. +Spiral-sdk signs in using the `SPIRAL_*` environment variables or a saved `spiral login`. +`SpiralDatabase` currently returns a `ConnectorArrowDatabase` backed by +`SpiralDBKeyedConnector`. It defaults to `writable=True` and passes options such as +`overrides` to the connector. Use `writable=False` to open the plain keyed layout. +The default backend may change in a later release. +Orcapod will announce any change one release ahead. Build the database with the explicit +connector to choose the keyed backend directly. Each stored table is one keyed table of the dataset, named from its path (a readable part of the path and a digest of all of it). Its metadata records the full path, the @@ -66,7 +93,7 @@ index from the service. ### Optional write lock -`SpiralDBConnector(..., write_lock=provider)` accepts a `WriteLock` provider +`SpiralDBKeyedConnector(..., write_lock=provider)` accepts a `WriteLock` provider from `orcapod.databases.write_lock`. `None` uses `NoWriteLock`, which performs no coordination across processes. When several connectors share a scope, give them the same custom provider. @@ -113,24 +140,28 @@ resolves the names it uses again, so a replacement between runs is picked up. ## Saving and loading a job -A job saved on the SpiralDB database records the connector (`connector_type`, project, -dataset, the service address and `writable: true`), never a credential. A connector is not rebuilt from -a saved file: give it again when loading, as for every connector database: +A job saved using `SpiralDatabase` records its concrete backend. A job on the keyed +backend records `connector_type: spiraldb_keyed` along with the project, dataset, +connection overrides and `writable: true`. It saves no credentials. A change to the +default backend leaves that saved configuration intact. Supply the recorded backend +when loading the job, using the explicit classes to select it directly. ```python +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector + loaded = PipelineJob.load( "experiment.json", database=ConnectorArrowDatabase( - SpiralDBConnector("my-project-123456", "pipeline_results", writable=True) + SpiralDBKeyedConnector("my-project-123456", "pipeline_results", writable=True) ), ) ``` -A job saved on the SpiralDB database is loaded with a writable connector, and one saved -on a plain -`SpiralDBConnector` with a plain one: the load refuses the other kind, since the two -read different tables. +Use a writable connector for a job saved with `writable=True` and a plain connector +for a job saved with a plain `SpiralDBKeyedConnector`. The two modes read different +tables. Loading a job saved with the retired `spiraldb` type raises an error naming +`spiraldb_keyed`. ## Limits diff --git a/docs/dev/design_issues/ITL-1162-CA3.md b/docs/dev/design_issues/ITL-1162-CA3.md index fcbdbca28..22bc79619 100644 --- a/docs/dev/design_issues/ITL-1162-CA3.md +++ b/docs/dev/design_issues/ITL-1162-CA3.md @@ -29,7 +29,7 @@ buffered. A function job node (its result table) and a side-effect job node (its log) ask the database when it is attached, so a job refuses them before anything runs, naming the node. An operator job node with a cache and a cached source ask about their bookkeeping columns (`__node_content_hash`, `__data_context`) when attached or built; their user columns -are checked at the write. `SpiralDBConnector` states its name rule the same way (developer +are checked at the write. `SpiralDBKeyedConnector` states its name rule the same way (developer ruling, November 16, 2026). `PostgreSQLConnector` also states which table names it holds (`unstorable_table_name_reason`, 63 bytes), checked at every table entry (`UnstorableTableNameError`). The connectors' silent TEXT fallback in `CREATE TABLE` now diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index dc2b40648..369749b02 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -56,7 +56,7 @@ A table keeps the order its database gave the first write (SpiralDB: its own ord SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores the key columns, then the value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; live: `TestColumnOrderLive` in -`tests/test_databases/test_spiraldb_connector_integration.py`. +`tests/test_databases/test_spiraldb_keyed_connector_integration.py`. Pre-existing on main and equal here, not changed: another connection that changes a SQLite table between the flush's check and its write (a DDL in that window) is not seen; a rename diff --git a/docs/dev/design_issues/ITL-936-SP3.md b/docs/dev/design_issues/ITL-936-SP3.md index 1161ccfc9..4ba748d07 100644 --- a/docs/dev/design_issues/ITL-936-SP3.md +++ b/docs/dev/design_issues/ITL-936-SP3.md @@ -1,4 +1,4 @@ -## `src/orcapod/databases/spiraldb_connector.py` — SpiralDB stores every column nullable (ITL-936) +## `src/orcapod/databases/spiraldb_keyed/connector.py` — SpiralDB stores every column nullable (ITL-936) ### SP3 — Non-nullable columns arrive as `T | None` from SpiralDB; a null in a non-null struct field is stored as 0 **Status:** in progress @@ -15,7 +15,7 @@ client. Writing `{k: 4, v: 40, g: {x: null, y: null}}` with `g.x` declared non-n **Fix:** Orcapod records each table's non-nullable paths in the table's key-value metadata (`__orcapod_nullability__`, format `orcapod.nullability` v1; `orcapod.databases. -write_nullability_record` / `read_nullability_record`). `SpiralDBConnector` writes the record +write_nullability_record` / `read_nullability_record`). `SpiralDBKeyedConnector` writes the record before the first rows of a table, checks every non-nullable path for nulls before any write, refuses a write that disagrees with the record, and on read restores the record in `get_column_info` and checks and restores every batch in `iter_batches` diff --git a/docs/dev/design_issues/PLT-1773-SP1.md b/docs/dev/design_issues/PLT-1773-SP1.md index 2ccd7f66c..2843f7618 100644 --- a/docs/dev/design_issues/PLT-1773-SP1.md +++ b/docs/dev/design_issues/PLT-1773-SP1.md @@ -15,7 +15,7 @@ Vortex file reads to return: AccessDenied: There were headers present in the request which were not signed ``` -All three `TestSpiralDBConnectorIntegration` tests failed on every CI push from +All three `TestSpiralDBKeyedConnectorIntegration` tests failed on every CI push from 2026-06-15 onward. The runner image version was identical between the last green and first red run, confirming this was a server-side enforcement change rather than a runner regression. diff --git a/docs/dev/design_issues/PLT-1795-CA1.md b/docs/dev/design_issues/PLT-1795-CA1.md index 0096304bb..6f9c5ea1b 100644 --- a/docs/dev/design_issues/PLT-1795-CA1.md +++ b/docs/dev/design_issues/PLT-1795-CA1.md @@ -14,7 +14,7 @@ back, the column is returned as the raw storage type (e.g. `large_string`, `larg **Interim fix (PLT-1659 / ITL-471):** `DBConnectorProtocol` now declares a `validate_records` hook. `SQLiteConnector` and `PostgreSQLConnector` implement it to reject extension-typed columns -at write time, surfacing the issue immediately rather than on a confusing read. `SpiralDBConnector` +at write time, surfacing the issue immediately rather than on a confusing read. `SpiralDBKeyedConnector` overrides it as a no-op because it preserves field metadata via the native KV store. Two representations are rejected by the SQL implementations: - In-memory extension types: `isinstance(field.type, pa.ExtensionType)`. diff --git a/docs/dev/plans/2026-03-26-postgresql-table-source.md b/docs/dev/plans/2026-03-26-postgresql-table-source.md index 5291990bf..6a7f81ea9 100644 --- a/docs/dev/plans/2026-03-26-postgresql-table-source.md +++ b/docs/dev/plans/2026-03-26-postgresql-table-source.md @@ -896,7 +896,7 @@ Expected: All tests PASS. ```bash pytest tests/ -v --ignore=tests/test_databases/test_postgresql_connector_integration.py \ --ignore=tests/test_databases/test_spiraldb_connector.py \ - --ignore=tests/test_databases/test_spiraldb_connector_integration.py \ + --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py \ -m "not postgres" ``` @@ -1204,7 +1204,7 @@ Run the full unit test suite one last time to confirm everything is clean. pytest tests/ -v \ --ignore=tests/test_databases/test_postgresql_connector_integration.py \ --ignore=tests/test_databases/test_spiraldb_connector.py \ - --ignore=tests/test_databases/test_spiraldb_connector_integration.py \ + --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py \ -m "not postgres" ``` diff --git a/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md b/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md index 537927681..230c3f652 100644 --- a/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md +++ b/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md @@ -3,7 +3,7 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use sensei:subagent-driven-development (recommended) or sensei:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Upgrade `pyspiral` from the broken `0.11.7` to `0.14.9` so that all three -`TestSpiralDBConnectorIntegration` tests pass green in CI again. +`TestSpiralDBKeyedConnectorIntegration` tests pass green in CI again. **Architecture:** Three targeted edits — bump the minimum version constraint in `pyproject.toml`, verify the `uv.lock` pin is at `0.14.9` (already updated during @@ -110,14 +110,14 @@ Closes PLT-1773" ### Task 2: Add breadcrumb to integration test module docstring **Files:** -- Modify: `tests/test_databases/test_spiraldb_connector_integration.py:1-19` +- Modify: `tests/test_databases/test_spiraldb_keyed_connector_integration.py:1-19` - [ ] **Step 1: Extend the module docstring** Replace the existing module docstring (lines 1–19) with: ```python -"""Integration tests for SpiralDBConnector against the live dev project. +"""Integration tests for SpiralDBKeyedConnector against the live dev project. These tests are skipped unless the ``SPIRAL_INTEGRATION_TESTS=1`` env var is set. They require a valid auth mechanism, either: @@ -155,12 +155,12 @@ using ``httpx``) resolved the issue. If these tests start failing with a similar - [ ] **Step 2: Verify the file still imports cleanly** ```bash -uv run python -c "import tests.test_databases.test_spiraldb_connector_integration" 2>&1 || \ +uv run python -c "import tests.test_databases.test_spiraldb_keyed_connector_integration" 2>&1 || \ uv run python -c " import importlib.util, sys spec = importlib.util.spec_from_file_location( 'test_mod', - 'tests/test_databases/test_spiraldb_connector_integration.py' + 'tests/test_databases/test_spiraldb_keyed_connector_integration.py' ) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) @@ -174,7 +174,7 @@ at module level is fine to execute). - [ ] **Step 3: Commit** ```bash -git add tests/test_databases/test_spiraldb_connector_integration.py +git add tests/test_databases/test_spiraldb_keyed_connector_integration.py git commit -m "docs(spiraldb): add PLT-1773 breadcrumb to integration test module docstring Explains the t3.storage.dev header-signing enforcement change (2026-06-15) @@ -214,7 +214,7 @@ Vortex file reads to return: AccessDenied: There were headers present in the request which were not signed ``` -All three `TestSpiralDBConnectorIntegration` tests failed on every CI push from +All three `TestSpiralDBKeyedConnectorIntegration` tests failed on every CI push from 2026-06-15 onward. The runner image version was identical between the last green and first red run, confirming this was a server-side enforcement change rather than a runner regression. @@ -233,7 +233,7 @@ covering routine version bumps. - [ ] **Step 2: Run a quick smoke test to confirm no other tests broke** ```bash -uv run pytest tests/test_databases/ -v --ignore=tests/test_databases/test_spiraldb_connector_integration.py +uv run pytest tests/test_databases/ -v --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py ``` Expected: all tests PASS (the integration tests are excluded since they require @@ -308,9 +308,9 @@ EOF The `spiral-integration` job runs on push (not on PRs), so it will fire when the branch is pushed. Watch the Actions tab for the run. Expected outcome: all three -`TestSpiralDBConnectorIntegration` tests PASS. +`TestSpiralDBKeyedConnectorIntegration` tests PASS. If they fail with a different error (not the unsigned-headers `AccessDenied`), the pyspiral 0.14.9 API may have a breaking change not caught by the static inspection. In that case, read the new error, identify which API call broke, and update -`spiraldb_connector.py` accordingly. +`spiraldb_keyed/connector.py` accordingly. diff --git a/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md b/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md index ee8eac306..9cb2be40a 100644 --- a/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md +++ b/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md @@ -4,7 +4,7 @@ **Goal:** Preserve Arrow table- and column-level metadata (including nested struct/list field metadata) across SpiralDB write/read cycles using the native KV store, and replace the blanket extension-type guard in `ConnectorArrowDatabase` with a per-connector `validate_records` hook. -**Architecture:** Four private helpers in `spiraldb_connector.py` handle recursive metadata serialization/deserialization. `upsert_records` writes metadata to the SpiralDB KV store after each data write; `iter_batches` reads and restores it per scan. `DBConnectorProtocol` gains an abstract `validate_records` method; each connector implements it (rejecting for SQLite/PostgreSQL, no-op for SpiralDB); `ConnectorArrowDatabase` delegates to it instead of applying its own guard. +**Architecture:** Four private helpers in `spiraldb_keyed/connector.py` handle recursive metadata serialization/deserialization. `upsert_records` writes metadata to the SpiralDB KV store after each data write; `iter_batches` reads and restores it per scan. `DBConnectorProtocol` gains an abstract `validate_records` method; each connector implements it (rejecting for SQLite/PostgreSQL, no-op for SpiralDB); `ConnectorArrowDatabase` delegates to it instead of applying its own guard. **Tech Stack:** PyArrow (`pa.Field`, `pa.DataType`, `pa.struct`, `pa.list_`, `pa.large_list`, `pa.fixed_size_list`), Python `base64` + `json` stdlib, pyspiral `Table.set_metadata` / `Table.get_metadata`, `unittest.mock`. @@ -14,7 +14,7 @@ | File | Action | What changes | |---|---|---| -| `src/orcapod/databases/spiraldb_connector.py` | Modify | Add 4 private helpers; modify `upsert_records` and `iter_batches`; add `validate_records` no-op | +| `src/orcapod/databases/spiraldb_keyed/connector.py` | Modify | Add 4 private helpers; modify `upsert_records` and `iter_batches`; add `validate_records` no-op | | `src/orcapod/protocols/db_connector_protocol.py` | Modify | Add abstract `validate_records` method | | `src/orcapod/databases/sqlite_connector.py` | Modify | Add rejecting `validate_records` method | | `src/orcapod/databases/postgresql_connector.py` | Modify | Add rejecting `validate_records` method | @@ -22,7 +22,7 @@ | `tests/test_databases/test_spiraldb_metadata_helpers.py` | Create | Pure-function tests for the 4 helpers | | `tests/test_databases/test_spiraldb_connector.py` | Modify | Add `TestUpsertRecordsMetadata`, `TestIterBatchesMetadata`, `TestValidateRecords` | | `tests/test_databases/test_connector_arrow_database.py` | Modify | Update `MockDBConnector` + `TestExtensionTypeWriteGuard` | -| `tests/test_databases/test_spiraldb_connector_integration.py` | Modify | Add `TestArrowMetadataRoundTrip` | +| `tests/test_databases/test_spiraldb_keyed_connector_integration.py` | Modify | Add `TestArrowMetadataRoundTrip` | --- @@ -30,7 +30,7 @@ - **Run all Python via `uv run`** — never call `python` or `pytest` directly. - **Branch:** `eywalker/itl-471-spiraldbconnector-preserve-arrow-table-and-column-level` -- **`_ARROW_METADATA_KEY = "__arrow_metadata__"`** — the single reserved KV key; define it as a module-level constant in `spiraldb_connector.py`. +- **`_ARROW_METADATA_KEY = "__arrow_metadata__"`** — the single reserved KV key; define it as a module-level constant in `spiraldb_keyed/connector.py`. - **`validate_records` inheritance:** Connectors do NOT inherit from `DBConnectorProtocol` (structural subtyping only). The abstract method on the Protocol is for documentation/type checking. Each connector must implement it explicitly. `MockDBConnector` in the test file also needs it. - **`field.with_type(new_type)`** — use this PyArrow method to create a new `pa.Field` with a different type but same name, nullability, and metadata. Check if it exists; if not, use `pa.field(f.name, new_type, f.nullable, f.metadata)`. - **`pa.fixed_size_list`** — `pa.fixed_size_list(value_type_or_field, list_size)`. Use `arrow_type.list_size` for the size. @@ -67,7 +67,7 @@ Expected: all pass (integration tests skipped). Note the count — it's the base **Files:** - Create: `tests/test_databases/test_spiraldb_metadata_helpers.py` -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` ### Step 1: Write failing tests for `_serialize_field_meta_tree` @@ -83,7 +83,7 @@ import json import pyarrow as pa import pytest -from orcapod.databases.spiraldb_connector import ( +from orcapod.databases.spiraldb_keyed.connector import ( _ARROW_METADATA_KEY, _load_arrow_metadata, _restore_field, @@ -247,7 +247,7 @@ Expected: `ImportError` or `ModuleNotFoundError` — helpers don't exist yet. - [ ] **Step 3: Implement `_ARROW_METADATA_KEY`, `_serialize_field_meta_tree`, `_serialize_arrow_metadata`** -Add immediately after the existing module-level `logger = logging.getLogger(__name__)` line in `src/orcapod/databases/spiraldb_connector.py`: +Add immediately after the existing module-level `logger = logging.getLogger(__name__)` line in `src/orcapod/databases/spiraldb_keyed/connector.py`: ```python import base64 @@ -353,7 +353,7 @@ Expected: all pass. - [ ] **Step 5: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_metadata_helpers.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_metadata_helpers.py git commit -m "feat(spiraldb): add _serialize_field_meta_tree and _serialize_arrow_metadata helpers (ITL-471)" ``` @@ -363,7 +363,7 @@ git commit -m "feat(spiraldb): add _serialize_field_meta_tree and _serialize_arr **Files:** - Modify: `tests/test_databases/test_spiraldb_metadata_helpers.py` (append new test classes) -- Modify: `src/orcapod/databases/spiraldb_connector.py` (append new helpers) +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` (append new helpers) - [ ] **Step 1: Write failing tests for `_load_arrow_metadata` and `_restore_field`** @@ -522,7 +522,7 @@ Expected: `ImportError` — `_load_arrow_metadata` and `_restore_field` not defi - [ ] **Step 3: Implement `_load_arrow_metadata`, `_restore_arrow_type`, and `_restore_field`** -Append to `src/orcapod/databases/spiraldb_connector.py` (after `_serialize_arrow_metadata`): +Append to `src/orcapod/databases/spiraldb_keyed/connector.py` (after `_serialize_arrow_metadata`): ```python def _load_arrow_metadata( @@ -669,7 +669,7 @@ Expected: all pass. - [ ] **Step 5: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_metadata_helpers.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_metadata_helpers.py git commit -m "feat(spiraldb): add _load_arrow_metadata and _restore_field helpers (ITL-471)" ``` @@ -681,7 +681,7 @@ git commit -m "feat(spiraldb): add _load_arrow_metadata and _restore_field helpe - Modify: `src/orcapod/protocols/db_connector_protocol.py` - Modify: `src/orcapod/databases/sqlite_connector.py` - Modify: `src/orcapod/databases/postgresql_connector.py` -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` - Modify: `src/orcapod/databases/connector_arrow_database.py` - Modify: `tests/test_databases/test_connector_arrow_database.py` - Modify: `tests/test_databases/test_spiraldb_connector.py` @@ -693,7 +693,7 @@ git commit -m "feat(spiraldb): add _load_arrow_metadata and _restore_field helpe ```python class TestValidateRecords: def test_no_op_for_plain_columns(self, connector): - """validate_records is a no-op on SpiralDBConnector for plain columns.""" + """validate_records is a no-op on SpiralDBKeyedConnector for plain columns.""" table = pa.table({ "id": pa.array([b"a"], type=pa.large_binary()), "value": pa.array([1], type=pa.int64()), @@ -701,7 +701,7 @@ class TestValidateRecords: connector.validate_records(table) # must not raise def test_no_op_for_extension_typed_columns(self, connector): - """SpiralDBConnector.validate_records allows extension-typed columns.""" + """SpiralDBKeyedConnector.validate_records allows extension-typed columns.""" ext_field = pa.field( "payload", pa.large_string(), @@ -758,7 +758,7 @@ Add a new test at the end of `TestExtensionTypeWriteGuard`: uv run pytest tests/test_databases/test_spiraldb_connector.py::TestValidateRecords tests/test_databases/test_connector_arrow_database.py::TestExtensionTypeWriteGuard::test_permissive_connector_allows_extension_types -v --tb=short ``` -Expected: `AttributeError: 'SpiralDBConnector' object has no attribute 'validate_records'` +Expected: `AttributeError: 'SpiralDBKeyedConnector' object has no attribute 'validate_records'` - [ ] **Step 3: Add `validate_records` to `DBConnectorProtocol`** @@ -860,13 +860,13 @@ In `src/orcapod/databases/postgresql_connector.py`, add after the `upsert_record ) ``` -- [ ] **Step 6: Add no-op `validate_records` to `SpiralDBConnector`** +- [ ] **Step 6: Add no-op `validate_records` to `SpiralDBKeyedConnector`** -In `src/orcapod/databases/spiraldb_connector.py`, add after the `upsert_records` method (before `def close`): +In `src/orcapod/databases/spiraldb_keyed/connector.py`, add after the `upsert_records` method (before `def close`): ```python def validate_records(self, records: "pa.Table") -> None: - """No-op: ``SpiralDBConnector`` preserves Arrow field metadata via the native KV store.""" + """No-op: ``SpiralDBKeyedConnector`` preserves Arrow field metadata via the native KV store.""" ``` - [ ] **Step 7: Add `validate_records` to `MockDBConnector` in the test file** @@ -957,7 +957,7 @@ git add \ src/orcapod/protocols/db_connector_protocol.py \ src/orcapod/databases/sqlite_connector.py \ src/orcapod/databases/postgresql_connector.py \ - src/orcapod/databases/spiraldb_connector.py \ + src/orcapod/databases/spiraldb_keyed/connector.py \ src/orcapod/databases/connector_arrow_database.py \ tests/test_databases/test_connector_arrow_database.py \ tests/test_databases/test_spiraldb_connector.py @@ -970,7 +970,7 @@ git commit -m "feat(spiraldb): add per-connector validate_records hook, replace **Files:** - Modify: `tests/test_databases/test_spiraldb_connector.py` (append new test class) -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` - [ ] **Step 1: Write failing tests** @@ -1071,7 +1071,7 @@ Expected: `AssertionError` — `set_metadata` not called (feature not implemente - [ ] **Step 3: Modify `upsert_records` to write metadata** -In `src/orcapod/databases/spiraldb_connector.py`, find the `upsert_records` method. The current structure is: +In `src/orcapod/databases/spiraldb_keyed/connector.py`, find the `upsert_records` method. The current structure is: ```python if not skip_existing: @@ -1129,7 +1129,7 @@ Expected: all pass. - [ ] **Step 5: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_connector.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_connector.py git commit -m "feat(spiraldb): persist Arrow metadata in upsert_records via KV store (ITL-471)" ``` @@ -1139,7 +1139,7 @@ git commit -m "feat(spiraldb): persist Arrow metadata in upsert_records via KV s **Files:** - Modify: `tests/test_databases/test_spiraldb_connector.py` (append new test class) -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` - [ ] **Step 1: Write failing tests** @@ -1232,7 +1232,7 @@ Expected: `AssertionError` — metadata not reattached (feature not implemented) - [ ] **Step 3: Modify `iter_batches` to restore metadata** -In `src/orcapod/databases/spiraldb_connector.py`, find `iter_batches`. Replace the body starting from `table_name = _parse_table_name(query)` onward: +In `src/orcapod/databases/spiraldb_keyed/connector.py`, find `iter_batches`. Replace the body starting from `table_name = _parse_table_name(query)` onward: ```python table_name = _parse_table_name(query) @@ -1295,7 +1295,7 @@ Expected: all pass (integration tests skipped). - [ ] **Step 6: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_connector.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_connector.py git commit -m "feat(spiraldb): restore Arrow metadata in iter_batches via recursive _restore_field (ITL-471)" ``` @@ -1304,11 +1304,11 @@ git commit -m "feat(spiraldb): restore Arrow metadata in iter_batches via recurs ## Task 7: Integration tests **Files:** -- Modify: `tests/test_databases/test_spiraldb_connector_integration.py` +- Modify: `tests/test_databases/test_spiraldb_keyed_connector_integration.py` - [ ] **Step 1: Append `TestArrowMetadataRoundTrip` class** -Append to `tests/test_databases/test_spiraldb_connector_integration.py`: +Append to `tests/test_databases/test_spiraldb_keyed_connector_integration.py`: ```python class TestArrowMetadataRoundTrip: @@ -1521,7 +1521,7 @@ class TestArrowMetadataRoundTrip: - [ ] **Step 2: Verify integration tests are skipped (no credentials)** ```bash -uv run pytest tests/test_databases/test_spiraldb_connector_integration.py -v --tb=short +uv run pytest tests/test_databases/test_spiraldb_keyed_connector_integration.py -v --tb=short ``` Expected: all skipped (`Set SPIRAL_INTEGRATION_TESTS=1 to run SpiralDB integration tests`). @@ -1529,7 +1529,7 @@ Expected: all skipped (`Set SPIRAL_INTEGRATION_TESTS=1 to run SpiralDB integrati - [ ] **Step 3: Commit** ```bash -git add tests/test_databases/test_spiraldb_connector_integration.py +git add tests/test_databases/test_spiraldb_keyed_connector_integration.py git commit -m "test(spiraldb): add TestArrowMetadataRoundTrip integration tests (ITL-471)" ``` @@ -1540,7 +1540,7 @@ git commit -m "test(spiraldb): add TestArrowMetadataRoundTrip integration tests - [ ] **Step 1: Run the complete unit test suite** ```bash -uv run pytest tests/ -v --tb=short -q --ignore=tests/test_databases/test_spiraldb_connector_integration.py +uv run pytest tests/ -v --tb=short -q --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py ``` Expected: all pass. @@ -1572,7 +1572,7 @@ git push -u origin eywalker/itl-471-spiraldbconnector-preserve-arrow-table-and-c | `validate_records` on `DBConnectorProtocol` | Task 4 | | `SQLiteConnector.validate_records` rejecting | Task 4 | | `PostgreSQLConnector.validate_records` rejecting | Task 4 | -| `SpiralDBConnector.validate_records` no-op | Task 4 | +| `SpiralDBKeyedConnector.validate_records` no-op | Task 4 | | `ConnectorArrowDatabase` guard replaced | Task 4 | | Schema metadata integration test | Task 7 | | Field metadata integration test | Task 7 | diff --git a/docs/dev/plans/2026-11-09-v0.2-release-checklist.md b/docs/dev/plans/2026-11-09-v0.2-release-checklist.md index 15aa233b0..3539ec439 100644 --- a/docs/dev/plans/2026-11-09-v0.2-release-checklist.md +++ b/docs/dev/plans/2026-11-09-v0.2-release-checklist.md @@ -486,7 +486,7 @@ The 16 skips: - 7 in `tests/test_databases/test_delta_table_database_s3.py` — MinIO container could not be started (no Docker here; skipped in CI too, ITL-819). -- 9 in `tests/test_databases/test_spiraldb_connector_integration.py` — need +- 9 in `tests/test_databases/test_spiraldb_keyed_connector_integration.py` — need `SPIRAL_INTEGRATION_TESTS=1` and credentials. The 77 deselected are the `postgres`-marked tests, which the Release workflow also diff --git a/docs/dev/plans/2026-11-11-itl-926-spiral-source-reverify.md b/docs/dev/plans/2026-11-11-itl-926-spiral-source-reverify.md index 11c5684ca..48f67acda 100644 --- a/docs/dev/plans/2026-11-11-itl-926-spiral-source-reverify.md +++ b/docs/dev/plans/2026-11-11-itl-926-spiral-source-reverify.md @@ -8,7 +8,7 @@ The coordinator's brief is the spec. Phase 1 needs no SpiralDB credentials. ## Phase 1 — audit, fake, end-to-end, pyspiral, live-run kit (no code changes to `src/`) -1. **Audit (A).** Read `spiraldb_table_source.py`, `db_table_source.py`, `spiraldb_connector.py`, +1. **Audit (A).** Read `spiraldb_table_source.py`, `db_table_source.py`, `spiraldb_keyed/connector.py`, `connector_arrow_database.py`, `db_connector_protocol.py`, `pipeline/serialization.py` against CLAUDE.md "Arrow types". Run the mocked unit tests (`tests/test_core/sources/test_spiraldb_table_source.py`, diff --git a/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md b/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md index cfe6c8241..40119630b 100644 --- a/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md +++ b/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md @@ -8,9 +8,9 @@ records each table's non-nullable column paths in the table's key-value metadata when it writes, restores them on read, and checks every batch, so recorded columns arrive as `T`. -**Architecture:** A pure module `orcapod/databases/spiraldb_nullability.py` (no pyspiral import) +**Architecture:** A pure module `orcapod/databases/spiraldb_keyed/nullability.py` (no pyspiral import) encodes/decodes a versioned, chunked JSON record, applies it to an Arrow schema and checks a -batch against it. `SpiralDBConnector` calls it in `upsert_records` (write the record on a +batch against it. `SpiralDBKeyedConnector` calls it in `upsert_records` (write the record on a table's first write, refuse a disagreeing later write, refuse nulls in non-null paths before anything is written), `get_column_info` (schema) and `iter_batches` (check + restore per batch), wrapping errors with project/dataset/table. Tables without a record are untouched. @@ -86,7 +86,7 @@ into a struct of null fields ("SpiralDB doesn't allow struct-level nullability") -> dict[str, bytes]`; any writer does `table.set_metadata(nullability_record_metadata(schema))` with the Arrow schema it writes. `orcapod.databases.read_nullability_record(metadata) -> frozenset[tuple[str, ...]] | None` reads it back (for `verify`). -* `SpiralDBConnector.upsert_records(records)`: +* `SpiralDBKeyedConnector.upsert_records(records)`: 1. Check `records` has no null in any non-null path (else `NullInNonNullableColumnError`, nothing written: SpiralDB would store `0` in a struct field). 2. Table has a record: the incoming schema's non-null paths must equal it, else @@ -155,12 +155,12 @@ if read_nullability_record(table.get_metadata()) != read_nullability_record(kv): ## File structure -* Create `src/orcapod/databases/spiraldb_nullability.py`: record encode/decode, schema apply, +* Create `src/orcapod/databases/spiraldb_keyed/nullability.py`: record encode/decode, schema apply, batch enforce. Pure pyarrow. * Modify `src/orcapod/errors.py`: `NullabilityRecordError`, `NullabilityRecordMismatchError`, `NullInNonNullableColumnError` (all `ValueError` subclasses; the last two carry `column`/`table` attributes). -* Modify `src/orcapod/databases/spiraldb_connector.py`: write/read integration. +* Modify `src/orcapod/databases/spiraldb_keyed/connector.py`: write/read integration. * Modify `src/orcapod/databases/__init__.py`: export the two public helpers. * Modify `tests/test_databases/fake_pyspiral.py`: server nullability behaviour. * Tests: `tests/test_databases/test_spiraldb_nullability.py` (helpers), @@ -188,7 +188,7 @@ if read_nullability_record(table.get_metadata()) != read_nullability_record(kv): chunk; digest mismatch; 400-column table splits into chunks each ≤ 8 KiB; map item non-null raises; apply to schema; path absent from schema raises; enforce: null at top level, in a struct field, in a list item raises with the dotted column path; clean batch is cast. -- [ ] Implement `spiraldb_nullability.py` and the errors. Commit. +- [ ] Implement `spiraldb_keyed/nullability.py` and the errors. Commit. ### Task 2: Connector write path (TDD on the fake) @@ -205,7 +205,7 @@ if read_nullability_record(table.get_metadata()) != read_nullability_record(kv): ### Task 4: Source end to end -- [ ] Rewrite `TestNonNullableColumns` to write through `SpiralDBConnector` (record) and show: +- [ ] Rewrite `TestNonNullableColumns` to write through `SpiralDBKeyedConnector` (record) and show: `T` schema, pod `x: float`/`int` runs, Join, save/load. Unrecorded table: pod refused. - [ ] Unrecorded table hashes pinned by explicit values (computed before the change). - [ ] `TestSourceId.test_explicit_source_id_keeps_its_hashes`: the table written through the diff --git a/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md b/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md index 9081c608e..d542e5b32 100644 --- a/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md +++ b/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md @@ -39,7 +39,7 @@ pyspiral fake, which gains a scan log. |---|---| | `tests/test_databases/fake_pyspiral.py` | fake: scan log, lazy batches, `limit` (Phase A); `where`, `asof`, `table_id`, `last_modified_at`, row count (Phase B) | | `tests/test_core/sources/test_spiraldb_table_source_streaming.py` | new: streaming behaviour through the public interface | -| `src/orcapod/databases/spiraldb_connector.py` | Phase B: metadata-only reads and a restricted scan | +| `src/orcapod/databases/spiraldb_keyed/connector.py` | Phase B: metadata-only reads and a restricted scan | | `src/orcapod/core/sources/spiraldb_table_source.py` | Phase B: the source | | `docs/concepts/sources.md`, `changelog.d/ITL-186.md`, `design_issues/ITL-186-SP4.md` | Phase B | diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md index de7f31bdd..4b3bea8bc 100644 --- a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -4,7 +4,7 @@ Stage A of using SpiralDB as a job's pipeline and result database (ITL-1446). It the still-valid parts of PRs 589 (ITL-1495) and 590 (ITL-1497) onto current `main`, and the manifest-in-metadata part of PR 595 (ITL-1498). Those branches were sources to copy from; none is merged. Nothing here is public: no way to open a store exists, and -`SpiralDBConnector` still refuses every write (`SpiralDBWriteNotSupportedError`). +`SpiralDBKeyedConnector` still refuses every write (`SpiralDBWriteNotSupportedError`). ## The store format is provisional @@ -33,7 +33,7 @@ keyed tables deprecated: `Client.keyed_table`, `keyed_table_by_id` and DeprecationWarning, stacklevel=3)`, so the warning is attributed to the module that calls the SDK. 0.16.80 changes nothing else Orcapod uses (it removes the duration types, which the store already refuses). Orcapod's only module that opens or creates keyed tables is -`orcapod.databases.spiraldb_connector` (the schema migration script opens and creates +`orcapod.databases.spiraldb_keyed.connector` (the schema migration script opens and creates through its helpers `_open_keyed_table` and `_create_keyed_table`); before each open or creation it puts one filter FIRST in the filter list: action `ignore`, that exact message, `DeprecationWarning`, and that module only (`_ignore_keyed_table_deprecation`). First, not @@ -133,7 +133,7 @@ round trip of every other row in one manifest pass. ## What is left (later stages of ITL-1446) -Store mode in `SpiralDBConnector` and `ConnectorArrowDatabase` (create on first write, find +Store mode in `SpiralDBKeyedConnector` and `ConnectorArrowDatabase` (create on first write, find by name, the identity and manifest checks, data-context checks, listing for stale layouts), the write rules of ITL-1386 for the store, the one-writer lease, the public switch-on with save and load, and every table kind end to end. diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index af817cf75..320232613 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -8,8 +8,8 @@ collides with `main`'s SQL store catalog (`_sql_store.py`, ITL-1552) and is not Its `spiraldb_store_tables.py` and its tests are. Nothing is public. The store mode is a private constructor argument, -`SpiralDBConnector(project, dataset, _store=True)`, read and written only through -`ConnectorArrowDatabase`. A plain `SpiralDBConnector` behaves as on `main`: it reads and +`SpiralDBKeyedConnector(project, dataset, _store=True)`, read and written only through +`ConnectorArrowDatabase`. A plain `SpiralDBKeyedConnector` behaves as on `main`: it reads and refuses every write (`SpiralDBWriteNotSupportedError`). ## Structure @@ -19,7 +19,7 @@ refuses every write (`SpiralDBWriteNotSupportedError`). `store_table_names.require_store_path_domain`, the one path domain the identity record and the manifest apply). Each table's metadata holds its identity record and manifest, written in one upsert before its first rows. Rows go through the codec (`spiral_store`). -- `SpiralDBConnector` builds a `StoreTables` when `_store=True`, hands it out through the +- `SpiralDBKeyedConnector` builds a `StoreTables` when `_store=True`, hands it out through the private `_store_tables()`, and in store mode refuses raw access (`lookup_table`, `iter_batches`, `get_table_names` and every read built on them) with a `ValueError`. Its protocol write methods still raise `SpiralDBWriteNotSupportedError`. `to_config` refuses @@ -27,10 +27,10 @@ refuses every write (`SpiralDBWriteNotSupportedError`). - `ConnectorArrowDatabase` gets an internal store branch beside `_sql_store`: naming, finding, reading, the stored-id check, listing, column info, the stored schema, the storable-column check, validation and the write go to `StoreTables` when the connector - is a store-mode `SpiralDBConnector`. `DBConnectorProtocol` is unchanged. + is a store-mode `SpiralDBKeyedConnector`. `DBConnectorProtocol` is unchanged. The branch is taken only for a store-mode connector. For every other connector, the -plain `SpiralDBConnector` included, the code paths are `main`'s, with one exception: a +plain `SpiralDBKeyedConnector` included, the code paths are `main`'s, with one exception: a lookup of committed rows (`get_record_by_id`, `get_all_records` and the reads built on them) now raises `OrcapodDatabaseReadError` on every connector when finding or reading the stored table fails, as `get_table_schema` already did. For example, a SQLite @@ -106,7 +106,7 @@ the stored table fails, as `get_table_schema` already did. For example, a SQLite ## Finding a table, and what is kept - Every keyed table the store opens (by name or by id) or creates is opened or created by - `spiraldb_connector` (`_open_keyed_table`, `_open_keyed_table_by_id`, + `spiraldb_keyed.connector` (`_open_keyed_table`, `_open_keyed_table_by_id`, `_create_keyed_table`), handed to `StoreTables` as callables: spiral-sdk 0.16.79 and later warn on every keyed-table call, attributed to the calling module, and Orcapod ignores that warning for that module's own calls only (stage A, `_ignore_keyed_table_deprecation`). diff --git a/docs/dev/plans/itl-998-plan.md b/docs/dev/plans/itl-998-plan.md index 536f41c43..e6e1a1518 100644 --- a/docs/dev/plans/itl-998-plan.md +++ b/docs/dev/plans/itl-998-plan.md @@ -52,9 +52,9 @@ ITL-1477, stays an isolated addition: one gate, one function and their tests, li `filter` (the docstring names ITL-1477 for floats; the error text does not). The sentence calling a range of the first key columns "the cheapest to read" is removed (not measured). -### `src/orcapod/databases/spiraldb_connector.py` +### `src/orcapod/databases/spiraldb_keyed/connector.py` -- The `where` parameter of `SpiralDBConnector.scan_batches` is PROVISIONAL and takes the source's +- The `where` parameter of `SpiralDBKeyedConnector.scan_batches` is PROVISIONAL and takes the source's `Condition` (its terms are the one list of `(column, operator, value)`) instead of a mapping; done this way rather than a new `terms=` argument, since `Condition` is the one restriction class. One loop builds the predicate: an equality as today (`_literal`; a `float16` equality still @@ -111,7 +111,7 @@ dicts, which ignore order, so they keep passing; one new test compares the JSON - `tests/test_core/sources/test_spiraldb_table_source_live.py` (`ORCAPOD_SPIRALDB_TEST_PROJECT`, read-only): a window, and a window with an equality, equal the local selection of the full read; record ids a subset; arguments reversed; `limit`; `head`; an empty window. -- `tests/test_databases/test_spiraldb_connector_integration.py` (`SPIRAL_INTEGRATION_TESTS`, writes its own +- `tests/test_databases/test_spiraldb_keyed_connector_integration.py` (`SPIRAL_INTEGRATION_TESTS`, writes its own tables and drops them): the kept form of the conformance probe for every type of section 2, against pyarrow, plus the float order the service uses (so a change in it shows, and ITL-1477 starts from it), run on the final code before ready (D12). The fake runs the same cases. @@ -146,7 +146,7 @@ Run locally: the touched test files only, one pytest process; ruff, ruff format, section 5 table; the tests above cover each point (a restricted copy given a connector, tokens of a window, bounded views, async rows, spool staleness, certificates, repeated keys inside a window). Whichever lands after ITL-998 runs those tests on its own head. -- 553 and 554 (other drafts of ITL-1457) conflict in `spiraldb_connector.py`, in the scan's predicate lines; the +- 553 and 554 (other drafts of ITL-1457) conflict in `spiraldb_keyed/connector.py`, in the scan's predicate lines; the one that lands second resolves it. - 576 (ITL-1465): no text conflict; merged in only through `main`. diff --git a/docs/dev/scripts/itl_1371_logical_identity_appends.py b/docs/dev/scripts/itl_1371_logical_identity_appends.py index b874d36a9..a8105f52a 100644 --- a/docs/dev/scripts/itl_1371_logical_identity_appends.py +++ b/docs/dev/scripts/itl_1371_logical_identity_appends.py @@ -25,7 +25,7 @@ from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase -from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector from orcapod.databases.sqlite_connector import SQLiteConnector NAME = b"ARROW:extension:name" @@ -117,7 +117,7 @@ def open_db(kind: str, root: Path): if kind == "SQLite": return ConnectorArrowDatabase(SQLiteConnector(str(root / "s.db"))) if kind == "SpiralDB": - return ConnectorArrowDatabase(SpiralDBConnector("p")) + return ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) raise AssertionError(kind) @@ -149,7 +149,9 @@ def main() -> None: warnings.simplefilter("ignore") kinds = ["in-memory", "Delta", "SQLite", "SpiralDB"] with tempfile.TemporaryDirectory() as tmp: - from tests.test_databases import fake_pyspiral # pyright: ignore[reportAttributeAccessIssue] # historical: ran on the pyspiral fake, removed in ITL-1186 + from tests.test_databases import ( + fake_pyspiral, # pyright: ignore[reportAttributeAccessIssue] # historical: ran on the pyspiral fake, removed in ITL-1186 + ) with fake_pyspiral.install(Path(tmp) / "spiral"): fake_pyspiral.FakeSpiral().project("p") diff --git a/docs/dev/scripts/itl_1844_database_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py index 4abf5220c..555fed732 100644 --- a/docs/dev/scripts/itl_1844_database_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -47,16 +47,15 @@ from orcapod.databases import ( # noqa: E402 ConnectorArrowDatabase, DeltaTableDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) -from orcapod.databases.spiral_database_identity import spiral_table_name # noqa: E402 +from orcapod.databases.spiraldb_keyed.identity import spiral_table_name # noqa: E402 +from orcapod.databases.spiraldb_keyed.write_scope import database_writes # noqa: E402 from orcapod.errors import SpiralDBScopeOpenError # noqa: E402 -from orcapod.databases.spiraldb_write_scope import database_writes # noqa: E402 from orcapod.side_effects import SideEffectPod, sink_pod # noqa: E402 from orcapod.sources import ArrowTableSource # noqa: E402 from orcapod.types import CacheMode # noqa: E402 - VOLATILE = { "__data_id", "__pipeline_record_id", @@ -210,7 +209,7 @@ def evaluate( def spiral_db() -> ConnectorArrowDatabase: return ConnectorArrowDatabase( - SpiralDBConnector(project, dataset, writable=True) + SpiralDBKeyedConnector(project, dataset, writable=True) ) delta = DeltaTableDatabase(work / "delta") @@ -371,7 +370,7 @@ def database_tables(project: str, dataset: str, stamp: str) -> list[dict[str, st dataset holds a table of another table format under a database table name. """ spiral_db = ConnectorArrowDatabase( - SpiralDBConnector(project, dataset, writable=True) + SpiralDBKeyedConnector(project, dataset, writable=True) ) every = sorted( path diff --git a/docs/dev/scripts/itl_1903/rename.py b/docs/dev/scripts/itl_1903/rename.py new file mode 100644 index 000000000..f88d980e4 --- /dev/null +++ b/docs/dev/scripts/itl_1903/rename.py @@ -0,0 +1,252 @@ +"""Apply the keyed SpiralDB rename from a checkout, including after a merge. + +Run with `uv run python docs/dev/scripts/itl_1903/rename.py` and review the diff. +Run Ruff's import and format checks after applying it. Re-running the script +leaves previously renamed files alone and updates references added upstream. +""" + +from __future__ import annotations + +import os +import re +import subprocess +from pathlib import Path + +DATABASES = Path("src/orcapod/databases") +KEYED_MODULES = { + "spiraldb_connector": "connector", + "spiraldb_nullability": "nullability", + "spiraldb_schema_table": "schema_table", + "spiraldb_sign_in": "sign_in", + "spiraldb_tables": "tables", + "spiraldb_writable_registry": "writable_registry", + "spiraldb_write_scope": "write_scope", + "spiral_database_identity": "identity", +} +# The lease may be deleted upstream. Its successor and the shared codec also +# retain their generic module paths. +GENERIC_MODULES = ("spiral_database_codec", "spiraldb_lease", "write_lock") +MOVES = { + **{ + DATABASES / f"{old}.py": DATABASES / "spiraldb_keyed" / f"{new}.py" + for old, new in KEYED_MODULES.items() + }, + Path("docs/concepts/spiraldb-database.md"): Path( + "docs/concepts/spiraldb-keyed-database.md" + ), + Path("tests/test_databases/test_spiraldb_connector_integration.py"): Path( + "tests/test_databases/test_spiraldb_keyed_connector_integration.py" + ), +} +TEXT_ROOTS = {"src", "tests", "scripts", "docs", "changelog.d"} +TEXT_SUFFIXES = {".py", ".md"} +EXTRA_TEXT = { + Path(".github/workflows/run-tests.yml"), + Path("site/astro.config.mjs"), + Path("CLAUDE.md"), + Path("RELEASING.md"), + Path(".zed/rules"), +} +LEGACY_CONNECTOR_REFERENCES = ( + "orcapod.databases.spiraldb_connector", + "SpiralDBConnector", +) +LEGACY_GUIDE_REFERENCES = ("'/concepts/spiraldb-database':",) +# The cross-version dry run and the old guide redirect still use these names. +PRESERVED_REFERENCES = { + Path("scripts/migrate_spiral_schemas.py"): LEGACY_CONNECTOR_REFERENCES, + Path("tests/test_databases/test_migrate_spiral_schemas.py"): ( + LEGACY_CONNECTOR_REFERENCES + ), + Path("site/astro.config.mjs"): LEGACY_GUIDE_REFERENCES, + Path("tests/test_docs/test_site_content.py"): LEGACY_GUIDE_REFERENCES, +} +BASELINE = Path(".basedpyright/baseline.json") +SCRIPT_DIR = Path("docs/dev/scripts/itl_1903") +RENAME_FRAGMENT = Path("changelog.d/ITL-1903.md") +REPLACEMENTS = ( + ("SpiralDBConnector", "SpiralDBKeyedConnector"), + ('"connector_type": "spiraldb"', '"connector_type": "spiraldb_keyed"'), + ('"postgresql", "spiraldb")', '"postgresql", "spiraldb_keyed")'), + ('``"postgresql"``, ``"spiraldb"``', '``"postgresql"``, ``"spiraldb_keyed"``'), + ('``"postgresql"`` or ``"spiraldb"``', '``"postgresql"`` or ``"spiraldb_keyed"``'), + ( + 'connector_type`` is not ``"spiraldb"``', + 'connector_type`` is not ``"spiraldb_keyed"``', + ), + ( + 'config.get("connector_type") != "spiraldb"', + 'config.get("connector_type") != "spiraldb_keyed"', + ), + ("Expected connector_type 'spiraldb'", "Expected connector_type 'spiraldb_keyed'"), + ( + 'saved_connector_kind(config) != "spiraldb"', + 'saved_connector_kind(config) != "spiraldb_keyed"', + ), + ("# SpiralDB as a Job's", "# Keyed SpiralDB as a Job's"), + ("[SpiralDB as a Job's", "[Keyed SpiralDB as a Job's"), + (r"page('SpiralDB as a Job\'s", r"page('Keyed SpiralDB as a Job\'s"), + ("spiraldb-database", "spiraldb-keyed-database"), + ( + "test_spiraldb_connector_integration.py", + "test_spiraldb_keyed_connector_integration.py", + ), + ( + "tests.test_databases.test_spiraldb_connector_integration", + "tests.test_databases.test_spiraldb_keyed_connector_integration", + ), + ("from .spiraldb_connector import ", "from .spiraldb_keyed.connector import "), + ( + "from orcapod.databases import SpiralDBKeyedConnector, spiraldb_connector", + "from orcapod.databases import SpiralDBKeyedConnector\n" + "from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector", + ), + ( + "from orcapod.databases import ConnectorArrowDatabase, spiraldb_connector", + "from orcapod.databases import ConnectorArrowDatabase\n" + "from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector", + ), + ( + "from orcapod.databases import spiraldb_connector, spiraldb_lease", + "from orcapod.databases import spiraldb_lease\n" + "from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector", + ), + ( + "from orcapod.databases import spiraldb_lease, spiraldb_write_scope", + "from orcapod.databases import spiraldb_lease\n" + "from orcapod.databases.spiraldb_keyed import write_scope as spiraldb_write_scope", + ), + ( + " spiraldb_connector,\n" + " spiraldb_lease,\n" + " spiraldb_writable_registry,\n" + " spiraldb_write_scope,\n" + ")", + " spiraldb_lease,\n" + ")\n" + "from orcapod.databases.spiraldb_keyed import (\n" + " connector as spiraldb_connector,\n" + " writable_registry as spiraldb_writable_registry,\n" + " write_scope as spiraldb_write_scope,\n" + ")", + ), +) + + +def git(*args: str) -> str: + return subprocess.run( + ["git", *args], check=True, stdout=subprocess.PIPE, text=True + ).stdout + + +def move_files() -> None: + for old, new in MOVES.items(): + if old.exists() == new.exists(): + raise SystemExit(f"Expected exactly one of {old} and {new} to exist.") + for old, new in MOVES.items(): + if old.exists(): + new.parent.mkdir(parents=True, exist_ok=True) + git("mv", "--", str(old), str(new)) + + +def replace_text(text: str) -> str: + for old, new in REPLACEMENTS: + text = text.replace(old, new) + for old, new in KEYED_MODULES.items(): + text = text.replace( + f"orcapod.databases.{old}", f"orcapod.databases.spiraldb_keyed.{new}" + ) + text = text.replace(f"databases/{old}.py", f"databases/spiraldb_keyed/{new}.py") + text = text.replace( + f"from orcapod.databases import {old} as ", + f"from orcapod.databases.spiraldb_keyed import {new} as ", + ) + text = text.replace( + f"from orcapod.databases import {old}\n", + f"from orcapod.databases.spiraldb_keyed import {new} as {old}\n", + ) + text = text.replace( + f"from orcapod.databases import {old} # noqa: E402 # after the skip\n", + "from orcapod.databases.spiraldb_keyed import ( # noqa: E402 # after the skip\n" + f" {new} as {old},\n" + ")\n", + ) + text = re.sub(rf"(?<=`){old}\.py(?=`)", f"spiraldb_keyed/{new}.py", text) + text = re.sub(rf"(?<=`){old}(?=[`\.])", f"spiraldb_keyed.{new}", text) + text = re.sub( + r"(?m)^from orcapod\.databases import \(\n(?P(?: [\w ,]+\n)+)\)", + replace_grouped_imports, + text, + ) + return text + + +def replace_file_text(path: Path, text: str) -> str: + """Rename references in a file while keeping its intentional legacy literals.""" + if path not in PRESERVED_REFERENCES: + return replace_text(text) + literals = "|".join(map(re.escape, PRESERVED_REFERENCES[path])) + parts = re.split(f"({literals})", text) + # The captures are preserved verbatim and the intervening text is renamed. + parts[::2] = map(replace_text, parts[::2]) + return "".join(parts) + + +def replace_grouped_imports(match: re.Match[str]) -> str: + imports = match["imports"].splitlines() + direct: list[str] = [] + keyed: list[str] = [] + for line in imports: + name, _, alias = line.strip().removesuffix(",").partition(" as ") + if name in KEYED_MODULES: + keyed.append(f" {KEYED_MODULES[name]} as {alias or name},") + else: + direct.append(line) + if not keyed: + return match[0] + groups = [] + if direct: + groups.append("from orcapod.databases import (\n" + "\n".join(direct) + "\n)") + groups.append( + "from orcapod.databases.spiraldb_keyed import (\n" + "\n".join(keyed) + "\n)" + ) + return "\n".join(groups) + + +def main() -> None: + os.chdir(Path(__file__).resolve().parents[4]) + move_files() + package = DATABASES / "spiraldb_keyed" / "__init__.py" + if not package.exists(): + package.write_text( + '"""The keyed-table backend for SpiralDB."""\n', encoding="utf-8" + ) + + generic_paths = {DATABASES / f"{module}.py" for module in GENERIC_MODULES} + for name in git("ls-files", "-z").split("\0"): + if not name: + continue + path = Path(name) + if path == BASELINE: + original = path.read_text(encoding="utf-8") + updated = original + for old, new in MOVES.items(): + updated = updated.replace(f'"./{old}":', f'"./{new}":') + elif path in EXTRA_TEXT or ( + path.parts[0] in TEXT_ROOTS + and path.suffix in TEXT_SUFFIXES + and not path.is_relative_to(SCRIPT_DIR) + and not path.is_relative_to("tests/test_hashing/golden") + and path != RENAME_FRAGMENT + and (path not in generic_paths or path.exists()) + ): + original = path.read_text(encoding="utf-8") + updated = replace_file_text(path, original) + else: + continue + if original != updated: + path.write_text(updated, encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md b/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md index b2e1079ff..394d5f595 100644 --- a/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md +++ b/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md @@ -8,7 +8,7 @@ ## Problem -All three `TestSpiralDBConnectorIntegration` tests have been failing in CI on every push to +All three `TestSpiralDBKeyedConnectorIntegration` tests have been failing in CI on every push to `extension-type-system` and `main` since approximately June 15, 2026 (between 04:04 and 20:57 UTC). The error is identical across all tests: @@ -59,7 +59,7 @@ downgrade. Full API compatibility check between 0.11.7 and 0.14.9: -| API call (in `SpiralDBConnector`) | Status | +| API call (in `SpiralDBKeyedConnector`) | Status | |---|---| | `sp.Spiral(overrides=...)` | ✅ unchanged | | `spiral.project(project_id)` | ✅ unchanged | @@ -77,7 +77,7 @@ Unit tests mock the `sp` module entirely and are unaffected by the version chang ### 4. Add breadcrumb comments -- **`tests/test_databases/test_spiraldb_connector_integration.py`** — extend the module +- **`tests/test_databases/test_spiraldb_keyed_connector_integration.py`** — extend the module docstring to document the t3.storage.dev enforcement change and explain that pyspiral must be kept up to date. - **`DESIGN_ISSUES.md`** — add a new entry recording the root cause, the symptom, and @@ -103,7 +103,7 @@ Unit tests mock the `sp` module entirely and are unaffected by the version chang - Breadcrumb documentation **Out of scope:** -- Changes to `SpiralDBConnector` logic (API is compatible — no edits needed) +- Changes to `SpiralDBKeyedConnector` logic (API is compatible — no edits needed) - Pinning the runner image or GitHub Actions environment - Any SpiralDB connector refactor diff --git a/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md b/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md index d84b0feb5..16461f734 100644 --- a/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md +++ b/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md @@ -1,4 +1,4 @@ -# ITL-471: SpiralDBConnector — Preserve Arrow Table- and Column-Level Metadata via Native KV Store +# ITL-471: SpiralDBKeyedConnector — Preserve Arrow Table- and Column-Level Metadata via Native KV Store **Date:** 2026-07-08 **Issue:** [ITL-471](https://linear.app/enigma-metamorphic/issue/ITL-471) @@ -8,12 +8,12 @@ ## Overview -`SpiralDBConnector` writes Arrow tables to SpiralDB via `tbl.write(records)` and reads them +`SpiralDBKeyedConnector` writes Arrow tables to SpiralDB via `tbl.write(records)` and reads them back via `self._spiral.scan(tbl.select()).to_record_batches()`. SpiralDB's Vortex columnar format silently drops all Arrow metadata — both schema-level (`schema.metadata`) and per-column (`field.metadata`) — on ingestion. This makes it impossible to round-trip Arrow extension types (Path, UUID, dataclass, etc.) through the SpiralDB backend, and prevents -`SpiralDBConnector` from participating in the peek-register-read pattern used for extension +`SpiralDBKeyedConnector` from participating in the peek-register-read pattern used for extension type auto-registration. SpiralDB exposes a native table-level KV metadata store (`Table.set_metadata` / @@ -29,13 +29,13 @@ guard and replaces it with a per-connector hook. ## Goals & Success Criteria -- On write, `SpiralDBConnector` serializes `schema.metadata` and per-field `field.metadata` +- On write, `SpiralDBKeyedConnector` serializes `schema.metadata` and per-field `field.metadata` from the incoming Arrow table into the SpiralDB native KV store. - On read (`iter_batches`), the connector loads stored metadata and reattaches it to the reconstructed Arrow schema and per-field `pa.Field` objects; the existing `large_string`/`large_binary` normalization is preserved. - Arrow extension types survive a full write→read cycle through `ConnectorArrowDatabase` + - `SpiralDBConnector`, enabling `register_discovered_extensions` / peek-register-read. + `SpiralDBKeyedConnector`, enabling `register_discovered_extensions` / peek-register-read. - The `ValueError` extension-type guard in `ConnectorArrowDatabase.add_records` no longer triggers for the SpiralDB backend. Other connectors (SQLite, PostgreSQL) continue to reject extension-typed records by default. @@ -55,7 +55,7 @@ In scope: - A single stable KV key encoding scheme under `"__arrow_metadata__"`. - Restoring metadata on read so extension-type discovery works. - Per-connector `validate_records` hook on `DBConnectorProtocol` (default rejects - extension types; `SpiralDBConnector` overrides to no-op). + extension types; `SpiralDBKeyedConnector` overrides to no-op). - Replacing `ConnectorArrowDatabase`'s inline extension-type guard with a delegation call to `self._connector.validate_records(records)`. - Unit tests and SpiralDB-backend integration tests. @@ -116,7 +116,7 @@ The value is a UTF-8–encoded JSON blob with this structure: called**. On read, absence of the key means no metadata to restore — backward compatible with tables written before this change. -Four private module-level helpers live in `spiraldb_connector.py`: +Four private module-level helpers live in `spiraldb_keyed/connector.py`: ```python def _serialize_arrow_metadata(table: pa.Table) -> dict[str, bytes] | None: @@ -272,11 +272,11 @@ def validate_records(self, records: "pa.Table") -> None: ) ``` -`SpiralDBConnector` overrides it as a no-op: +`SpiralDBKeyedConnector` overrides it as a no-op: ```python def validate_records(self, records: "pa.Table") -> None: - """No-op: SpiralDBConnector preserves Arrow field metadata via the native KV store.""" + """No-op: SpiralDBKeyedConnector preserves Arrow field metadata via the native KV store.""" ``` `SQLiteConnector` and `PostgreSQLConnector` inherit the default-reject behavior without @@ -313,7 +313,7 @@ No other changes to `ConnectorArrowDatabase`. correct KV dict; skipped when records have no Arrow metadata; `skip_existing=True` path also calls `set_metadata`. - `TestValidateRecords`: default implementation raises for in-memory extension types and - metadata-only extension fields, passes for plain types; `SpiralDBConnector.validate_records` + metadata-only extension fields, passes for plain types; `SpiralDBKeyedConnector.validate_records` is a no-op for all inputs. ### Unit Tests (`tests/test_databases/test_connector_arrow_database.py`) @@ -322,7 +322,7 @@ No other changes to `ConnectorArrowDatabase`. `validate_records`; a mock connector with a permissive override allows extension-typed records; a mock connector with the default raises. -### Integration Tests (`tests/test_databases/test_spiraldb_connector_integration.py`) +### Integration Tests (`tests/test_databases/test_spiraldb_keyed_connector_integration.py`) New class `TestArrowMetadataRoundTrip` (gated on `SPIRAL_INTEGRATION_TESTS=1`): @@ -347,12 +347,12 @@ New class `TestArrowMetadataRoundTrip` (gated on `SPIRAL_INTEGRATION_TESTS=1`): | File | Change | |---|---| -| `src/orcapod/databases/spiraldb_connector.py` | Add `_serialize_arrow_metadata`, `_load_arrow_metadata` helpers; modify `upsert_records` (write metadata after data write); modify `iter_batches` (load + restore metadata); add `validate_records` no-op override | +| `src/orcapod/databases/spiraldb_keyed/connector.py` | Add `_serialize_arrow_metadata`, `_load_arrow_metadata` helpers; modify `upsert_records` (write metadata after data write); modify `iter_batches` (load + restore metadata); add `validate_records` no-op override | | `src/orcapod/protocols/db_connector_protocol.py` | Add `validate_records` concrete default method | | `src/orcapod/databases/connector_arrow_database.py` | Replace inline guard (~lines 247–273) with `self._connector.validate_records(records)` | | `tests/test_databases/test_spiraldb_connector.py` | New test classes for serialization helpers, metadata read/write, `validate_records` | | `tests/test_databases/test_connector_arrow_database.py` | Tests for delegated `validate_records` | -| `tests/test_databases/test_spiraldb_connector_integration.py` | New `TestArrowMetadataRoundTrip` class | +| `tests/test_databases/test_spiraldb_keyed_connector_integration.py` | New `TestArrowMetadataRoundTrip` class | --- diff --git a/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md b/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md index e6535dae4..56955609e 100644 --- a/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md +++ b/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md @@ -39,7 +39,7 @@ the same commit, the static marks in the tree, and local runs of the files that | Group | Count | Stated reason | Verified cause | Verdict | |---|---|---|---|---| | Live Spiral source: `tests/test_core/sources/test_spiraldb_table_source_live.py` | 8 | "Set ORCAPOD_SPIRALDB_TEST_PROJECT to run" | The variable is set nowhere in `.github/`. The tests need a configured project, dataset and keyed table, plus credentials and network. | Correct to skip in `Run Tests`. Could run in the `spiral-integration` job once that job works and a project with the table exists (needs a developer decision and Spiral data). | -| Spiral connector integration: `test_spiraldb_connector_integration.py` | 9 | "Set SPIRAL_INTEGRATION_TESTS=1" | Run by the `spiral-integration` job (push to `main` only), which sets the variable. In that job all 9 **fail** (section 3.2). | Correct to skip in `Run Tests`; the job that runs them is broken. | +| Spiral connector integration: `test_spiraldb_keyed_connector_integration.py` | 9 | "Set SPIRAL_INTEGRATION_TESTS=1" | Run by the `spiral-integration` job (push to `main` only), which sets the variable. In that job all 9 **fail** (section 3.2). | Correct to skip in `Run Tests`; the job that runs them is broken. | | S3 / MinIO: `test_delta_table_database_s3.py` (7), `test_list_table_paths.py::test_s3_lists_tables_and_nested_tables` (1) | 8 | "MinIO container could not be started: 404 ... pull access denied for minio/minio" | See 3.3. The fixture starts MinIO with testcontainers and skips on any exception; in CI the image cannot be pulled, so the S3 path is never tested. | Should run in CI but does not; needs a SpiralDB workload credential (3.3, ITL-1079, ITL-1008). | | Delta tables under special-character roots: `test_delta_native_fs_read.py` (`x#y`, `q?r`, two tests each) | 4 | "deltalake cannot write a table at ..." | `_write_or_skip` skips when `deltalake` itself cannot write a table under a root named `x#y` or `q?r`. The other six special names run and pass. | Correct to skip: a limit of `deltalake`, not of Orcapod. Re-check on each `deltalake` upgrade. | | GPU tensors: `test_tensor_round_trip.py` (MPS, CUDA), `test_tensor_conversion_warning.py` (CUDA or MPS) | 3 | "needs MPS / CUDA / a CUDA or MPS device" | GitHub's Ubuntu runners have no GPU and no MPS. | Correct to skip. Running them needs a GPU runner (a paid CI service): not recommended before v0.3.0. | diff --git a/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md b/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md index 88d02e36e..1faee2fd1 100644 --- a/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md +++ b/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md @@ -65,7 +65,7 @@ frozenset); **decide** needs a decision (listed at the end). | P19 | `logical_types/user_class_identity.py` `identity_string` | a user class's identity record | SHA-256 hex prefix | the extension name `name@` | ok (in a name) | | P20 | `semantic_types/universal_converter.py` (synthesized struct class) *(code only)* | the field signature text | MD5 hex, 8 digits | a synthesized Python class name | ok (in a name) | | P21 | `pipeline/serialization.py` `DatabaseRegistry._make_key` | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job | ok (in a name) | -| P22 | `databases/spiraldb_nullability.py` `_encode` / `read_nullability_record` | the nullability path list | SHA-256 hex | chunk key and checksum of a stored metadata record | ok (in a name, checked on read) | +| P22 | `databases/spiraldb_keyed/nullability.py` `_encode` / `read_nullability_record` | the nullability path list | SHA-256 hex | chunk key and checksum of a stored metadata record | ok (in a name, checked on read) | | P23 | random ids: `job.py` `run_id` (`uuid4`), orchestrators' `run_id`, `datagram.py` `uuid7`, `data_function.py` record `uuid7`, observers' `uuid7`, `function_node.py` correlation key `uuid4` | nothing | random | ids | ok (not hashes) | | P24 | builtin `hash()`: `pipeline/graph.py` `_sanitize_node_id`, `core/streams/base.py` (config cache key), `ContentIdentifiableBase.__hash__` | Python objects | process-dependent | Graphviz node ids, in-memory keys | ok (display only) | | P25 | `hashing/arrow_utils.py` `get_pyarrow_table_hash`, `hashing/arrow_serialization.py` *(code only)* | Arrow tables | SHA-256, SHA3, BLAKE2b hex | **no caller anywhere in the library** | **decide** (D9) | diff --git a/docs/dev/specs/itl-1186-switch.md b/docs/dev/specs/itl-1186-switch.md index b340f6e16..b37391e74 100644 --- a/docs/dev/specs/itl-1186-switch.md +++ b/docs/dev/specs/itl-1186-switch.md @@ -3,7 +3,7 @@ Status: superseded in part. After an independent design review the first step is narrowed (November 24, 2026): **reading only**. The schema table is written by the migration tool alone, one row per table keyed by SpiralDB's table id, one schema per table, and a completion -marker last (`src/orcapod/databases/spiraldb_schema_table.py` is the statement). The connector +marker last (`src/orcapod/databases/spiraldb_keyed/schema_table.py` is the statement). The connector refuses writes; sections 1 and 2 below (a row per write, `earlier_schemas`) are not built. "Measured" means measured on the service with spiral-sdk 0.16.74 (and pyspiral 0.16.33 for comparison) on throwaway tables. diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md index 763b978df..81bf32b4b 100644 --- a/docs/dev/specs/itl-1367-stored-column-order.md +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -43,7 +43,7 @@ added column takes its place by name. Struct children are sorted by name too. The evidence, two live sessions as the agent workload on the test project, every table a throwaway one dropped at the end (the final listing showed none left). Each probe wrote -with pyspiral's `Table.write` (or `SpiralDBConnector.upsert_records`), then read the +with pyspiral's `Table.write` (or `SpiralDBKeyedConnector.upsert_records`), then read the table's schema (`Table.schema()`) and its rows (`SELECT *` through the connector): | Probe | Written | Schema and rows read back | diff --git a/docs/dev/specs/itl-926-live/FINDINGS.md b/docs/dev/specs/itl-926-live/FINDINGS.md index b448f8ed3..5569885a8 100644 --- a/docs/dev/specs/itl-926-live/FINDINGS.md +++ b/docs/dev/specs/itl-926-live/FINDINGS.md @@ -1,6 +1,6 @@ # ITL-926 — Phase 1 findings (November 11, 2026) -Audit of `SpiralDBTableSource` / `DBTableSource` / `SpiralDBConnector`, an end-to-end run of +Audit of `SpiralDBTableSource` / `DBTableSource` / `SpiralDBKeyedConnector`, an end-to-end run of the workshop path through a disk-backed pyspiral fake (`tests/test_databases/fake_pyspiral.py`), a pyspiral 0.14.9 → 0.16.33 API check, and a read-only live check. Repro scripts are in `docs/dev/specs/itl-926-live/`. @@ -114,7 +114,7 @@ Recommendation: move the lock to 0.16.33. Keep the floor at `>=0.14.0`, or raise ## Integration tests vs. the workshop path -`tests/test_databases/test_spiraldb_connector_integration.py` covers the connector and +`tests/test_databases/test_spiraldb_keyed_connector_integration.py` covers the connector and `ConnectorArrowDatabase` round trips plus ITL-471 metadata. It does not cover `SpiralDBTableSource`, `PipelineJob`, `Join`, caching, save/load, nullability, composite keys, timestamp keys, or large tables. The `spiral-integration` job needs the `SPIRAL_WORKLOAD_ID` @@ -157,7 +157,7 @@ secret (GitHub OIDC), `vars.SPIRAL_PROJECT_ID` and `vars.SPIRAL_SERVER_URL` * pandas turns `date32` into `datetime64[ms]`. * `fixed_size_list` tables fail before any of these methods can run (C2). 5. **Discovery.** There is no source-level helper. - `SpiralDBConnector(project).get_table_names()` and `.get_pk_columns(table)` are public + `SpiralDBKeyedConnector(project).get_table_names()` and `.get_pk_columns(table)` are public today (`orcapod.databases`) and are what the docs will show. A `SpiralDBTableSource.list_tables(project)` helper is a new-API decision. 6. **Setup.** `pip install "orcapod[spiraldb]"` installs the `spiral` CLI (pyspiral console diff --git a/docs/dev/specs/itl-936-live/live_nullability.py b/docs/dev/specs/itl-936-live/live_nullability.py index 449065e08..a4c7e8ba9 100644 --- a/docs/dev/specs/itl-936-live/live_nullability.py +++ b/docs/dev/specs/itl-936-live/live_nullability.py @@ -16,7 +16,7 @@ 1. ``fresh``: right after ``create_table`` the schema holds only the key columns (the connector's test for "a table with no rows yet", where it writes the record). -2. ``record``: ``SpiralDBConnector.upsert_records`` writes the record; SpiralDB's own schema +2. ``record``: ``SpiralDBKeyedConnector.upsert_records`` writes the record; SpiralDB's own schema is all nullable; ``get_column_info`` and ``iter_batches`` restore the written nullability at every depth; ``SpiralDBTableSource`` gives ``T``; a pod ``x: float`` runs; a ``Join`` of two recorded tables runs; the saved job loads in a fresh process, with every row and @@ -29,7 +29,7 @@ nullable struct field. Reports the rows and the child arrays as read back. ``struct_null_without_push_down``: a null struct written straight through pyspiral without ``push_down_nulls`` (refused, or what is stored); ``struct_null_connector``: the same rows - through ``SpiralDBConnector`` are refused by Orcapod before anything is written. + through ``SpiralDBKeyedConnector`` are refused by Orcapod before anything is written. 5. ``metadata``: several keys in one ``set_metadata`` call; a 400-column record (chunked); an entry over 8 KiB (expected refused). @@ -195,7 +195,7 @@ def write_mode(project: str, dataset: str, report: dict[str, Any]) -> bool: import spiral as sp # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) from orcapod.databases import ( - SpiralDBConnector, + SpiralDBKeyedConnector, read_nullability_record, # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 write_nullability_record, # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 ) @@ -217,7 +217,7 @@ def write_mode(project: str, dataset: str, report: dict[str, Any]) -> bool: created: list[str] = [] ok = True try: - connector = SpiralDBConnector(project, dataset=dataset) + connector = SpiralDBKeyedConnector(project, dataset=dataset) # 1. fresh key_info = [ColumnInfo("k", pa.int64(), nullable=False)] connector.create_table_if_not_exists(names["a"], key_info, pk_column="k") @@ -457,7 +457,9 @@ def read_mode( """ import spiral as sp # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) - from orcapod.databases import read_nullability_record # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 + from orcapod.databases import ( + read_nullability_record, # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 + ) from orcapod.sources import SpiralDBTableSource proj = sp.Spiral().project(project) # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 diff --git a/docs/dev/specs/itl-998-range-restriction.md b/docs/dev/specs/itl-998-range-restriction.md index b37994d72..0615acdb3 100644 --- a/docs/dev/specs/itl-998-range-restriction.md +++ b/docs/dev/specs/itl-998-range-restriction.md @@ -276,13 +276,13 @@ the implementation will). A clean merge does not prove the behaviour; the last c `spiraldb_table_source.py` with 558, 560, 562, 566, 570 and 571; these are between those PRs and do not involve ITL-998. The prototype also merges cleanly with the integration branch (569), and its `where` tests give the same 488 passes and 2 failures there as on `main`. Two other drafts of ITL-1457, 553 and 554, do conflict with -it in `spiraldb_connector.py`; the conflict is with the prototype's scan lines, so whichever lands second is +it in `spiraldb_keyed/connector.py`; the conflict is with the prototype's scan lines, so whichever lands second is rebased. **D11, merge order (approved).** ITL-1465 (PR 576) first: ITL-998 depends on it. ITL-998 may then merge before 555 and 558; it is independent of the ITL-1464 stack and need not wait for it. The stack follows, with 567 last, rebuilt on the rest (it rewrites `_whole_table`). If 553 or 554 is chosen over 555, the one that lands second -resolves the conflict in `spiraldb_connector.py`. Checked again on 2026-11-26 against the current heads: the +resolves the conflict in `spiraldb_keyed/connector.py`. Checked again on 2026-11-26 against the current heads: the prototype merges cleanly with 576, 555, 558, 559, 560, 562, 563, 565, 566, 567, 569, 570 and 571, and conflicts with 553 and 554 as before. @@ -336,7 +336,7 @@ Change: - **One list of terms** to `scan_batches` (`(column, operator, value)`, equality included) instead of `where=` plus `comparisons=`: one loop, and `Condition.equalities` (one value per column) is no longer how a scan is - described. The implemented `SpiralDBConnector.scan_batches` has a PROVISIONAL `where` + described. The implemented `SpiralDBKeyedConnector.scan_batches` has a PROVISIONAL `where` parameter that takes the `Condition` holding those terms. - `check_restriction` calls `check_equality_conditions` for a range bound: call the value check (`check_value_for_column`) under a neutral name; its "where names columns..." text stays. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 197690290..721808fb5 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -61,8 +61,8 @@ The library value types (NumPy, pandas, Polars, torch) are The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB and writes it only as a writable SpiralDB database ([SpiralDB as a Job's -Database](../concepts/spiraldb-database.md)), not compared here. See [The +SpiralDB and writes it only as a writable SpiralDB database ([Keyed SpiralDB as a Job's +Database](../concepts/spiraldb-keyed-database.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 80befc851..c8bbeaae2 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -401,7 +401,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | run snapshot | sorted labelled sink hashes | SHA-256 hex, 16 digits | the run URI `@` (a name) | `pipeline/job.py:PipelineJob._prepare_run`, `pipeline/job.py:PipelineJob._prepare_run..` | | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | -| SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | +| SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_keyed/schema_table.py:rows_digest` | | SpiralDB database manifest checksum | a writable SpiralDB database table's manifest payload (record path and Arrow schemas, canonical JSON); its format is provisional | SHA-256 hex | the manifest header's check of its chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_database_codec.py:_checksum` | | Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_digest` | | synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` | diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 7429e634d..c65d5e9a8 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -3,7 +3,7 @@ Orcapod on pyspiral kept each table's non-nullable columns and Arrow metadata in the table's key-value metadata, which spiral-sdk does not read. This tool records each table's schema in the dataset's schema table (``__orcapod_schemas__``), which Orcapod on spiral-sdk reads -(``orcapod.databases.spiraldb_schema_table``). It writes nothing else. +(``orcapod.databases.spiraldb_keyed.schema_table``). It writes nothing else. Three steps, each in an environment of its own (the two clients cannot be installed together); ``RELEASING.md`` has the exact commands: @@ -69,7 +69,7 @@ def spiral_module() -> Any: def require_credentials() -> None: """Stop unless the client can sign in without asking a person. - The rule of ``orcapod.databases.spiraldb_sign_in``, stated again: the dry run's + The rule of ``orcapod.databases.spiraldb_keyed.sign_in``, stated again: the dry run's Orcapod does not have it. """ env = os.environ @@ -252,7 +252,17 @@ def describe_table( def dry_run(args: argparse.Namespace) -> None: """Write the plan and print what each dataset's schema table would hold.""" - from orcapod.databases.spiraldb_connector import SpiralDBConnector + keyed_package = "orcapod.databases.spiraldb_keyed" + keyed_module = f"{keyed_package}.connector" + try: + connector_type = importlib.import_module(keyed_module).SpiralDBKeyedConnector + except ModuleNotFoundError as exc: + if exc.name not in (keyed_package, keyed_module): + raise + # The pinned pyspiral release recipe uses Orcapod from before the rename. + connector_type = importlib.import_module( + "orcapod.databases.spiraldb_connector" + ).SpiralDBConnector sp = spiral_module() @@ -280,7 +290,7 @@ def dry_run(args: argparse.Namespace) -> None: # Every selected dataset that lists a table, a reserved name included: a dataset # whose only table is a reserved name reaches the reserved-name check below. connectors = { - dataset: SpiralDBConnector(args.project, dataset) + dataset: connector_type(args.project, dataset) for dataset in sorted(set(args.dataset)) if dataset in tables or dataset in reserved } @@ -384,7 +394,7 @@ def sdk_client() -> Any: def planned_rows(tables: list[dict[str, Any]]) -> list[Any]: """Return the plan's rows, checked to say what the plan says.""" - from orcapod.databases.spiraldb_schema_table import SchemaRow + from orcapod.databases.spiraldb_keyed.schema_table import SchemaRow rows = [] for table in tables: @@ -414,11 +424,11 @@ def require_unchanged( rows: list[Any], ) -> None: """Refuse unless every table of the dataset is as the plan found it.""" - from orcapod.databases.spiraldb_connector import ( + from orcapod.databases.spiraldb_keyed.connector import ( _list_dataset, _open_keyed_table, ) - from orcapod.databases.spiraldb_schema_table import ( + from orcapod.databases.spiraldb_keyed.schema_table import ( compared_columns, describe_difference, ) @@ -499,7 +509,7 @@ def require_own_schema_table( ) -> Any | None: """Return the dataset's schema table when this plan's write created it, ``None`` when there is none yet; refuse any other.""" - from orcapod.databases.spiraldb_connector import _open_keyed_table + from orcapod.databases.spiraldb_keyed.connector import _open_keyed_table if planned["schema_table"] is not None: raise MigrationError( @@ -534,8 +544,11 @@ def require_own_schema_table( def open_rows(client: Any, project: str, dataset: str) -> tuple[dict[str, Any], Any]: """Return the schema table's rows by table id and its marker, as stored now.""" - from orcapod.databases.spiraldb_connector import _open_keyed_table - from orcapod.databases.spiraldb_schema_table import read_rows, require_schema_table + from orcapod.databases.spiraldb_keyed.connector import _open_keyed_table + from orcapod.databases.spiraldb_keyed.schema_table import ( + read_rows, + require_schema_table, + ) table = _open_keyed_table(client, project, dataset, SCHEMA_TABLE) if table is None or not require_schema_table(table): @@ -547,8 +560,8 @@ def write(args: argparse.Namespace) -> None: """Write the planned rows, one by one, and the completion marker last.""" import pyarrow as pa - from orcapod.databases import spiraldb_schema_table as st - from orcapod.databases.spiraldb_connector import _create_keyed_table + from orcapod.databases.spiraldb_keyed import schema_table as st + from orcapod.databases.spiraldb_keyed.connector import _create_keyed_table plan = read_plan(args.plan) require_scope(plan, args) @@ -663,11 +676,11 @@ def put(dataset: str, values: dict[str, Any]) -> None: def verify(args: argparse.Namespace) -> None: """Check with spiral-sdk alone that every source is what the plan says.""" - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector plan = read_plan(args.plan) require_scope(plan, args) - from orcapod.databases import spiraldb_schema_table as st + from orcapod.databases.spiraldb_keyed import schema_table as st client = sdk_client() project = plan["project"] @@ -675,7 +688,7 @@ def verify(args: argparse.Namespace) -> None: checked = refused = 0 for dataset, planned in plan["datasets"].items(): tables = planned["tables"] - connector = SpiralDBConnector(project, dataset) + connector = SpiralDBKeyedConnector(project, dataset) rows = planned_rows(tables) require_unchanged(client, project, dataset, tables, rows) present, marker = open_rows(client, project, dataset) diff --git a/site/astro.config.mjs b/site/astro.config.mjs index bc6e5326b..af9060a75 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -98,6 +98,9 @@ const page = (label, slug) => ({ label, slug }); export default defineConfig({ site, base, + redirects: { + '/concepts/spiraldb-database': `${base}concepts/spiraldb-keyed-database/`, + }, // mkdocs rendered '--' and quotes as written; so does the site. markdown: { smartypants: false }, // sharp is not installed (pnpm-workspace.yaml): images are served as they are. @@ -169,7 +172,7 @@ export default defineConfig({ page('Function Pods', 'concepts/function-pods'), page('Data-tags', 'concepts/data-tags'), page('Pipelines and Jobs', 'concepts/pipeline-job'), - page('SpiralDB as a Job\'s Database', 'concepts/spiraldb-database'), + page('Keyed SpiralDB as a Job\'s Database', 'concepts/spiraldb-keyed-database'), page('Provenance', 'concepts/provenance'), page('Working in Notebooks', 'concepts/notebooks'), page('Your Own Data Types', 'concepts/your-own-data-types'), diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index c9557da57..da6b01bd9 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -454,7 +454,7 @@ async def async_process_data( def _standalone_writes(self) -> AbstractContextManager[None]: """Give this standalone execution its own writable dataset scopes.""" - from orcapod.databases.spiraldb_write_scope import database_writes + from orcapod.databases.spiraldb_keyed.write_scope import database_writes return database_writes(result_databases_of_pods(self)) @@ -871,7 +871,7 @@ async def _async_execute( standalone: bool = False, ) -> None: """Stream rows in a new execution or as work delegated by a job node.""" - from orcapod.databases.spiraldb_write_scope import invocation_writes + from orcapod.databases.spiraldb_keyed.write_scope import invocation_writes from orcapod.pipeline.observer import NoOpObserver try: @@ -1638,7 +1638,7 @@ def _pod_base(self) -> "_FunctionPodBase": def _write_scope(self, pod: _FunctionPodBase) -> AbstractContextManager[None]: """Use the job's scope for a delegated source stream.""" - from orcapod.databases.spiraldb_write_scope import stream_writes + from orcapod.databases.spiraldb_keyed.write_scope import stream_writes return stream_writes(self, result_databases_of_pods(pod)) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 089bcb880..6c9147149 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -1848,7 +1848,7 @@ def require_storable_tables( if result_database is None: result_database = pipeline_database.at("_result") self.require_storable_results(result_database) - from orcapod.databases.spiraldb_write_scope import writable_connectors + from orcapod.databases.spiraldb_keyed.write_scope import writable_connectors try: require_storable(pipeline_database, _pipeline_meta_schema()) @@ -2858,7 +2858,7 @@ def execute( than this node; raised before any row is processed, whatever the error policy. """ - from orcapod.databases.spiraldb_write_scope import invocation_writes + from orcapod.databases.spiraldb_keyed.write_scope import invocation_writes from orcapod.pipeline.observer import NoOpObserver try: diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 7e9d08317..0b4b5854e 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1083,7 +1083,7 @@ def require_storable_tables( require_storable_path( pipeline_database, lambda: self._stored_table_path, node_label=self.label ) - from orcapod.databases.spiraldb_write_scope import writable_connectors + from orcapod.databases.spiraldb_keyed.write_scope import writable_connectors try: require_storable( diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 9e0649556..13b7c6033 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -304,6 +304,23 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: ) return saved + @classmethod + def check_saved_config(cls, config: dict[str, Any]) -> None: + """Refuse unsupported inline cache database configurations on job load. + + Args: + config: The saved cached source configuration. + + Raises: + ValueError: If the cache database has an unsupported SpiralDB config. + """ + from orcapod.pipeline.serialization import spiraldb_saved_config_refusal + + if ( + reason := spiraldb_saved_config_refusal(config.get("cache_database")) + ) is not None: + raise ValueError(f"cache_database: {reason}") + @classmethod def from_config( cls, @@ -549,7 +566,7 @@ def require_storable_cache(self) -> None: UnstorableColumnError: If the database cannot store a column, naming this source. """ - from orcapod.databases.spiraldb_write_scope import writable_connectors + from orcapod.databases.spiraldb_keyed.write_scope import writable_connectors database = self._cache_database # As every read of this source does first: a rebound wrapped source sets its diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index fd2d2fe96..848435214 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -83,8 +83,8 @@ ) from orcapod.core.streams.base import check_head_size from orcapod.core.streams.view import StreamView, ViewStatus -from orcapod.databases.spiraldb_connector import ( - SpiralDBConnector, +from orcapod.databases.spiraldb_keyed.connector import ( + SpiralDBKeyedConnector, SpiralDBTable, SpiralDBTableNotFoundError, require_same_process, @@ -284,7 +284,7 @@ class SpiralDBTableSource(RootSource): data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. overrides: Optional: ``{"server.url": "https://api.spiraldb.dev"}``, the - address of the service, passed to ``SpiralDBConnector``. + address of the service, passed to ``SpiralDBKeyedConnector``. tag_only_columns: Tag columns kept as tags only, not data, exactly as in v0.3; ``True`` for all of them. Keyword-only. Every other tag column is a data-tag: also a data column of the same name (ITL-1023). @@ -376,7 +376,7 @@ def __init__( self._dataset = dataset self._table_name = table_name self._overrides = None if overrides is None else dict(overrides) - self._connection: SpiralDBConnector | None = None + self._connection: SpiralDBKeyedConnector | None = None self._connection_lock = Lock() # Checks of one source run one at a time: the refusal is the latest's verdict. self._check_lock = Lock() @@ -751,14 +751,14 @@ def identity_structure(self) -> Any: # Reading # ------------------------------------------------------------------------- - def _connector(self) -> SpiralDBConnector: + def _connector(self) -> SpiralDBKeyedConnector: """Return the connector owned by this source.""" require_same_process(self._pid) # before a lock inherited by a fork with self._connection_lock: if self._closed: raise RuntimeError("SpiralDBTableSource is closed") if self._connection is None: - self._connection = SpiralDBConnector( + self._connection = SpiralDBKeyedConnector( project_id=self._project_id, dataset=self._dataset, overrides=self._overrides, diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index ce7cfbdb2..c2783fd39 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -4,7 +4,8 @@ from .in_memory_databases import InMemoryArrowDatabase from .noop_database import NoOpArrowDatabase from .postgresql_connector import PostgreSQLConnector -from .spiraldb_connector import SpiralDBConnector +from .spiral_database import SpiralDatabase +from .spiraldb_keyed.connector import SpiralDBKeyedConnector from .sqlite_connector import SQLiteConnector __all__ = [ @@ -13,7 +14,8 @@ "ExtensionAwareDatabase", "InMemoryArrowDatabase", "NoOpArrowDatabase", - "SpiralDBConnector", + "SpiralDatabase", + "SpiralDBKeyedConnector", "SQLiteConnector", "PostgreSQLConnector", ] @@ -25,7 +27,7 @@ # # SQLiteConnector -- PLT-1076 (stdlib sqlite3, zero extra deps) ✓ # PostgreSQLConnector -- PLT-1075 (psycopg3) ✓ -# SpiralDBConnector -- PLT-1074 +# SpiralDBKeyedConnector -- PLT-1074 # # ArrowDatabaseProtocol backends (existing, not connector-based): # diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 7e8c5db87..1f419d3a3 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -5,12 +5,11 @@ ``__record_id`` column convention, in-memory pending-batch management, deduplication and flush. -Connector implementations (SQLiteConnector, PostgreSQLConnector, SpiralDBConnector) +Connector implementations (SQLiteConnector, PostgreSQLConnector, SpiralDBKeyedConnector) need only satisfy DBConnectorProtocol; they do not implement ArrowDatabaseProtocol. -Example:: - - connector = SQLiteConnector(":memory:") # PLT-1076 +Examples: + connector = SQLiteConnector(":memory:") db = ConnectorArrowDatabase(connector) db.add_record(("results", "my_fn"), record_id=b"sha256:abc", record=table) db.flush() @@ -43,16 +42,15 @@ stored_path, ) from orcapod.databases.postgresql_connector import PostgreSQLConnector -from orcapod.databases.spiraldb_connector import SpiralDBConnector -from orcapod.databases.spiral_database_identity import ( +from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed.identity import ( SpiralTableCollisionError, refuse_other_format_path, ) -from orcapod.databases.spiraldb_tables import ( +from orcapod.databases.spiraldb_keyed.tables import ( SpiralDBTables, declared_keeping_identifier, ) -from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, require_store_path_domain, @@ -75,6 +73,7 @@ UnstorableColumnError, UnstorableTableNameError, ) +from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol from orcapod.utils.arrow_utils import ( normalize_schema_to_large_types, @@ -248,11 +247,11 @@ class ConnectorArrowDatabase: on ``flush()``. SQLite and PostgreSQL table names use a readable path hint and a digest of the full path. A catalog records the original path. - A writable SpiralDB database, ``SpiralDBConnector(..., writable=True)`` (provisional - in 0.4.0), is read and written through its database tables (``spiraldb_tables``): + A writable SpiralDB database, ``SpiralDBKeyedConnector(..., writable=True)`` (provisional + in 0.4.0), is read and written through its database tables (``spiraldb_keyed.tables``): names computed from the full path, identity and manifest in each table's metadata, rows through the database codec. Its writes use a write scope - (``spiraldb_write_scope``). A plain ``SpiralDBConnector`` refuses every write, as + (``spiraldb_keyed.write_scope``). A plain ``SpiralDBKeyedConnector`` refuses every write, as before. Args: @@ -286,9 +285,9 @@ def __init__( connector if isinstance(connector, SQLStoreConnector) else None ) # A writable SpiralDB connector; ``None`` for any other (ITL-1840). - self._spiral_connector: SpiralDBConnector | None = ( + self._spiral_connector: SpiralDBKeyedConnector | None = ( connector - if isinstance(connector, SpiralDBConnector) + if isinstance(connector, SpiralDBKeyedConnector) and connector._writable_tables() is not None # pyright: ignore[reportPrivateUsage] # the database's one reader and writer else None ) @@ -1154,7 +1153,7 @@ def _read_stored_schema( """The schema a read of the stored table gives, its field metadata included. Read without rows from a connector that offers ``get_arrow_schema`` - (``SpiralDBConnector``); from any other, the schema of its first batch. + (``SpiralDBKeyedConnector``); from any other, the schema of its first batch. """ if (tables := self._spiral) is not None: return tables.arrow_schema(table_name) diff --git a/src/orcapod/databases/spiral_database.py b/src/orcapod/databases/spiral_database.py new file mode 100644 index 000000000..b355ad588 --- /dev/null +++ b/src/orcapod/databases/spiral_database.py @@ -0,0 +1,34 @@ +from typing import Any + +from .connector_arrow_database import ConnectorArrowDatabase +from .spiraldb_keyed.connector import SpiralDBKeyedConnector + + +def SpiralDatabase( + project_id: str, + dataset: str, + *, + writable: bool = True, + **connector_options: Any, +) -> ConnectorArrowDatabase: + """Open a SpiralDB database using Orcapod's default backend. + + Saved jobs record the concrete backend and its configuration. The default + backend may change in a later release, with one release of advance notice. + + Args: + project_id: SpiralDB project identifier. + dataset: Dataset within the project. + writable: Use the writable database layout. Pass ``False`` for the plain + keyed connector's layout. + **connector_options: Additional keyword arguments forwarded to + ``SpiralDBKeyedConnector``, such as ``overrides`` or ``write_lock``. + + Returns: + A database backed by a ``SpiralDBKeyedConnector``. + """ + return ConnectorArrowDatabase( + SpiralDBKeyedConnector( + project_id, dataset, writable=writable, **connector_options + ) + ) diff --git a/src/orcapod/databases/spiral_database_codec.py b/src/orcapod/databases/spiral_database_codec.py index 16d36d53d..2b5003d86 100644 --- a/src/orcapod/databases/spiral_database_codec.py +++ b/src/orcapod/databases/spiral_database_codec.py @@ -17,7 +17,7 @@ no rows may be recorded again (``manifest_entries``, ``read_manifest``): the record path, the kind, the logical schema, and the stored names at every depth. It is kept in the table's own metadata, in chunks of at most 8 KiB, beside the table's - identity record (``spiral_database_identity``); never in the dataset's schema table, + identity record (``spiraldb_keyed.identity``); never in the dataset's schema table, which is all or nothing under one completion marker (decision of 2026-11-26). Logical types are handled by their identifier (extension name and metadata) alone, as diff --git a/src/orcapod/databases/spiraldb_keyed/__init__.py b/src/orcapod/databases/spiraldb_keyed/__init__.py new file mode 100644 index 000000000..b5b475910 --- /dev/null +++ b/src/orcapod/databases/spiraldb_keyed/__init__.py @@ -0,0 +1 @@ +"""The keyed-table backend for SpiralDB.""" diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py similarity index 96% rename from src/orcapod/databases/spiraldb_connector.py rename to src/orcapod/databases/spiraldb_keyed/connector.py index ad6031c7c..8c72ea78a 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -1,4 +1,4 @@ -"""SpiralDBConnector — DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). +"""SpiralDBKeyedConnector — DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``. Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials @@ -6,11 +6,10 @@ The connector is dataset-scoped: all tables are read from and written to a single ``(project_id, dataset)`` pair. They are SpiralDB's keyed tables. The schema each -is read with is in the dataset's schema table (``spiraldb_schema_table``). +is read with is in the dataset's schema table (``spiraldb_keyed.schema_table``). -Example:: - - connector = SpiralDBConnector(project_id="my-project-123456", dataset="default") +Examples: + connector = SpiralDBKeyedConnector(project_id="my-project-123456", dataset="default") rows = pa.Table.from_batches(connector.scan_batches("units")) """ @@ -36,21 +35,23 @@ import pyarrow.compute as pc from typing_extensions import override -from orcapod.databases.spiraldb_nullability import ( +from orcapod.databases.spiraldb_keyed.nullability import ( cast_changed_columns, check_no_nulls, schema_paths, ) -from orcapod.databases.spiraldb_schema_table import ( +from orcapod.databases.spiraldb_keyed.schema_table import ( SCHEMA_TABLE, KeptRows, SchemaTable, compared_columns, describe_difference, ) -from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path -from orcapod.databases.spiraldb_writable_registry import register_writable_connector -from orcapod.databases.spiraldb_tables import SpiralDBTables +from orcapod.databases.spiraldb_keyed.sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables +from orcapod.databases.spiraldb_keyed.writable_registry import ( + register_writable_connector, +) from orcapod.databases.write_lock import NoWriteLock, WriteLock from orcapod.errors import ( NullInNonNullableColumnError, @@ -83,9 +84,9 @@ _SCAN_BATCH_ROWS = 8_192 _LIST_TIMEOUT_S = 60 _NO_WRITES = ( - "a plain SpiralDBConnector only reads SpiralDB tables; nothing was written. A job " + "a plain SpiralDBKeyedConnector only reads SpiralDB tables; nothing was written. A job " "keeps its tables in SpiralDB through a writable SpiralDB database: " - "ConnectorArrowDatabase(SpiralDBConnector(..., writable=True))" + "ConnectorArrowDatabase(SpiralDBKeyedConnector(..., writable=True))" ) # Tables a warning was issued for in this process (``UnrecordedTableSchemaWarning``). _warned_unrecorded: set[tuple[str, str]] = set() @@ -141,7 +142,7 @@ def _about_table(table: str) -> Iterator[None]: # --------------------------------------------------------------------------- -# SpiralDBConnector +# SpiralDBKeyedConnector # --------------------------------------------------------------------------- @@ -525,7 +526,7 @@ def _http_get_json(url: str, token: str | None) -> dict[str, Any]: STORE_KEY_REFUSAL = ( "a SpiralDB connector configuration with a 'store' key is not read: the writable " - "SpiralDB database is SpiralDBConnector(..., writable=True), saved as " + "SpiralDB database is SpiralDBKeyedConnector(..., writable=True), saved as " "'writable': true" ) """The refusal of a saved SpiralDB connector configuration that names ``store``.""" @@ -703,7 +704,7 @@ def _equals(array: Any, value: Any) -> Any: class SpiralDBTable: - """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). + """One SpiralDB table, looked up once (``SpiralDBKeyedConnector.lookup_table``). Every lookup of a table by name is a round trip to SpiralDB. A caller that needs several items of one table (a source's id, key, schema and version when it is built, @@ -718,7 +719,7 @@ class SpiralDBTable: """ def __init__( - self, connector: SpiralDBConnector, table: Any, table_name: str + self, connector: SpiralDBKeyedConnector, table: Any, table_name: str ) -> None: """Wrap the keyed ``table`` that ``connector`` looked up as ``table_name``.""" self._connector = connector @@ -728,7 +729,7 @@ def __init__( # The SDK's handle of each other version opened (``_at``), by version. self._versions: dict[str, Any] = {} - def with_connector(self, connector: SpiralDBConnector) -> SpiralDBTable: + def with_connector(self, connector: SpiralDBKeyedConnector) -> SpiralDBTable: """Return this table read through ``connector``, which shares its SDK client. What was worked out per version is shared: a snapshot never changes. @@ -839,7 +840,7 @@ def scan_batches( Args: where: Equalities and ranges of columns, all of which must hold - (``SpiralDBConnector.scan_batches``). + (``SpiralDBKeyedConnector.scan_batches``). limit: Read at most this many matching rows. asof: Read this version. columns: The columns to read; ``None`` reads every column. Each batch @@ -1031,7 +1032,7 @@ def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: return cast_changed_columns(batch, self.schema) -class SpiralDBConnector: +class SpiralDBKeyedConnector: """DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). Scoped to a single dataset within a SpiralDB project, and to its keyed tables. Auth @@ -1050,7 +1051,7 @@ class SpiralDBConnector: through ``ConnectorArrowDatabase``. One writer process per dataset at a time is assumed, not checked (ITL-1899): concurrent writers are not supported, and with two a run can store results twice, deliver side effects twice and - overwrite a cached source instead of refusing (``spiraldb_write_scope``). + overwrite a cached source instead of refusing (``spiraldb_keyed.write_scope``). Provisional in 0.4.0: the table format may change in a later version, which may not read tables written now. write_lock: Optional, for a writable connector: the ``WriteLock`` acquired @@ -1118,7 +1119,7 @@ def _new_tables(self) -> SpiralDBTables: Each writable connector has its own, so a run's write scope attached to one connector's tables is not another connector's (``share_client`` too). """ - from orcapod.databases.spiraldb_write_scope import one_call_scope + from orcapod.databases.spiraldb_keyed.write_scope import one_call_scope client, health = self._client, self._health project_id, dataset = self._project_id, self._dataset @@ -1146,7 +1147,7 @@ def write_lock(self) -> WriteLock: def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" if self._closed: - raise RuntimeError("SpiralDBConnector is closed") + raise RuntimeError("SpiralDBKeyedConnector is closed") require_same_process(self._pid) def _writable_tables(self) -> SpiralDBTables | None: @@ -1184,7 +1185,7 @@ def _refuse_if_writable(self) -> None: "ConnectorArrowDatabase only, never as raw tables" ) - def share_client(self) -> SpiralDBConnector: + def share_client(self) -> SpiralDBKeyedConnector: """Return an independently closable connector in the same SDK client scope. A writable connector's copy is writable too, registered as one, with the same @@ -1410,13 +1411,13 @@ def iter_batches( self._refuse_if_writable() if params is not None: logger.warning( - "SpiralDBConnector does not support query parameters; " + "SpiralDBKeyedConnector does not support query parameters; " "ignoring params=%r", params, ) if batch_size != 1000: logger.warning( - "SpiralDBConnector does not support batch_size; " + "SpiralDBKeyedConnector does not support batch_size; " "batch sizing is controlled by the Spiral execution engine. " "Ignoring batch_size=%r", batch_size, @@ -1625,7 +1626,7 @@ def close(self) -> None: # ``share_client`` has its own. self._tables = None - def __enter__(self) -> SpiralDBConnector: + def __enter__(self) -> SpiralDBKeyedConnector: return self def __exit__(self, *args: Any) -> None: @@ -1646,7 +1647,7 @@ def to_config(self) -> dict[str, Any]: """ self._require_open() config: dict[str, Any] = { - "connector_type": "spiraldb", + "connector_type": "spiraldb_keyed", "project_id": self._project_id, "dataset": self._dataset, "overrides": None if self._overrides is None else dict(self._overrides), @@ -1656,23 +1657,23 @@ def to_config(self) -> dict[str, Any]: return config @classmethod - def from_config(cls, config: dict[str, Any]) -> SpiralDBConnector: - """Reconstruct a SpiralDBConnector from a config dict. + def from_config(cls, config: dict[str, Any]) -> SpiralDBKeyedConnector: + """Reconstruct a SpiralDBKeyedConnector from a config dict. Args: config: Dict with ``connector_type``, ``project_id``, and optionally ``dataset``, ``overrides`` and ``writable`` keys. Returns: - A new, open SpiralDBConnector instance. + A new, open SpiralDBKeyedConnector instance. Raises: - ValueError: If ``connector_type`` is not ``"spiraldb"``, or the config holds + ValueError: If ``connector_type`` is not ``"spiraldb_keyed"``, or the config holds a ``store`` key (not an option: ``writable``). """ - if config.get("connector_type") != "spiraldb": + if config.get("connector_type") != "spiraldb_keyed": raise ValueError( - f"Expected connector_type 'spiraldb', " + f"Expected connector_type 'spiraldb_keyed', " f"got {config.get('connector_type')!r}" ) if "store" in config: diff --git a/src/orcapod/databases/spiral_database_identity.py b/src/orcapod/databases/spiraldb_keyed/identity.py similarity index 100% rename from src/orcapod/databases/spiral_database_identity.py rename to src/orcapod/databases/spiraldb_keyed/identity.py diff --git a/src/orcapod/databases/spiraldb_nullability.py b/src/orcapod/databases/spiraldb_keyed/nullability.py similarity index 99% rename from src/orcapod/databases/spiraldb_nullability.py rename to src/orcapod/databases/spiraldb_keyed/nullability.py index c021ae80d..9c2742c44 100644 --- a/src/orcapod/databases/spiraldb_nullability.py +++ b/src/orcapod/databases/spiraldb_keyed/nullability.py @@ -2,7 +2,7 @@ SpiralDB reports every top-level column (key columns included) and every struct field as nullable, whatever was written; only list items keep a non-null flag (ITL-936). Orcapod -records each table's schema in the dataset's schema table (``spiraldb_schema_table``) and +records each table's schema in the dataset's schema table (``spiraldb_keyed.schema_table``) and enforces its non-nullable paths on read. A path starts with a top-level column name; each further segment is a struct field name, or diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_keyed/schema_table.py similarity index 99% rename from src/orcapod/databases/spiraldb_schema_table.py rename to src/orcapod/databases/spiraldb_keyed/schema_table.py index 908cf8b1b..8b2ab2d7d 100644 --- a/src/orcapod/databases/spiraldb_schema_table.py +++ b/src/orcapod/databases/spiraldb_keyed/schema_table.py @@ -33,7 +33,7 @@ import pyarrow as pa -from orcapod.databases.spiraldb_nullability import ITEM, ColumnPath, field_members +from orcapod.databases.spiraldb_keyed.nullability import ITEM, ColumnPath, field_members from orcapod.errors import TableSchemaError from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.utils import arrow_utils diff --git a/src/orcapod/databases/spiraldb_sign_in.py b/src/orcapod/databases/spiraldb_keyed/sign_in.py similarity index 100% rename from src/orcapod/databases/spiraldb_sign_in.py rename to src/orcapod/databases/spiraldb_keyed/sign_in.py diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_keyed/tables.py similarity index 99% rename from src/orcapod/databases/spiraldb_tables.py rename to src/orcapod/databases/spiraldb_keyed/tables.py index 6dff9f955..dcd5c2541 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_keyed/tables.py @@ -1,11 +1,11 @@ """The tables of a writable SpiralDB database, one dataset's (ITL-1840). What ``ConnectorArrowDatabase`` does with the tables of a writable SpiralDB database, -``SpiralDBConnector(..., writable=True)`` (public and provisional in 0.4.0, ITL-1844). +``SpiralDBKeyedConnector(..., writable=True)`` (public and provisional in 0.4.0, ITL-1844). The design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, carried from PR 595 onto ``main``'s database structure. -- A table's name is computed from its full record path (``spiral_database_identity``); a +- A table's name is computed from its full record path (``spiraldb_keyed.identity``); a table is found by opening that name. In a write scope, a name the run's listing of the dataset does not show is absent without an open (ITL-1899): the listing is updated as the run creates and writes tables. @@ -29,7 +29,7 @@ (ITL-954). One writer process per dataset is assumed (ITL-1899), not checked: every write happens -inside a scope of the dataset (``spiraldb_write_scope``), a job run's or, for a write +inside a scope of the dataset (``spiraldb_keyed.write_scope``), a job run's or, for a write outside a run, one of its own for that call, and at most one scope of a dataset is open in a process. The scope's ``WriteLock`` (``write_lock``; a no-op by default) is acquired at its first create or append. A first write still re-reads the table just before @@ -58,8 +58,8 @@ import pyarrow.compute as pc import orcapod.databases.spiral_database_codec as codec -import orcapod.databases.spiral_database_identity as identity -from orcapod.databases.spiral_database_identity import SpiralTableCollisionError +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.logical_types.canonical_form import ( @@ -124,7 +124,7 @@ def shows_absent(self, table_name: str) -> bool: @dataclass(eq=False) class RunState: - """A scope's state for one dataset (``spiraldb_write_scope``), shared by the + """A scope's state for one dataset (``spiraldb_keyed.write_scope``), shared by the dataset's connectors in the scope: the write lock's acquisition, the key index, the catalog and the kept reads. It holds only while the scope's process is the dataset's one writer (the single-writer assumption, ITL-1899). @@ -420,7 +420,7 @@ def __init__( # recorded stays what its first write compares with). self._now: threading.local = threading.local() # The state of the scope these tables are written in - # (``spiraldb_write_scope``); ``None`` outside one. + # (``spiraldb_keyed.write_scope``); ``None`` outside one. self._attached_run: RunState | None = None key_column: str = codec.KEY_COLUMN @@ -1202,7 +1202,7 @@ def write_scope(self, *, invocation: bool = False) -> Iterator[None]: yield def attach_run(self, state: RunState) -> None: - """Write these tables in a scope (``spiraldb_write_scope``). + """Write these tables in a scope (``spiraldb_keyed.write_scope``). Args: state: The scope's state of this dataset. diff --git a/src/orcapod/databases/spiraldb_writable_registry.py b/src/orcapod/databases/spiraldb_keyed/writable_registry.py similarity index 84% rename from src/orcapod/databases/spiraldb_writable_registry.py rename to src/orcapod/databases/spiraldb_keyed/writable_registry.py index 1c7e52ff3..8566ae283 100644 --- a/src/orcapod/databases/spiraldb_writable_registry.py +++ b/src/orcapod/databases/spiraldb_keyed/writable_registry.py @@ -1,7 +1,7 @@ """Which writable SpiralDB connectors exist in this process (ITL-1844). A run opens a write scope for every writable SpiralDB database it may write -(``spiraldb_write_scope.database_writes``), found by walking the run's graph. A writable +(``spiraldb_keyed.write_scope.database_writes``), found by walking the run's graph. A writable database always holds its writable connector, so when no writable connector exists in the process no run can write one, and the run skips the walk (``any_writable_connector``). @@ -19,7 +19,7 @@ def register_writable_connector(connector: object) -> None: """Record a writable connector, for as long as it exists. Args: - connector: A ``SpiralDBConnector`` made with ``writable=True``. + connector: A ``SpiralDBKeyedConnector`` made with ``writable=True``. """ _writable_connectors.add(connector) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_keyed/write_scope.py similarity index 95% rename from src/orcapod/databases/spiraldb_write_scope.py rename to src/orcapod/databases/spiraldb_keyed/write_scope.py index ce9d53a66..f36e1d5eb 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_keyed/write_scope.py @@ -1,6 +1,6 @@ """The write scopes of writable SpiralDB databases (ITL-1899). -A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) is written by +A writable SpiralDB database (``SpiralDBKeyedConnector(..., writable=True)``) is written by one writer process at a time: Orcapod assumes it and does not check it. Concurrent writers in several processes are not supported; with two, a run can store results twice, deliver side effects twice, and overwrite a cached source instead of refusing. @@ -10,7 +10,7 @@ may write (``database_writes``), for the whole run; a write outside a run (a ``CachedSource`` read outside a run, a ``ConnectorArrowDatabase`` flushed directly) opens one of its own for that call (``one_call_scope``). A scope's state -(``spiraldb_tables.RunState``) holds what the scope read of the dataset: the key index, +(``spiraldb_keyed.tables.RunState``) holds what the scope read of the dataset: the key index, the catalog (one listing of the dataset on first use) and the kept reads. It is shared by the scope's connectors of the dataset, and forgotten when the scope ends. @@ -37,14 +37,14 @@ from contextvars import ContextVar from typing import TYPE_CHECKING -from orcapod.databases.spiraldb_tables import RunState, active_run_states +from orcapod.databases.spiraldb_keyed.tables import RunState, active_run_states from orcapod.databases.write_lock import NoWriteLock, WriteLockHandle from orcapod.errors import OrcapodDatabaseWriteError, SpiralDBScopeOpenError from orcapod.protocols.spiraldb_run import invocation_boundary if TYPE_CHECKING: - from orcapod.databases.spiraldb_connector import SpiralDBConnector - from orcapod.databases.spiraldb_tables import SpiralDBTables + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector + from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables _open_scopes: dict[tuple[str, str], _DatasetScope] = {} """Open scopes by (project, dataset) in this process.""" @@ -63,7 +63,7 @@ """The source streams delegated by the current execution's job graph.""" -def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: +def writable_connectors(databases: Iterable[object]) -> list[SpiralDBKeyedConnector]: """The distinct writable SpiralDB connectors under ``databases``, in the order met. Args: @@ -76,7 +76,7 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views - found: list[SpiralDBConnector] = [] + found: list[SpiralDBKeyedConnector] = [] for given in databases: database = unwrap_database_views(given) # a library view's database too if not isinstance(database, ConnectorArrowDatabase): @@ -136,7 +136,7 @@ def stream_writes( @contextlib.contextmanager def one_call_scope( - connector: SpiralDBConnector, *, invocation: bool = False + connector: SpiralDBKeyedConnector, *, invocation: bool = False ) -> Iterator[None]: """Open a scope for one direct call, or join the enclosing invocation's scope. @@ -161,10 +161,10 @@ def invocation_writes( @contextlib.contextmanager def _connector_scopes( - writable: list[SpiralDBConnector], *, join: bool = False + writable: list[SpiralDBKeyedConnector], *, join: bool = False ) -> Iterator[None]: """``database_writes`` over writable connectors.""" - groups: dict[tuple[str, str, str], list[SpiralDBConnector]] = {} + groups: dict[tuple[str, str, str], list[SpiralDBKeyedConnector]] = {} for connector in writable: groups.setdefault(connector._write_scope_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only inherited = _invocation_scopes.get() if join else {} @@ -244,7 +244,7 @@ class _DatasetScope: """One open write scope of a dataset in this process.""" def __init__( - self, key: tuple[str, str, str], connectors: list[SpiralDBConnector] + self, key: tuple[str, str, str], connectors: list[SpiralDBKeyedConnector] ) -> None: _, self._project_id, self._dataset = key providers = [ @@ -266,7 +266,7 @@ def __init__( self.refused: BaseException | None = None self.state = RunState(self._acquire) - def open(self, connectors: list[SpiralDBConnector]) -> None: + def open(self, connectors: list[SpiralDBKeyedConnector]) -> None: """Reserve the dataset and attach each tables object.""" with _open_scopes_lock: if self._reservation in _open_scopes: @@ -280,7 +280,7 @@ def open(self, connectors: list[SpiralDBConnector]) -> None: self._attach(_tables(connector)) self._accepting_joins = True - def join(self, connectors: list[SpiralDBConnector]) -> bool: + def join(self, connectors: list[SpiralDBKeyedConnector]) -> bool: """Attach cache stores in the same invocation to this scope.""" with self.state.lock: if not self._accepting_joins: @@ -374,7 +374,7 @@ def close(self) -> list[BaseException]: return failures -def _tables(connector: SpiralDBConnector) -> SpiralDBTables: +def _tables(connector: SpiralDBKeyedConnector) -> SpiralDBTables: tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only if tables is None: raise RuntimeError("not a writable SpiralDB connector") diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 25ee8e604..89adc6b39 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -26,9 +26,9 @@ def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: A path inside this syntax can still be refused for its size: each entry of the identity record is capped at SpiralDB's entry limit - (``spiral_database_identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an + (``spiraldb_keyed.identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an 8,192-character component is valid here, round-trips through the chunked manifest, - and is refused by ``spiral_database_identity.table_identity_metadata``. + and is refused by ``spiraldb_keyed.identity.table_identity_metadata``. Args: path: The store's base path followed by its record path. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index f7f69a6fd..9edd5f6c2 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -742,10 +742,10 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: class SpiralDBWriteNotSupportedError(NotImplementedError): """A plain SpiralDB connector was asked to write: it only reads (ITL-1186). - Raised by every write of a plain ``SpiralDBConnector`` (creating or deleting a table, + Raised by every write of a plain ``SpiralDBKeyedConnector`` (creating or deleting a table, storing rows), so also by a job whose database is a ``ConnectorArrowDatabase`` on one. Nothing is written. A job keeps its tables in SpiralDB through a writable SpiralDB - database, ``SpiralDBConnector(..., writable=True)`` (ITL-1844). + database, ``SpiralDBKeyedConnector(..., writable=True)`` (ITL-1844). """ diff --git a/src/orcapod/pipeline/_observer_database.py b/src/orcapod/pipeline/_observer_database.py index 0ab42409b..2d8a9fd0d 100644 --- a/src/orcapod/pipeline/_observer_database.py +++ b/src/orcapod/pipeline/_observer_database.py @@ -9,7 +9,7 @@ from orcapod.databases import ( ConnectorArrowDatabase, ExtensionAwareDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.errors import SpiralDBObserverNotSupportedError @@ -52,7 +52,7 @@ def require_observer_database(database: ArrowDatabaseProtocol) -> None: return connector = _stored_reference(backend, "_connector") - if issubclass(type(connector), SpiralDBConnector): + if issubclass(type(connector), SpiralDBKeyedConnector): raise SpiralDBObserverNotSupportedError( "Observers cannot record to a SpiralDB database in this version. " + "Give the observer another database, for example Delta." diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index a503219da..3cddb5a46 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -52,8 +52,8 @@ RunPlan, check_sources, clear_run_rows, - plan_run, database_write_scope, + plan_run, ) from orcapod.pipeline.observer_losses import RunLosses from orcapod.pipeline.restrictions import ( @@ -2371,7 +2371,7 @@ def load( the argument that gives it is missing: a connector is not rebuilt from a file. The message names each such binding. Also if a SpiralDB database was saved writable - (``SpiralDBConnector(..., writable=True)``) and the one given is a + (``SpiralDBKeyedConnector(..., writable=True)``) and the one given is a plain SpiralDB connector database, or the other way round (ITL-1844). Only a SpiralDB database of the other kind is refused: a database that is not a SpiralDB one may stand for a saved @@ -2414,9 +2414,8 @@ def load( exc.add_note(f"Loading the job file {path}") raise - # A saved SpiralDB connector configuration this version does not read (a - # ``store`` key, a ``writable`` that is not a boolean) is refused first, given - # a connector or not, so an old file is told about writable=True (ITL-1844). + # Report unsupported keyed SpiralDB configurations before reporting missing + # connectors, even if the caller supplies a connector for the affected slot. unreadable = [ f"bindings.{slot_name}: {reason}" for slot_name in ("database", "result_database") diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 1efaf9be3..bb30a608b 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -33,13 +33,13 @@ OrcapodDatabaseWriteError, live_input_cycle_error, ) +from orcapod.pipeline.restrictions import restrictions_in_force, source_name +from orcapod.pipeline.result import StreamsOnRead from orcapod.pipeline.run_summary import ( RunCountingObserver, RunSummary, run_node_summaries, ) -from orcapod.pipeline.restrictions import restrictions_in_force, source_name -from orcapod.pipeline.result import StreamsOnRead from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -476,7 +476,7 @@ def database_write_scope( """The write scopes a run holds on the writable SpiralDB databases it may write. The run may write the databases ``write_scope_databases`` lists. Entered before the - run checks its sources (``spiraldb_write_scope.database_writes``). A load-only run + run checks its sources (``spiraldb_keyed.write_scope.database_writes``). A load-only run whose source check would read an input that computes or delivers is refused first (``refuse_unloadable_source_checks``). When no writable SpiralDB connector exists in the process, no run can write one: nothing is walked @@ -496,7 +496,9 @@ def database_write_scope( ``preflight_run_writes``. UnstorableColumnError: As ``preflight_run_writes``. """ - from orcapod.databases.spiraldb_writable_registry import any_writable_connector + from orcapod.databases.spiraldb_keyed.writable_registry import ( + any_writable_connector, + ) if load_only: # Reject inputs that compute or deliver before opening scopes or checking @@ -506,7 +508,7 @@ def database_write_scope( preflight_run_writes(streams, load_only=load_only) if not any_writable_connector(): return contextlib.nullcontext() - from orcapod.databases.spiraldb_write_scope import database_writes + from orcapod.databases.spiraldb_keyed.write_scope import database_writes source_streams: list[Any] = [] written = write_scope_databases( @@ -724,8 +726,10 @@ def batches_node_commits(node: Any) -> bool: from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.databases.extension_aware_database import unwrap_database_views from orcapod.databases.in_memory_databases import InMemoryArrowDatabase - from orcapod.databases.spiraldb_writable_registry import any_writable_connector - from orcapod.databases.spiraldb_write_scope import writable_connectors + from orcapod.databases.spiraldb_keyed.writable_registry import ( + any_writable_connector, + ) + from orcapod.databases.spiraldb_keyed.write_scope import writable_connectors if not isinstance(node, FunctionJobNode) or not any_writable_connector(): return False diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 7054094c3..0bd3edb5b 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -12,8 +12,6 @@ from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias, cast -from orcapod.types import Schema -from orcapod.types.argument_groups import SymmetricGroup from orcapod.logical_types.canonical_form import ( declaration_form_field, declaration_form_schema, @@ -25,8 +23,9 @@ arrow_type_identifier, require_readable, ) - from orcapod.semantic_types._schema_conversion import arrow_schema_for_types +from orcapod.types import Schema +from orcapod.types.argument_groups import SymmetricGroup from orcapod.utils.schema_utils import ReservedColumnNameError, require_names_not_system if TYPE_CHECKING: @@ -276,9 +275,9 @@ def _build_source_registry() -> dict[str, type]: from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.sources.dict_source import DictSource from orcapod.core.sources.list_source import ListSource + from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource from orcapod.core.sources.spiraldb_table_source import SpiralDBTableSource from orcapod.core.sources.sqlite_table_source import SQLiteTableSource - from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource return { CSVSource.SOURCE_KIND: CSVSource, @@ -354,8 +353,7 @@ def _build_data_function_registry() -> dict[str, type]: Returns: Dict mapping type ID strings to data function classes. """ - from orcapod.core.data_function import PythonDataFunction - from orcapod.core.data_function import PYTHON_FUNCTION + from orcapod.core.data_function import PYTHON_FUNCTION, PythonDataFunction return { PYTHON_FUNCTION.type_id: PythonDataFunction, @@ -377,9 +375,9 @@ def _build_data_function_registry() -> dict[str, type]: def _get_observer_registry() -> dict[str, type[_Observer]]: global _observer_registry if _observer_registry is None: - from orcapod.pipeline.status_observer import StatusObserver - from orcapod.pipeline.logging_observer import LoggingObserver from orcapod.pipeline.composite_observer import CompositeObserver + from orcapod.pipeline.logging_observer import LoggingObserver + from orcapod.pipeline.status_observer import StatusObserver _observer_registry = { "status": StatusObserver, @@ -507,7 +505,7 @@ def resolve_database_from_config( #: The kinds of connector a message may name. -_CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb") +_CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb_keyed") def saved_database_kind(config: Any) -> str: @@ -562,9 +560,9 @@ def saved_connector_kind(config: Any) -> str | None: 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. + ``"sqlite"``, ``"postgresql"`` or ``"spiraldb_keyed"`` for a known connector, + ``"unknown connector kind"`` for any other connector, or ``None`` for a database + that is not over a connector. """ from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE @@ -585,10 +583,9 @@ def saved_connector_kind(config: Any) -> str | None: def spiraldb_saved_config_refusal(config: Any) -> str | None: """Why a saved SpiralDB connector configuration is not read, or ``None``. - A saved SpiralDB connector with a ``store`` key (not an option of this version: - ``writable`` is), or a ``writable`` that is not a boolean, is refused whatever - database is given, also when none is: ``PipelineJob.load`` checks it before it - asks for a missing connector, so an old file is told about ``writable=True``. + ``PipelineJob.load`` checks this before asking for a missing connector. It + refuses the retired ``spiraldb`` type, configurations with a ``store`` key, + and a ``writable`` value that is not a boolean. Args: config: The saved database configuration. @@ -597,11 +594,26 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: The reason, or ``None`` when the configuration is not a SpiralDB connector's or is one this version reads. """ - from orcapod.databases.spiraldb_connector import STORE_KEY_REFUSAL + from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE + from orcapod.databases.spiraldb_keyed.connector import STORE_KEY_REFUSAL - if saved_connector_kind(config) != "spiraldb": + if not isinstance(config, dict): + return None + database = cast("dict[str, Any]", config) + connector = database.get("connector") + if database.get("type") != CONNECTOR_DATABASE_TYPE or not isinstance( + connector, dict + ): + return None + saved = cast("dict[str, Any]", connector) + kind = saved.get("connector_type") + if kind == "spiraldb": + return ( + "saved connector_type 'spiraldb' is unsupported; use 'spiraldb_keyed' " + "with SpiralDBKeyedConnector" + ) + if kind != "spiraldb_keyed": return None - saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) if "store" in saved: return STORE_KEY_REFUSAL writable = saved.get("writable", False) @@ -609,7 +621,7 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: return ( f"the saved SpiralDB connector's 'writable' is {writable!r}; it must be " "true or false (writable=True makes a writable SpiralDB database: " - "SpiralDBConnector(..., writable=True), saved as 'writable': true)" + "SpiralDBKeyedConnector(..., writable=True), saved as 'writable': true)" ) return None @@ -617,7 +629,7 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """Why a database given at load cannot stand for a saved SpiralDB one, or ``None``. - A job saved on a writable SpiralDB database (``SpiralDBConnector(..., + A job saved on a writable SpiralDB database (``SpiralDBKeyedConnector(..., writable=True)``, ITL-1844) is loaded with a writable connector, and one saved on a plain SpiralDB connector with a plain one: the two read different tables. The project and dataset are not compared (a job may be pointed at a copy). A saved @@ -634,18 +646,18 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector if (refusal := spiraldb_saved_config_refusal(config)) is not None: return refusal - if saved_connector_kind(config) != "spiraldb": + if saved_connector_kind(config) != "spiraldb_keyed": return None saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) given = unwrap_database_views(given) # a library view over the connector database if not isinstance(given, ConnectorArrowDatabase): return None connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over - if not isinstance(connector, SpiralDBConnector): + if not isinstance(connector, SpiralDBKeyedConnector): return None saved_writable = saved.get("writable", False) is True given_writable = connector._writable # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a writable database @@ -654,7 +666,7 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: if saved_writable: return ( "the job was saved on a writable SpiralDB database: pass a writable " - "connector, SpiralDBConnector(..., writable=True)" + "connector, SpiralDBKeyedConnector(..., writable=True)" ) return ( "the job was saved on a plain SpiralDB connector: pass one without " diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index ce7117d25..4a1d9c35e 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -2,12 +2,13 @@ from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager -from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol if TYPE_CHECKING: import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit @@ -392,7 +393,7 @@ class FieldMetadataKeepingDatabaseProtocol(Protocol): ``InMemoryArrowDatabase`` and ``DeltaTableDatabase`` keep it. A ``ConnectorArrowDatabase`` keeps it when its connector does: a connector states it - with the same member (``SpiralDBConnector`` does; ``SQLiteConnector`` and + with the same member (``SpiralDBKeyedConnector`` does; ``SQLiteConnector`` and ``PostgreSQLConnector`` do not). ``ExtensionAwareDatabase`` states what the database it wraps states. ``NoOpArrowDatabase`` keeps nothing. """ diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index 1fd57380f..2a6bc0654 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -7,13 +7,13 @@ Planned implementations: SQLiteConnector -- PLT-1076 (stdlib sqlite3, zero extra deps) PostgreSQLConnector -- PLT-1075 (psycopg3) - SpiralDBConnector -- PLT-1074 + SpiralDBKeyedConnector -- PLT-1074 """ from __future__ import annotations from collections.abc import Iterator -from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.types import ColumnInfo @@ -43,7 +43,7 @@ class DBConnectorProtocol(Protocol): DB-native type conversion internally. Planned implementations: ``SQLiteConnector`` (PLT-1076), - ``PostgreSQLConnector`` (PLT-1075), ``SpiralDBConnector`` (PLT-1074). + ``PostgreSQLConnector`` (PLT-1075), ``SpiralDBKeyedConnector`` (PLT-1074). """ # ── Schema introspection ────────────────────────────────────────────────── @@ -200,7 +200,7 @@ def to_config(self) -> dict[str, Any]: """Serialize connection configuration to a JSON-compatible dict. The returned dict must include a ``"connector_type"`` key - (e.g., ``"sqlite"``, ``"postgresql"``, ``"spiraldb"``) so that + (e.g., ``"sqlite"``, ``"postgresql"``, ``"spiraldb_keyed"``) so that a registry helper can dispatch to the correct ``from_config`` classmethod when deserializing. """ diff --git a/tests/test_changelog_fragments.py b/tests/test_changelog_fragments.py index 4a03c5755..6e8bdf665 100644 --- a/tests/test_changelog_fragments.py +++ b/tests/test_changelog_fragments.py @@ -97,6 +97,17 @@ def test_repository_fragments_directory_has_a_readme() -> None: assert (REPO_ROOT / "changelog.d" / "README.md").is_file() +def test_unreleased_fragments_do_not_advertise_removed_spiraldb_lease_apis() -> None: + for fragment in (REPO_ROOT / "changelog.d").glob("*.md"): + text = fragment.read_text(encoding="utf-8") + for retired_api in ( + "spiraldb_lease.clear", + "LeaseBusyError", + "SpiralDBLeaseRequiredError", + ): + assert retired_api not in text, fragment.name + + # --- --check ------------------------------------------------------------------------ diff --git a/tests/test_core/data_tags/test_database_capability.py b/tests/test_core/data_tags/test_database_capability.py index 5cc6769e8..d11e718df 100644 --- a/tests/test_core/data_tags/test_database_capability.py +++ b/tests/test_core/data_tags/test_database_capability.py @@ -20,14 +20,14 @@ import orcapod as op from orcapod.contexts import resolve_context -from orcapod.core.operators import Join from orcapod.core.data_tags import mark_data_tags +from orcapod.core.operators import Join from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, NoOpArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.sqlite_connector import SQLiteConnector @@ -111,7 +111,7 @@ def _source() -> op.sources.DictSource: def test_each_database_states_the_capability(tmp_path: Path, spiral: None) -> None: sqlite = ConnectorArrowDatabase(SQLiteConnector(":memory:")) - spiraldb = ConnectorArrowDatabase(SpiralDBConnector("p")) + spiraldb = ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) stated = { "in memory": InMemoryArrowDatabase(), "delta": DeltaTableDatabase(tmp_path / "delta"), diff --git a/tests/test_core/sources/test_discovered_results.py b/tests/test_core/sources/test_discovered_results.py index 36536bc74..d996881b2 100644 --- a/tests/test_core/sources/test_discovered_results.py +++ b/tests/test_core/sources/test_discovered_results.py @@ -28,7 +28,7 @@ DeltaTableDatabase, ExtensionAwareDatabase, InMemoryArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.databases.write_lock import NoWriteLock from orcapod.errors import ( @@ -129,7 +129,7 @@ def memory(name: str = "results") -> InMemoryArrowDatabase: else: with fake_spiral_sdk.install(tmp_path): yield lambda name="results": ConnectorArrowDatabase( - SpiralDBConnector("p", name, writable=True) + SpiralDBKeyedConnector("p", name, writable=True) ) @@ -520,7 +520,7 @@ def test_spiral_discovery_and_source_reads_do_not_write( ) -> None: """Read stored results or refuse plain mode without attempting any write.""" with fake_spiral_sdk.install(tmp_path): - writer = SpiralDBConnector("p", "results", writable=True) + writer = SpiralDBKeyedConnector("p", "results", writable=True) job, _ = _job(ConnectorArrowDatabase(writer), _input("reader", 10)) _run(job, asynchronous=False) writer.close() @@ -545,7 +545,7 @@ def test_spiral_discovery_and_source_reads_do_not_write( for owner, method in mutators } database = ConnectorArrowDatabase( - SpiralDBConnector("p", "results", writable=writable) + SpiralDBKeyedConnector("p", "results", writable=writable) ) if writable: (entry,) = discover_function_results(database) @@ -588,7 +588,7 @@ def test_discovery_recovers_an_ordinary_pipeline_without_its_function_module( with fake_spiral_sdk.install(tmp_path): assert_discovery_without_function_module( lambda: ConnectorArrowDatabase( - SpiralDBConnector("p", "results", writable=True) + SpiralDBKeyedConnector("p", "results", writable=True) ), ("spiral-fake", str(tmp_path), "p", "results"), tmp_path, @@ -633,7 +633,7 @@ def reopen_discovery_database( overrides = ( {"server.url": url} if url and backend == "spiral-live" else None ) - with SpiralDBConnector( + with SpiralDBKeyedConnector( project, dataset, overrides, writable=True ) as connector: yield ConnectorArrowDatabase(connector).at(*prefix) diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 956c69e77..f3136c949 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -22,12 +22,12 @@ import pytest from orcapod import PipelineJob -from orcapod.databases import spiraldb_connector as connector_module from orcapod.databases import ( InMemoryArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) -from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE +from orcapod.databases.spiraldb_keyed import connector as connector_module +from orcapod.databases.spiraldb_keyed.schema_table import SCHEMA_TABLE from orcapod.errors import InputValidationError from orcapod.operators import SelectColumns from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator @@ -726,7 +726,7 @@ def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: def test_the_connector_getters_answer_as_the_handle_does( calls: collections.Counter[str], ) -> None: - with SpiralDBConnector(project_id=_PROJECT) as connector: + with SpiralDBKeyedConnector(project_id=_PROJECT) as connector: table = connector.lookup_table("t") # The key columns in the table's key order. assert connector.get_pk_columns("t") == table.key_columns == _ARRANGED["keys"] diff --git a/tests/test_core/sources/test_spiraldb_table_source.py b/tests/test_core/sources/test_spiraldb_table_source.py index ed77d1387..ebe6ae7d5 100644 --- a/tests/test_core/sources/test_spiraldb_table_source.py +++ b/tests/test_core/sources/test_spiraldb_table_source.py @@ -2,7 +2,7 @@ SpiralDB needs network access and credentials, so these tests run against the disk-backed pyspiral fake (``tests/test_databases/fake_spiral_sdk.py``): the source goes -through the real ``SpiralDBConnector``. Reading in batches, restrictions, the row cap and +through the real ``SpiralDBKeyedConnector``. Reading in batches, restrictions, the row cap and record identity are in ``test_spiraldb_table_source_streaming.py``; the end-to-end test is in ``test_spiraldb_table_source_fake.py``. @@ -30,13 +30,13 @@ import pytest from orcapod.core.sources import SpiralDBTableSource -from orcapod.databases import SpiralDBConnector -from orcapod.databases.spiraldb_connector import SpiralDBTable +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed.connector import SpiralDBTable from tests.test_databases import fake_spiral_sdk _TABLE_NAME = "spike_data" _PROJECT_ID = "test-project-123456" -_CONNECTOR = "orcapod.core.sources.spiraldb_table_source.SpiralDBConnector" +_CONNECTOR = "orcapod.core.sources.spiraldb_table_source.SpiralDBKeyedConnector" def _make_table( @@ -251,10 +251,10 @@ class TestConnector: """The source forwards its arguments to the connector and closes it.""" def test_dataset_and_overrides_forwarded_to_connector(self): - """``dataset`` and ``overrides`` are forwarded to ``SpiralDBConnector``.""" + """``dataset`` and ``overrides`` are forwarded to ``SpiralDBKeyedConnector``.""" overrides = {"server.url": "http://api.spiraldb.dev"} _make_table(dataset="prod") - with patch(_CONNECTOR, wraps=SpiralDBConnector) as connector_class: + with patch(_CONNECTOR, wraps=SpiralDBKeyedConnector) as connector_class: SpiralDBTableSource( _PROJECT_ID, _TABLE_NAME, @@ -269,11 +269,11 @@ def test_dataset_and_overrides_forwarded_to_connector(self): def test_every_connector_is_closed(self): """Close the shared connector at context exit or failed construction.""" _make_table() - opened: list[SpiralDBConnector] = [] + opened: list[SpiralDBKeyedConnector] = [] def connect(**kwargs): """Open a real connector with ``kwargs`` and record it in ``opened``.""" - opened.append(SpiralDBConnector(**kwargs)) + opened.append(SpiralDBKeyedConnector(**kwargs)) return opened[-1] with patch(_CONNECTOR, side_effect=connect): diff --git a/tests/test_core/sources/test_spiraldb_table_source_fake.py b/tests/test_core/sources/test_spiraldb_table_source_fake.py index 371dc9601..3d1d6bc7d 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_fake.py +++ b/tests/test_core/sources/test_spiraldb_table_source_fake.py @@ -259,7 +259,7 @@ class TestSourceId: def two_projects(self, tmp_path: Path): """Provide two fake projects holding the same one-row ``item_profile`` table. - Each is written through ``SpiralDBConnector``, which records its non-nullable + Each is written through ``SpiralDBKeyedConnector``, which records its non-nullable columns (ITL-936); ``default.unrecorded`` holds the same row without a record. """ with fake_spiral_sdk.install(tmp_path / "spiral"): @@ -400,7 +400,7 @@ class TestNonNullableColumns: SpiralDB reports every column and struct field nullable, so this holds only for tables that carry Orcapod's nullability record: here, tables written through - ``SpiralDBConnector``. The same rows written without the record read as ``T | None``. + ``SpiralDBKeyedConnector``. The same rows written without the record read as ``T | None``. """ _KEYS = pa.schema( diff --git a/tests/test_core/test_result_cache.py b/tests/test_core/test_result_cache.py index 8102f9555..ba3428816 100644 --- a/tests/test_core/test_result_cache.py +++ b/tests/test_core/test_result_cache.py @@ -14,21 +14,20 @@ from pathlib import Path import pyarrow as pa - import pytest from orcapod.contexts import get_default_context from orcapod.core import result_cache -from orcapod.core.datagrams import Datagram, Data -from orcapod.core.datagrams.tag_data import EmptyData from orcapod.core.data_function import PythonDataFunction +from orcapod.core.datagrams import Data, Datagram +from orcapod.core.datagrams.tag_data import EmptyData from orcapod.core.result_cache import ResultCache from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, ExtensionAwareDatabase, InMemoryArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.errors import OrcapodDatabaseWriteError, UnrecordedTableSchemaWarning from orcapod.protocols.core_protocols.datagrams import DataProtocol @@ -184,7 +183,7 @@ def check(cache: ResultCache, expected: DataProtocol) -> None: # rows. The fake SDK's write API refuses Orcapod's reserved column names. key = ConnectorArrowDatabase.RECORD_ID_COLUMN name = "__".join(cache.record_path) - with fake_spiral_sdk.install(spiral_root), SpiralDBConnector("p") as connector: + with fake_spiral_sdk.install(spiral_root), SpiralDBKeyedConnector("p") as connector: project = fake_spiral_sdk.FakeClient().project("p") table = project.create_keyed_table( "default", diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 32d02f6f0..1d8c56b7e 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -32,7 +32,7 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE +from orcapod.databases.spiraldb_keyed.schema_table import SCHEMA_TABLE RULES = { "missing": "a missing table or dataset: SpiralError 'resource not found: " @@ -1259,10 +1259,13 @@ def install(root: Path | str): """Route Orcapod's SpiralDB calls to the fake, with tables stored under ``root``.""" with ( patch.dict(os.environ, {_ROOT_ENV: str(root)}), - patch("orcapod.databases.spiraldb_connector.sp", fake_module), - patch("orcapod.databases.spiraldb_connector.require_sign_in", lambda: None), + patch("orcapod.databases.spiraldb_keyed.connector.sp", fake_module), patch( - "orcapod.databases.spiraldb_connector._http_get_json", fake_http_get_json + "orcapod.databases.spiraldb_keyed.connector.require_sign_in", lambda: None + ), + patch( + "orcapod.databases.spiraldb_keyed.connector._http_get_json", + fake_http_get_json, ), ): yield @@ -1286,7 +1289,7 @@ def migrate( dataset: The dataset. complete: Whether to write the marker. """ - from orcapod.databases import spiraldb_schema_table as st + from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.utils import arrow_utils store = _store() diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index aae3c2926..5a1ae2886 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -14,10 +14,9 @@ import pyarrow as pa import pytest +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.databases.store_table_names import store_table_name -from orcapod.databases import SpiralDBConnector -from orcapod.databases import spiraldb_schema_table as st - from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -121,7 +120,7 @@ def args( # The reads the dry run makes, with the schemas in place; then they are taken away. for dataset in _DATASETS: fake.migrate("p", dict.fromkeys(_TABLES, _WRITTEN), dataset) - connector = SpiralDBConnector("p", dataset) + connector = SpiralDBKeyedConnector("p", dataset) for table in described[dataset]["tables"]: name = table["row"]["table_name"] table["source"] = tool.source_values("p", dataset, name) @@ -151,7 +150,7 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: tool.verify(args) for dataset in _DATASETS: for name in _TABLES: - schema = SpiralDBConnector("p", dataset).get_arrow_schema(name) + schema = SpiralDBKeyedConnector("p", dataset).get_arrow_schema(name) assert schema.metadata == {b"who": b"test"} assert not schema.field("v").nullable assert schema.field("v").metadata == {b"unit": b"mV"} @@ -238,7 +237,7 @@ def _legacy_listing( ) opened: list[tuple[str, str]] = [] - class LegacyConnector(SpiralDBConnector): + class LegacyConnector(SpiralDBKeyedConnector): """The connector of one dataset, serving that dataset's reserved tables.""" def lookup_table(self, table_name: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] # a stand-in handle @@ -265,7 +264,8 @@ def lookup_table(self, table_name: str) -> Any: # pyright: ignore[reportIncompa lambda _connector, _project, dataset, name: descriptions[dataset, name], ) monkeypatch.setattr( - "orcapod.databases.spiraldb_connector.SpiralDBConnector", LegacyConnector + "orcapod.databases.spiraldb_keyed.connector.SpiralDBKeyedConnector", + LegacyConnector, ) return plan, opened @@ -280,6 +280,44 @@ def _lease_key(n: int, arrow_type: pa.DataType | None = None) -> list[pa.Field[A return _key(f"{SPIRAL_LEASE_KEY_PREFIX}{n:032x}", arrow_type) +@pytest.mark.parametrize("keyed_available", [True, False], ids=["keyed", "pre-rename"]) +def test_dry_run_loads_the_connector_for_the_installed_version( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + keyed_available: bool, +) -> None: + """Both connector module layouts support the same synthetic dry run.""" + dataset = args.dataset[0] + lease = spiral_lease_table_name(1) + plan, opened = _legacy_listing( + tool, args, monkeypatch, [(dataset, lease, _lease_key(1))] + ) + keyed = "orcapod.databases.spiraldb_keyed.connector" + previous = "orcapod.databases.spiraldb_connector" + load = importlib.import_module + constructor = load(keyed).SpiralDBKeyedConnector + imported: list[str] = [] + + def load_connector(name: str) -> Any: + imported.append(name) + if not keyed_available: + if name == keyed: + raise ModuleNotFoundError(name="orcapod.databases.spiraldb_keyed") + if name == previous: + return SimpleNamespace(SpiralDBConnector=constructor) + return load(name) + + monkeypatch.setattr( + tool, "importlib", SimpleNamespace(import_module=load_connector) + ) + tool.dry_run(args) + + assert imported == ([keyed] if keyed_available else [keyed, previous]) + assert opened == [(dataset, lease)] + assert tool.read_plan(args.plan) == plan + + def test_dry_run_and_write_skip_lease_generations( tool: ModuleType, args: argparse.Namespace, @@ -418,7 +456,7 @@ def test_the_dry_run_reads_raise_no_keyed_table_deprecation( """The dry run's reads of each table go through the connector, which ignores the SDK's keyed-table deprecation for its own opens, after an earlier open too.""" fake.migrate("p", dict.fromkeys(_TABLES, _WRITTEN), "one") - connector = SpiralDBConnector("p", "one") + connector = SpiralDBKeyedConnector("p", "one") _ = connector.lookup_table("trials") # an earlier open, before the error filter with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) diff --git a/tests/test_databases/test_spiral_database_identity.py b/tests/test_databases/test_spiral_database_identity.py index 784e83aa3..e3fa53c7e 100644 --- a/tests/test_databases/test_spiral_database_identity.py +++ b/tests/test_databases/test_spiral_database_identity.py @@ -16,9 +16,8 @@ import pyarrow as pa import pytest -from orcapod.databases import spiral_database_codec -from orcapod.databases import spiral_database_identity as names -from orcapod.databases import store_table_names +from orcapod.databases import spiral_database_codec, store_table_names +from orcapod.databases.spiraldb_keyed import identity as names H = "0123456789abcdef" * 4 RESULT = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") @@ -416,7 +415,7 @@ def __getitem__(self, index: int | slice) -> str | Sequence[str]: def test_the_layout_is_the_last_component_of_the_path_recorded() -> None: - """Thread on spiral_database_identity.py:147: the layout is taken from the validated + """The keyed identity module takes the layout from the validated snapshot of the path, so a path that reads differently later records one path.""" record = names.table_identity_metadata(_ShiftingPath(), "std:v1:default") found = names.read_table_identity_metadata(record) diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index c1aed3337..0811159ad 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -29,18 +29,18 @@ RowsOnRead, _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class ) -from orcapod.core.streams.arrow_table_stream import ArrowTableStream, pending_whole_read from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.core.streams.arrow_table_stream import ArrowTableStream, pending_whole_read +from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table +from orcapod.core.streams.view import display_name from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.errors import SourceCheckFailedWarning -from orcapod.databases import spiraldb_connector as connector_module from orcapod.pipeline import ( AsyncPipelineOrchestrator, SyncPipelineOrchestrator, column_demand, ) -from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table -from orcapod.core.streams.view import display_name from orcapod.pipeline.dag import OrcaDAG from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py similarity index 98% rename from tests/test_databases/test_spiraldb_connector_integration.py rename to tests/test_databases/test_spiraldb_keyed_connector_integration.py index c8d158eb2..c6cb5cd09 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -33,10 +33,10 @@ import pyarrow.compute as pc import pytest -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector -from orcapod.databases import spiraldb_connector as connector_module -from orcapod.databases import spiraldb_schema_table as st -from orcapod.databases.spiraldb_connector import SpiralDBTableNotFoundError +from orcapod.databases import ConnectorArrowDatabase, 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.sources import SpiralDBTableSource from orcapod.types import Condition, col from tests.test_core.sources.test_discovered_results import ( @@ -76,7 +76,7 @@ def test_live_discovery_recovers_an_ordinary_pipeline( def open_database() -> ConnectorArrowDatabase: connector = connectors.enter_context( - SpiralDBConnector( + SpiralDBKeyedConnector( _PROJECT, _DISCOVERY_DATASET, {"server.url": _URL}, writable=True ) ) @@ -211,9 +211,9 @@ class _Place: dataset: str overrides: dict[str, str] | None - def connector(self) -> SpiralDBConnector: + def connector(self) -> SpiralDBKeyedConnector: """Return a new connector.""" - return SpiralDBConnector(self.project, self.dataset, self.overrides) + return SpiralDBKeyedConnector(self.project, self.dataset, self.overrides) def source(self, name: str, **options: Any) -> SpiralDBTableSource: """Return a source on a table.""" @@ -416,7 +416,7 @@ def test_versions(place: _Place) -> None: def test_a_missing_table_and_dataset(place: _Place) -> None: with pytest.raises(SpiralDBTableNotFoundError): place.connector().lookup_table("absent") - missing = SpiralDBConnector(place.project, "absent_dataset", place.overrides) + missing = SpiralDBKeyedConnector(place.project, "absent_dataset", place.overrides) with pytest.raises(SpiralDBTableNotFoundError): missing.lookup_table("absent") assert missing.get_table_names() == [] diff --git a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py index 48ce773b6..28df80117 100644 --- a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py +++ b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py @@ -16,9 +16,11 @@ sp = pytest.importorskip("spiral") -from orcapod.databases import spiraldb_connector # noqa: E402 # after the skip -from orcapod.databases.spiraldb_connector import ( # noqa: E402 # after the skip - SpiralDBConnector, +from orcapod.databases.spiraldb_keyed import ( # noqa: E402 # after the skip + connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed.connector import ( # noqa: E402 # after the skip + SpiralDBKeyedConnector, SpiralDBTableNotFoundError, ) @@ -65,19 +67,19 @@ class _SDK: @pytest.fixture -def connector() -> Iterator[SpiralDBConnector]: +def connector() -> Iterator[SpiralDBKeyedConnector]: """A connector on the real spiral-sdk client over the stub native client.""" with ( patch.object(spiraldb_connector, "sp", _SDK), patch.object(spiraldb_connector, "require_sign_in", lambda: None), ): - made = SpiralDBConnector("p", "d") + made = SpiralDBKeyedConnector("p", "d") yield made made.close() def test_orcapod_opens_keyed_tables_with_no_deprecation_warning( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """With every warning an error, Orcapod's opens of a table (by name, found and not found) and of a version (by id) raise what the stub raises, never the deprecation.""" @@ -91,7 +93,7 @@ def test_orcapod_opens_keyed_tables_with_no_deprecation_warning( _ = table.arrow_schema(asof=2) -def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: +def test_a_direct_sdk_open_still_warns(connector: SpiralDBKeyedConnector) -> None: """The filter Orcapod installs covers its own module only: an open called from another module (this test), by name or by id, still warns, after Orcapod's open.""" client = _Client() @@ -105,7 +107,7 @@ def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: def test_an_error_filter_added_after_an_open_does_not_reach_orcapods_opens( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """The first matching filter wins: an error filter added after Orcapod's first open ranks ahead of a filter that is merely present. Orcapod's later opens, by name and @@ -120,7 +122,7 @@ def test_an_error_filter_added_after_an_open_does_not_reach_orcapods_opens( def test_a_pytest_warns_block_after_an_open_records_no_deprecation( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """``pytest.warns`` adds an "always" filter; Orcapod's opens inside it, after an earlier open, record nothing of the SDK's deprecation.""" @@ -135,7 +137,7 @@ def test_a_pytest_warns_block_after_an_open_records_no_deprecation( def test_the_filter_is_kept_once_however_often_orcapod_opens( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """Moved to the front rather than added again: the filter list never grows.""" with warnings.catch_warnings(): diff --git a/tests/test_databases/test_spiraldb_projection.py b/tests/test_databases/test_spiraldb_projection.py index 65e148068..945a45ebf 100644 --- a/tests/test_databases/test_spiraldb_projection.py +++ b/tests/test_databases/test_spiraldb_projection.py @@ -19,7 +19,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.sources import spiraldb_table_source as source_module from orcapod.databases import InMemoryArrowDatabase -from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.sources import SpiralDBTableSource from orcapod.types import ColumnConfig, Condition from tests.test_databases import fake_spiral_sdk as fake diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index 453c57dd4..2e659af5b 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -6,9 +6,9 @@ from __future__ import annotations -import gc import asyncio import datetime as dt +import gc import math import os import signal @@ -25,9 +25,9 @@ import pytest from orcapod import PipelineJob, function_pod -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector from orcapod.core.sources import spiraldb_table_source as source_module -from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -36,8 +36,7 @@ ) from orcapod.nodes import FunctionJobNode from orcapod.sources import DictSource, SpiralDBTableSource -from orcapod.types import ColumnInfo -from orcapod.types import Condition +from orcapod.types import ColumnInfo, Condition from tests.test_databases import fake_spiral_sdk as fake _ITEM = pa.field("item", pa.float32(), False) @@ -90,7 +89,7 @@ def _keys(source: SpiralDBTableSource) -> list[tuple[Any, Any]]: def test_a_recorded_table_is_read_with_its_schema(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") schema = connector.get_arrow_schema("units") # SpiralDB's order: keys in key order, then by name, structs last, their fields too. assert schema.names == ["k2", "k1", "a", "z", "g"] @@ -126,7 +125,7 @@ def test_rows_come_in_key_order_and_values_are_kept(project: Any) -> None: (2, "a"), (1, "b"), ] - table = pa.Table.from_batches(SpiralDBConnector("p").scan_batches("units")) + table = pa.Table.from_batches(SpiralDBKeyedConnector("p").scan_batches("units")) expected = {(r["k2"], r["k1"]): r for r in _rows().to_pylist()} assert {(r["k2"], r["k1"]): r for r in table.to_pylist()} == expected @@ -160,7 +159,7 @@ def test_a_null_in_a_recorded_column_is_refused(project: Any) -> None: project.table("default.units").write(nulls) fake.migrate("p", {"units": _WRITTEN}) with pytest.raises(NullInNonNullableColumnError, match="units.*z|z.*units"): - list(SpiralDBConnector("p").scan_batches("units")) + list(SpiralDBKeyedConnector("p").scan_batches("units")) # ------------------------------------------------------------ a table that is not recorded @@ -183,11 +182,11 @@ def test_an_unrecorded_table_warns_once_and_reads_nullable( with pytest.warns(UnrecordedTableSchemaWarning, match=_unrecorded(name)) as seen: source = SpiralDBTableSource("p", name, tag_only_columns=True) _ = source.as_table() - _ = SpiralDBConnector("p").get_arrow_schema(name) + _ = SpiralDBKeyedConnector("p").get_arrow_schema(name) assert len(seen) == 1 assert "migrate_spiral_schemas.py" in str(seen[0].message) assert seen[0].filename == __file__ - schema = SpiralDBConnector("p").get_arrow_schema(name) + schema = SpiralDBKeyedConnector("p").get_arrow_schema(name) assert all(f.nullable and not f.metadata for f in schema) @@ -205,14 +204,14 @@ def test_a_recorded_table_warns_nothing(project: Any) -> None: with warnings.catch_warnings(): warnings.simplefilter("error") SpiralDBTableSource("p", "units", tag_only_columns=True).as_table() - assert SpiralDBConnector("p").get_table_names() == ["swapped", "units"] + assert SpiralDBKeyedConnector("p").get_table_names() == ["swapped", "units"] def test_a_recorded_table_that_is_gone_is_warned_about(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) project.drop_table("default.swapped") with pytest.warns(UnrecordedTableSchemaWarning, match="no longer holds.*swapped"): - assert SpiralDBConnector("p").get_table_names() == ["units"] + assert SpiralDBKeyedConnector("p").get_table_names() == ["units"] # ------------------------------------------------------------------ a row that disagrees @@ -232,7 +231,7 @@ def test_an_older_version_with_other_columns_is_refused(project: Any) -> None: pa.table({"k2": pa.array([9], pa.int32()), "k1": ["z"], "new": [1]}) ) fake.migrate("p", {}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") assert len(list(connector.scan_batches("units"))) > 0 with pytest.raises(TableSchemaError, match="not in the table: .'new'"): list(connector.scan_batches("units", asof=1)) @@ -257,7 +256,7 @@ def test_a_recreated_table_is_not_read_with_the_old_row(project: Any) -> None: pa.table({"k": ["a"], "v": [1]}) ) with pytest.warns(UnrecordedTableSchemaWarning, match="units has no row"): - schema = SpiralDBConnector("p").get_arrow_schema("units") + schema = SpiralDBKeyedConnector("p").get_arrow_schema("units") assert schema.names == ["k", "v"] @@ -366,7 +365,7 @@ def test_where_matches_as_the_service_does( project: Any, column: str, value: Any, expected: list[int] ) -> None: project.create_table("default.typed", key_schema=[("k", pa.int64())]).write(_TYPED) - batches = SpiralDBConnector("p").scan_batches( + batches = SpiralDBKeyedConnector("p").scan_batches( "typed", where=Condition.of({column: value}) ) assert [k for b in batches for k in b.column("k").to_pylist()] == expected @@ -383,7 +382,7 @@ def test_a_filter_applied_here_comes_before_the_limit(project: Any, limit: int) ) project.create_table("default.half", key_schema=[("k", pa.int64())]).write(rows) for where in ({"h": 2.0, "s": "x"}, {"s": "x", "h": 2.0}): - batches = SpiralDBConnector("p").scan_batches( + batches = SpiralDBKeyedConnector("p").scan_batches( "half", where=Condition.of(where), limit=limit ) found = [k for b in batches for k in b.column("k").to_pylist()] @@ -415,7 +414,9 @@ def test_every_equality_applied_here_holds( Condition.of(Condition.of(h=first), Condition.of(h=second)), Condition.of(Condition.of(h=first), Condition.of(s="x", h=second)), ): - batches = SpiralDBConnector("p").scan_batches("half", where=where, limit=limit) + batches = SpiralDBKeyedConnector("p").scan_batches( + "half", where=where, limit=limit + ) found = [k for b in batches for k in b.column("k").to_pylist()] if first != second: assert found == [] @@ -472,7 +473,7 @@ def test_warnings_from_many_threads_stop_once_shown(project: Any) -> None: def build(_: int) -> None: barrier.wait(10) - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") def shown(seen: list[warnings.WarningMessage]) -> int: return len([w for w in seen if w.category is UnrecordedTableSchemaWarning]) @@ -496,7 +497,7 @@ def test_every_concurrent_reader_raises_with_the_warning_as_an_error( def build(_: int) -> str: barrier.wait(10) try: - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") except UnrecordedTableSchemaWarning: return "raised" return "passed" @@ -519,7 +520,8 @@ def hook(*given: Any, **options: Any) -> None: if readers: return reader = threading.Thread( - target=lambda: SpiralDBConnector("p").get_arrow_schema(table), daemon=True + target=lambda: SpiralDBKeyedConnector("p").get_arrow_schema(table), + daemon=True, ) readers.append(reader) reader.start() @@ -529,7 +531,7 @@ def hook(*given: Any, **options: Any) -> None: with warnings.catch_warnings(): warnings.simplefilter("always", UnrecordedTableSchemaWarning) monkeypatch.setattr(warnings, "showwarning", hook) - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") assert finished == [True] @@ -540,13 +542,13 @@ def test_a_warning_hook_may_read_the_table_itself( def hook(*given: Any, **options: Any) -> None: calls.append(1) - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") with warnings.catch_warnings(): warnings.simplefilter("always", UnrecordedTableSchemaWarning) monkeypatch.setattr(warnings, "showwarning", hook) - SpiralDBConnector("p").get_arrow_schema("units") - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") assert calls == [1] @@ -565,7 +567,7 @@ def slow(*given: Any, **options: Any) -> None: def build() -> str: try: - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") except UnrecordedTableSchemaWarning: return "raised" return "passed" @@ -588,7 +590,7 @@ def second() -> str: def test_a_count_is_remembered_per_version(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) fake.count_log.clear() - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") assert connector.lookup_table("units").count_rows(at_most=2) == 2 assert connector.lookup_table("units").count_rows(at_most=1) == 1 assert connector.lookup_table("units").count_rows() == 3 @@ -611,7 +613,7 @@ def test_the_listing_reads_every_page(tmp_path: Path, count: int) -> None: for i in range(count): made.create_table(f"ds.t{i}", key_schema=[("k", pa.string())]) made.create_table(f"other.t{i}", key_schema=[("k", pa.string())]) - names = SpiralDBConnector("p q", "ds").get_table_names() + names = SpiralDBKeyedConnector("p q", "ds").get_table_names() assert names == sorted(f"t{i}" for i in range(count)) @@ -627,7 +629,7 @@ def test_a_listing_that_does_not_advance_is_refused( lambda url, token: {"items": [], "nextPageToken": next(tokens)}, ): with pytest.raises(RuntimeError, match="does not advance"): - SpiralDBConnector("p").get_table_names() + SpiralDBKeyedConnector("p").get_table_names() def test_the_token_is_never_sent_on_a_redirect() -> None: @@ -665,7 +667,7 @@ def log_message(self, format: str, *args: Any) -> None: def test_every_write_is_refused_and_writes_nothing(project: Any) -> None: - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") columns = [ColumnInfo("k", pa.large_string(), False)] for write in ( lambda: connector.create_table_if_not_exists("new", columns, "k"), @@ -687,7 +689,7 @@ def test_a_database_refuses_rows_before_it_holds_them( project: Any, flush: bool ) -> None: """Review finding B3.""" - database = ConnectorArrowDatabase(SpiralDBConnector("p")) + database = ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) rows = pa.table({"id": pa.array([b"1"], pa.large_binary()), "v": [1]}) with pytest.raises(SpiralDBWriteNotSupportedError): database.add_records(("t",), rows, record_id_column="id", flush=flush) @@ -705,7 +707,9 @@ def double(v: int) -> int: return 2 * v source = DictSource([{"k": 1, "v": 1}], tag_columns=["k"], source_id="s") - job = PipelineJob(name="j", database=ConnectorArrowDatabase(SpiralDBConnector("p"))) + job = PipelineJob( + name="j", database=ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) + ) with pytest.raises(SpiralDBWriteNotSupportedError): with job: double.pod(source, label="double") @@ -754,20 +758,20 @@ def double(z: float) -> float: def test_the_one_override_is_the_address(project: Any) -> None: overrides = {"server.url": "https://api.example.invalid"} - connector = SpiralDBConnector("p", overrides=overrides) + connector = SpiralDBKeyedConnector("p", overrides=overrides) assert connector._client.api_url == "https://api.example.invalid" # pyright: ignore[reportPrivateUsage] # what the client was given - assert SpiralDBConnector.from_config(connector.to_config()).to_config() == { - "connector_type": "spiraldb", + assert SpiralDBKeyedConnector.from_config(connector.to_config()).to_config() == { + "connector_type": "spiraldb_keyed", "project_id": "p", "dataset": "default", "overrides": overrides, } with pytest.raises(ValueError, match="authn.token"): - SpiralDBConnector("p", overrides={"authn.token": "x", **overrides}) + SpiralDBKeyedConnector("p", overrides={"authn.token": "x", **overrides}) def test_a_closed_connector_reads_nothing(project: Any) -> None: - with SpiralDBConnector("p") as connector: + with SpiralDBKeyedConnector("p") as connector: shared = connector.share_client() handle = connector.lookup_table("units") connector.close() @@ -849,7 +853,7 @@ async def cancel() -> None: def test_many_threads_read_through_one_connector(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") def read(i: int) -> tuple[list[str], int]: name = ("units", "swapped")[i % 2] @@ -865,7 +869,7 @@ def read(i: int) -> tuple[list[str], int]: def test_a_forked_child_is_refused_instead_of_hanging( project: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") monkeypatch.setattr(os, "getpid", lambda: -1) with pytest.raises(RuntimeError, match="after a fork"): connector.lookup_table("units") @@ -938,7 +942,7 @@ def hold() -> None: def test_a_missing_table_is_told_apart_from_other_failures( project: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") with pytest.raises(connector_module.SpiralDBTableNotFoundError): connector.lookup_table("absent") @@ -955,10 +959,10 @@ def denied(*_given: Any, **_options: Any) -> None: "query", ['SELECT * FROM "units"', "select * from units", 'SELECT * FROM "units"'] ) def test_a_query_names_its_table(project: Any, query: str) -> None: - batches = list(SpiralDBConnector("p").iter_batches(query)) + batches = list(SpiralDBKeyedConnector("p").iter_batches(query)) assert sum(b.num_rows for b in batches) == 3 def test_a_query_without_a_table_is_refused(project: Any) -> None: with pytest.raises(ValueError, match="Cannot parse"): - list(SpiralDBConnector("p").iter_batches("SELECT 1")) + list(SpiralDBKeyedConnector("p").iter_batches("SELECT 1")) diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index 71bd018aa..9b66aead8 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -17,11 +17,15 @@ from orcapod.databases import ( ConnectorArrowDatabase, - spiral_database_identity, - spiraldb_connector, ) -from orcapod.databases.spiraldb_tables import RunState, SpiralDBTables -from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.databases.spiraldb_keyed import ( + connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed import ( + identity as spiral_database_identity, +) +from orcapod.databases.spiraldb_keyed.tables import RunState, SpiralDBTables +from orcapod.databases.spiraldb_keyed.write_scope import database_writes from orcapod.types import CacheMode from tests.test_databases import fake_spiral_sdk as fake from tests.test_databases.test_spiraldb_writable_runs import ( @@ -273,7 +277,7 @@ def test_kept_rows_are_what_a_fresh_read_gives() -> None: def fresh() -> list[bytes]: """Read IDs from the service through a connector outside the scope.""" read = ConnectorArrowDatabase( - spiraldb_connector.SpiralDBConnector("p", "d", writable=True) + spiraldb_connector.SpiralDBKeyedConnector("p", "d", writable=True) ).get_all_records(path, record_id_column="__record_id") assert read is not None return sorted(cast("list[bytes]", read.column("__record_id").to_pylist())) diff --git a/tests/test_databases/test_spiraldb_schema_table.py b/tests/test_databases/test_spiraldb_schema_table.py index 07987076d..e80f42f3b 100644 --- a/tests/test_databases/test_spiraldb_schema_table.py +++ b/tests/test_databases/test_spiraldb_schema_table.py @@ -15,8 +15,8 @@ import pyarrow as pa import pytest -from orcapod.databases import SpiralDBConnector -from orcapod.databases import spiraldb_schema_table as st +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -237,15 +237,17 @@ def _edit_schema_table(**change: Any) -> None: # Every way a person reaches a table's rows or what is known of it. _PATHS = { "source": lambda: SpiralDBTableSource("p", "units", tag_only_columns=True), - "schema": lambda: SpiralDBConnector("p").get_arrow_schema("units"), - "columns": lambda: SpiralDBConnector("p").get_column_info("units"), - "batches": lambda: list(SpiralDBConnector("p").scan_batches("units")), - "query": lambda: list(SpiralDBConnector("p").iter_batches('SELECT * FROM "units"')), - "count": lambda: SpiralDBConnector("p").get_row_count_estimate("units"), + "schema": lambda: SpiralDBKeyedConnector("p").get_arrow_schema("units"), + "columns": lambda: SpiralDBKeyedConnector("p").get_column_info("units"), + "batches": lambda: list(SpiralDBKeyedConnector("p").scan_batches("units")), + "query": lambda: list( + SpiralDBKeyedConnector("p").iter_batches('SELECT * FROM "units"') + ), + "count": lambda: SpiralDBKeyedConnector("p").get_row_count_estimate("units"), "bounded count": lambda: ( - SpiralDBConnector("p").lookup_table("units").count_rows(at_most=1) + SpiralDBKeyedConnector("p").lookup_table("units").count_rows(at_most=1) ), - "listing": lambda: SpiralDBConnector("p").get_table_names(), + "listing": lambda: SpiralDBKeyedConnector("p").get_table_names(), } @@ -360,7 +362,7 @@ def test_a_foreign_table_at_the_reserved_name_is_refused(tmp_path: Path) -> None def test_the_reserved_name_is_refused_and_unlisted(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") assert connector.get_table_names() == ["trials", "units"] for use in (connector.lookup_table, connector.get_column_info): with pytest.raises(ValueError, match="reserved"): diff --git a/tests/test_databases/test_spiraldb_sign_in.py b/tests/test_databases/test_spiraldb_sign_in.py index fdb488674..cb3d1eb2b 100644 --- a/tests/test_databases/test_spiraldb_sign_in.py +++ b/tests/test_databases/test_spiraldb_sign_in.py @@ -11,8 +11,9 @@ import pytest -from orcapod.databases import SpiralDBConnector, spiraldb_connector -from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector +from orcapod.databases.spiraldb_keyed.sign_in import require_sign_in, saved_login_path from orcapod.errors import SpiralDBSignInError from orcapod.sources import SpiralDBTableSource @@ -138,7 +139,7 @@ def Client(**_options: object) -> None: monkeypatch.setattr(spiraldb_connector, "sp", NoClient) with pytest.raises(SpiralDBSignInError): - SpiralDBConnector("p") + SpiralDBKeyedConnector("p") with pytest.raises(SpiralDBSignInError): SpiralDBTableSource("p", "t") @@ -151,4 +152,4 @@ class Pyspiral: monkeypatch.setattr(spiraldb_connector, "sp", Pyspiral) with pytest.raises(ImportError, match="pyspiral"): - SpiralDBConnector("p") + SpiralDBKeyedConnector("p") diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 93c8cb106..16cd431ba 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1,6 +1,6 @@ """A SpiralDB connector in writable mode, under ``ConnectorArrowDatabase`` (ITL-1840). -On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBConnector`` built +On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBKeyedConnector`` built with ``writable=True``. The tests cover each table kind's layout written and read back, the write rules of ITL-1386, refusals of tables that are not the database's, the data-context checks and the listing the @@ -28,12 +28,12 @@ ) from orcapod.core.operators import SelectDataColumns from orcapod.core.sources.cached_source import CachedSource -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector from orcapod.databases import spiral_database_codec as codec -from orcapod.databases import spiral_database_identity as identity -from orcapod.databases.spiral_database_identity import SpiralTableCollisionError -from orcapod.databases.spiraldb_tables import SpiralDBTables -from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.databases.spiraldb_keyed import identity as identity +from orcapod.databases.spiraldb_keyed.identity import SpiralTableCollisionError +from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables +from orcapod.databases.spiraldb_keyed.write_scope import database_writes from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -59,12 +59,14 @@ def root(tmp_path: Path) -> Iterator[Path]: yield tmp_path -def writable_connector(project: str = "p", dataset: str = "d") -> SpiralDBConnector: +def writable_connector( + project: str = "p", dataset: str = "d" +) -> SpiralDBKeyedConnector: """A writable connector on the fake service.""" - return SpiralDBConnector(project, dataset, writable=True) + return SpiralDBKeyedConnector(project, dataset, writable=True) -def tables_of(connector: SpiralDBConnector) -> SpiralDBTables: +def tables_of(connector: SpiralDBKeyedConnector) -> SpiralDBTables: tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] assert tables is not None return tables @@ -1065,7 +1067,7 @@ def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: # ------------------------------------------------------ concurrent first writers -def _made_meanwhile(connector: SpiralDBConnector, make: Any) -> None: +def _made_meanwhile(connector: SpiralDBKeyedConnector, make: Any) -> None: """Run ``make`` (another party's act) just before ``connector`` creates or opens a table for its first write.""" tables = tables_of(connector) @@ -1216,7 +1218,7 @@ def test_raw_access_is_refused_in_database_mode() -> None: @pytest.mark.usefixtures("root") def test_a_plain_connector_still_writes_nothing() -> None: """Main's behaviour: a database on a plain connector refuses every write.""" - db = ConnectorArrowDatabase(SpiralDBConnector("p", "d")) + db = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "d")) with pytest.raises(SpiralDBWriteNotSupportedError): db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") with pytest.raises(SpiralDBWriteNotSupportedError): @@ -2317,7 +2319,7 @@ def test_a_database_mode_add_flush_and_listing_raise_no_keyed_table_deprecation( and open one by id itself, and raised). A direct call from elsewhere still warns.""" import warnings - from orcapod.databases import spiraldb_connector + from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector called: dict[str, int] = {} diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 5d29fe1f4..6499d41c1 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -2,7 +2,7 @@ and load (ITL-1844). On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a writable -SpiralDB database (``SpiralDBConnector(..., writable=True)``) and on Delta, and every +SpiralDB database (``SpiralDBKeyedConnector(..., writable=True)``) and on Delta, and every stored table is compared: same paths, same rows, apart from the columns a run fills with its own time or a random id. """ @@ -17,35 +17,41 @@ from pathlib import Path from typing import Any, Never, cast -from typing_extensions import override - import pyarrow as pa import pytest +from typing_extensions import override from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context from orcapod.core.function_pod import FallThroughPod, FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.sources.cached_source import CachedSource, SOURCE_RECORDED_AT_COL +from orcapod.core.sources.cached_source import SOURCE_RECORDED_AT_COL, CachedSource from orcapod.core.streams.base import typed_zero_row_table from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, - SpiralDBConnector, + SpiralDatabase, + SpiralDBKeyedConnector, SQLiteConnector, ) -from orcapod.contexts import get_default_context -from orcapod.databases import ( - spiral_database_identity, - spiraldb_connector, - spiraldb_writable_registry, - spiraldb_write_scope, -) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase -from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.databases.spiraldb_keyed import ( + connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed import ( + identity as spiral_database_identity, +) +from orcapod.databases.spiraldb_keyed import ( + writable_registry as spiraldb_writable_registry, +) +from orcapod.databases.spiraldb_keyed import ( + write_scope as spiraldb_write_scope, +) +from orcapod.databases.spiraldb_keyed.write_scope import database_writes from orcapod.databases.write_lock import NoWriteLock, WriteLock, WriteLockHandle from orcapod.errors import ( RowFailuresWarning, @@ -53,9 +59,10 @@ UnboundSourceError, UnstorableColumnError, ) -from orcapod.pipeline import AsyncPipelineOrchestrator -from orcapod.pipeline import node_run +from orcapod.pipeline import AsyncPipelineOrchestrator, node_run from orcapod.pipeline.execution_context import ExecutionContext +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import ( InvocationContext, @@ -64,8 +71,6 @@ sink_pod, ) from orcapod.sources import ArrowTableSource -from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.types import CacheMode, ColumnConfig, ContentHash, NodeConfig from tests.test_databases import fake_spiral_sdk as fake @@ -130,14 +135,14 @@ def _cached(cache: Any, table: pa.Table, *, order: str = "as given") -> CachedSo """The rows as a cached source, in one of the ``ORDERS`` arrangements: the columns as given or reversed, the tag argument in the other order, or the tags also data columns (data-tags).""" + tags = ["unit", "trial"] if order == "reversed": table = table.select(list(reversed(table.column_names))) + tags.reverse() return CachedSource( ArrowTableSource( table, - tag_columns=["trial", "unit"] - if order == "tags reversed" - else ["unit", "trial"], + tag_columns=tags[::-1] if order == "tags reversed" else tags, tag_only_columns=order != "data-tags", source_id="trials", record_id_columns=["unit", "trial"], @@ -188,7 +193,7 @@ def _database( ) -> ConnectorArrowDatabase: """Open a fresh writable database handle with an optional lock provider.""" return ConnectorArrowDatabase( - SpiralDBConnector("p", dataset, writable=True, write_lock=write_lock) + SpiralDBKeyedConnector("p", dataset, writable=True, write_lock=write_lock) ) @@ -204,6 +209,17 @@ def acquire(self, project_id: str, dataset: str) -> WriteLockHandle: return super().acquire(project_id, dataset) +@pytest.mark.usefixtures("root") +def test_spiral_database_forwards_write_lock_to_the_keyed_backend() -> None: + lock = _RecordingWriteLock() + database = SpiralDatabase("p", "d", write_lock=lock) + assert lock.acquisitions == [] + + _ = _run(_job(database), "sync") + + assert lock.acquisitions == [("p", "d")] + + def _database_tables(dataset: str = "d") -> list[str]: return sorted( t["name"] @@ -227,17 +243,18 @@ def _types(table: pa.Table) -> dict[str, pa.DataType]: return {f.name: f.type for f in table.schema if f.name not in VOLATILE} -def _same_tables(spiral_db: Any, delta: Any) -> None: +def _same_tables(left: Any, right: Any, *, same_column_order: bool = True) -> None: """Same paths, and in each the same rows, apart from the volatile columns.""" - paths = sorted(spiral_db.list_table_paths()) - assert paths == sorted(delta.list_table_paths()) + paths = sorted(left.list_table_paths()) + assert paths == sorted(right.list_table_paths()) for path in paths: - on_spiral = spiral_db.get_all_records(path) - on_delta = delta.get_all_records(path) - assert on_spiral is not None and on_delta is not None, path - assert on_spiral.schema.names == on_delta.schema.names, path - assert _types(on_spiral) == _types(on_delta), path - assert _comparable(on_spiral) == _comparable(on_delta), path + left_table = left.get_all_records(path) + right_table = right.get_all_records(path) + assert left_table is not None and right_table is not None, path + if same_column_order: + assert left_table.schema.names == right_table.schema.names, path + assert _types(left_table) == _types(right_table), path + assert _comparable(left_table) == _comparable(right_table), path def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: @@ -259,6 +276,48 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: # ------------------------------------------------------------ every table kind +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("writable", [True, False]) +def test_spiral_database_forwards_explicit_write_mode(writable: bool) -> None: + overrides = {"server.url": "https://example.invalid"} + default = SpiralDatabase("p", "d", overrides=overrides) + default_backend = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=True) + ) + assert default.to_config() == default_backend.to_config() + + overrides_first = SpiralDatabase("p", "d", overrides=overrides, writable=writable) + writable_first = SpiralDatabase("p", "d", writable=writable, overrides=overrides) + explicit = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=writable) + ) + assert ( + overrides_first.to_config() + == writable_first.to_config() + == explicit.to_config() + ) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +@pytest.mark.parametrize("order", ["as given", "reversed"]) +def test_spiral_database_stores_every_role_like_the_explicit_backend( + entry: str, order: str +) -> None: + database = SpiralDatabase("p", "factory") + explicit = _database("explicit") + for backend in (database, explicit): + calls.clear() + delivered.clear() + _ = _run(_job(backend, order=order), entry) + assert sorted(calls) == [(1, 5), (2, 6), (3, 7)] + assert sorted(delivered) == [6, 8, 10] + + assert sorted(path[-1] for path in database.list_table_paths()) == sorted(LAYOUTS) + _same_tables(database, explicit) + assert _database_tables("factory") == _database_tables("explicit") + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ["sync", "run_async"]) def test_overdeep_pipeline_path_is_refused_before_writes(entry: str) -> None: @@ -279,6 +338,19 @@ def test_sqlite_job_checks_the_pipeline_path_at_compile_time() -> None: combine.pod(_other_source(), label="combine") +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +def test_spiral_database_storage_is_stable_across_arrangements(entry: str) -> None: + original = SpiralDatabase("p", "original") + reordered = SpiralDatabase("p", "reordered") + _ = _run(_job(original, order="as given"), entry) + _ = _run(_job(reordered, order="reversed"), entry) + + assert sorted(path[-1] for path in original.list_table_paths()) == sorted(LAYOUTS) + assert _database_tables("original") == _database_tables("reordered") + _same_tables(original, reordered, same_column_order=False) + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ["sync", "run_async"]) @pytest.mark.parametrize("storage", ["source cache", "pipeline tag", "operator cache"]) @@ -556,6 +628,95 @@ def partial_results(x: int, y: int) -> tuple[int, float]: # ------------------------------------------------------------------ load only +@pytest.mark.parametrize("nested", [False, True], ids=["direct", "nested"]) +def test_load_refuses_the_retired_connector_type_in_a_cache( + root: Path, nested: bool +) -> None: + database = SpiralDatabase("p", "d") + job = _job(database) + if nested: + (source_node,) = ( + node for node in job.nodes.values() if isinstance(node, SourceJobNode) + ) + assert isinstance(source_node.bound_source, CachedSource) + job.bind( + sources={ + source_node.name: CachedSource( + source_node.bound_source, cache_database=database + ) + } + ) + saved = root / "job.json" + job.save(saved) + contents = json.loads(saved.read_text()) + (source,) = ( + source + for source in contents["bindings"]["sources"].values() + if source["source_type"] == "cached" + ) + cache_owner = source["inner_source"] if nested else source + cache_owner["cache_database"]["connector"]["connector_type"] = "spiraldb" + saved.write_text(json.dumps(contents)) + + with pytest.raises(ValueError, match=r"cache_database.*spiraldb_keyed"): + PipelineJob.load(saved, database=database) + + +def test_spiral_database_job_round_trip_records_the_concrete_backend( + root: Path, +) -> None: + overrides = {"server.url": "https://example.invalid"} + database = SpiralDatabase(project_id="p", dataset="d", overrides=overrides) + results = SpiralDatabase(overrides=overrides, dataset="r", project_id="p") + job = _job(database, result_database=results) + _ = job.run() + saved = root / "job.json" + job.save(saved) + bindings = json.loads(saved.read_text())["bindings"] + + explicit = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=True) + ) + explicit_results = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "r", overrides=overrides, writable=True) + ) + for slot, dataset, backend in ( + ("database", "d", explicit), + ("result_database", "r", explicit_results), + ): + assert bindings[slot] == backend.to_config() + assert bindings[slot]["type"] == "connector_arrow_database" + assert bindings[slot]["connector"] == { + "connector_type": "spiraldb_keyed", + "project_id": "p", + "dataset": dataset, + "overrides": overrides, + "writable": True, + } + (cache_slot,) = ( + name + for name, config in bindings["sources"].items() + if config["source_type"] == "cached" + ) + assert bindings["sources"][cache_slot]["cache_database"] == explicit.to_config() + + loaded = PipelineJob.load( + saved, database=explicit, result_database=explicit_results + ) + _ = loaded.run(load_only=True) + for label in ("combine", "select"): + original = job.nodes[label].as_source().as_table() + restored = loaded.nodes[label].as_source().as_table() + assert restored.num_rows == 3 + assert _comparable(restored) == _comparable(original) + saved_again = root / "loaded.json" + loaded.save(saved_again) + recorded = json.loads(saved_again.read_text())["bindings"] + for slot in ("database", "result_database"): + assert recorded[slot] == bindings[slot] + assert recorded["sources"][cache_slot]["cache_database"] == explicit.to_config() + + @pytest.mark.usefixtures("root") def test_a_loaded_job_reads_and_runs_load_only(root: Path) -> None: spiral_db = _database() @@ -564,6 +725,8 @@ def test_a_loaded_job_reads_and_runs_load_only(root: Path) -> None: saved = root / "job.json" job.save(saved) text = saved.read_text() + connector = json.loads(text)["bindings"]["database"]["connector"] + assert connector["connector_type"] == "spiraldb_keyed" assert '"writable": true' in text assert not any(word in text.lower() for word in ("secret", "token", "private")) loaded = PipelineJob.load(saved, database=_database()) @@ -606,10 +769,12 @@ def test_load_refuses_a_spiraldb_connector_of_the_other_kind( _job(delta).save(saved) data = json.loads(saved.read_text()) data["bindings"]["database"] = ConnectorArrowDatabase( - SpiralDBConnector("p", "d") + SpiralDBKeyedConnector("p", "d") ).to_config() saved.write_text(json.dumps(data)) - given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + given = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", writable=given_writable) + ) with pytest.raises(ValueError, match="bindings.database.*writable"): _ = PipelineJob.load(saved, database=given) @@ -633,7 +798,7 @@ def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( None if given_writable is None else ConnectorArrowDatabase( - SpiralDBConnector("p", "d", writable=given_writable) + SpiralDBKeyedConnector("p", "d", writable=given_writable) ) ) with pytest.raises(ValueError, match=r"'store' key.*writable=True"): @@ -661,7 +826,7 @@ def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( None if given_writable is None else ConnectorArrowDatabase( - SpiralDBConnector("p", "d", writable=given_writable) + SpiralDBKeyedConnector("p", "d", writable=given_writable) ) ) with pytest.raises( @@ -674,29 +839,29 @@ def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( @pytest.mark.usefixtures("root") def test_a_spiraldb_connector_config_with_a_store_key_is_refused() -> None: - config = SpiralDBConnector("p", "d", writable=True).to_config() + config = SpiralDBKeyedConnector("p", "d", writable=True).to_config() del config["writable"] config["store"] = True with pytest.raises(ValueError, match=r"'store' key.*writable=True"): - _ = SpiralDBConnector.from_config(config) + _ = SpiralDBKeyedConnector.from_config(config) @pytest.mark.usefixtures("root") def test_the_writable_flag_is_saved_without_credentials() -> None: - assert SpiralDBConnector("p", "d", writable=True).to_config() == { - "connector_type": "spiraldb", + assert SpiralDBKeyedConnector("p", "d", writable=True).to_config() == { + "connector_type": "spiraldb_keyed", "project_id": "p", "dataset": "d", "overrides": None, "writable": True, } - assert "writable" not in SpiralDBConnector("p", "d").to_config() - rebuilt = SpiralDBConnector.from_config( - SpiralDBConnector("p", "d", writable=True).to_config() + assert "writable" not in SpiralDBKeyedConnector("p", "d").to_config() + rebuilt = SpiralDBKeyedConnector.from_config( + SpiralDBKeyedConnector("p", "d", writable=True).to_config() ) assert rebuilt._writable_tables() is not None # pyright: ignore[reportPrivateUsage] with pytest.raises(TypeError, match="writable must be True or False"): - _ = SpiralDBConnector("p", "d", writable="yes") # pyright: ignore[reportArgumentType] + _ = SpiralDBKeyedConnector("p", "d", writable="yes") # pyright: ignore[reportArgumentType] # ------------------------------------------------------------------ the scope @@ -905,11 +1070,13 @@ def test_load_refuses_a_wrapped_spiraldb_connector_of_the_other_kind( _job(DeltaTableDatabase(root / "delta")).save(saved) data = json.loads(saved.read_text()) data["bindings"]["database"] = ConnectorArrowDatabase( - SpiralDBConnector("p", "d") + SpiralDBKeyedConnector("p", "d") ).to_config() saved.write_text(json.dumps(data)) given = _wrapped( - ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", writable=given_writable) + ) ) with pytest.raises(ValueError, match="bindings.database.*writable"): _ = PipelineJob.load(saved, database=given) @@ -945,7 +1112,7 @@ def test_the_scope_key_keeps_the_service_address_of_construction() -> None: """Changing the caller's overrides after construction moves neither the client, the scope nor the saved configuration to another service.""" overrides = {"server.url": "https://one.example"} - connector = SpiralDBConnector("p", "d", writable=True, overrides=overrides) + connector = SpiralDBKeyedConnector("p", "d", writable=True, overrides=overrides) key = connector._write_scope_key() # pyright: ignore[reportPrivateUsage] overrides["server.url"] = "https://two.example" assert connector._write_scope_key() == key # pyright: ignore[reportPrivateUsage] @@ -954,7 +1121,7 @@ def test_the_scope_key_keeps_the_service_address_of_construction() -> None: assert saved["overrides"] == {"server.url": "https://one.example"} saved["overrides"]["server.url"] = "https://three.example" assert connector.to_config()["overrides"] == {"server.url": "https://one.example"} - loaded = SpiralDBConnector.from_config(connector.to_config()) + loaded = SpiralDBKeyedConnector.from_config(connector.to_config()) assert loaded._write_scope_key() == key # pyright: ignore[reportPrivateUsage] @@ -966,9 +1133,9 @@ def test_connectors_reaching_one_service_share_one_scope(given: str) -> None: """A writable connector with no address and one given the default address (also with a final slash) reach one service and share scope state. A connector to another service has a different identity and cannot open a competing scope for the pair.""" - plain = SpiralDBConnector("p", "d", writable=True) - addressed = SpiralDBConnector("p", "d", {"server.url": given}, writable=True) - other = SpiralDBConnector( + plain = SpiralDBKeyedConnector("p", "d", writable=True) + addressed = SpiralDBKeyedConnector("p", "d", {"server.url": given}, writable=True) + other = SpiralDBKeyedConnector( "p", "d", {"server.url": "https://other.invalid"}, writable=True ) databases = [ConnectorArrowDatabase(c) for c in (plain, addressed, other)] @@ -1026,7 +1193,7 @@ def test_a_client_without_its_resolved_address_is_refused( takes the scope: no address is guessed, and no scope is taken.""" from types import SimpleNamespace - connector = SpiralDBConnector("p", "d", writable=True) + connector = SpiralDBKeyedConnector("p", "d", writable=True) client = connector._client # pyright: ignore[reportPrivateUsage] stand_in = ( SimpleNamespace() @@ -1048,7 +1215,7 @@ def test_a_write_through_another_connector_during_a_run_is_refused() -> None: @function_pod(output_keys="z") def write_elsewhere(x: int) -> int: - other = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=True)) + other = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "d", writable=True)) row = pa.table( { "__data_context": pa.array(["std:v1:default"], pa.large_string()), @@ -1176,7 +1343,7 @@ def test_a_job_on_a_shared_writable_connector_takes_the_scope_after_its_original monkeypatch.setattr( spiraldb_writable_registry, "_writable_connectors", weakref.WeakSet() ) - original = SpiralDBConnector("p", "d", writable=True) + original = SpiralDBKeyedConnector("p", "d", writable=True) shared = original.share_client() original.close() del original @@ -1195,9 +1362,9 @@ def test_a_job_on_a_writable_connector_and_its_shared_copy_runs( ) -> None: """A connector and its ``share_client`` copy bound in one run: the run takes ONE scope of the dataset and attaches it to the database tables of both.""" - from orcapod.databases.spiraldb_tables import SpiralDBTables + from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables - connector = SpiralDBConnector("p", "d", writable=True) + connector = SpiralDBKeyedConnector("p", "d", writable=True) spiral_db = ConnectorArrowDatabase(connector) shared = connector.share_client() results = ConnectorArrowDatabase(shared) @@ -1223,8 +1390,8 @@ def test_a_decorator_result_database_on_a_database_is_scoped(root: Path) -> None """A function pod's own result database (``@function_pod(result_database=...)``) on a writable SpiralDB database is written under the run's scope on a cache miss, and a pod cache database (``pod_cache_database``) too.""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) - pod_cache = ConnectorArrowDatabase(SpiralDBConnector("p", "g", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) + pod_cache = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "g", writable=True)) @function_pod( output_keys=("total",), @@ -1248,7 +1415,7 @@ def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: """A ``share_client`` copy is another connector: while a run holds the scope through the original, a write through the copy (not part of the run) is refused and nothing is written.""" - connector = SpiralDBConnector("p", "d", writable=True) + connector = SpiralDBKeyedConnector("p", "d", writable=True) outside = ConnectorArrowDatabase(connector.share_client()) row = pa.table( { @@ -1272,7 +1439,7 @@ def test_a_bound_function_pod_stream_built_outside_the_job_is_scoped( """A function pod stream built outside the job (it becomes a bound slot) whose pod caches on a writable SpiralDB database (``result_database``, or a ``CachedFunctionPod`` through ``pod_cache_database``) writes under the run's scope.""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: return x + y @@ -1310,7 +1477,7 @@ def test_a_load_only_run_over_an_outside_function_pod_stream_is_refused_not_busy """A load-only run reads no function pod stream built outside the job, so it takes no scope of that pod's database: on a busy dataset it gives the refusal that says how to run the input, never ``SpiralDBScopeOpenError`` (review of de39bbc4c).""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: return x + y @@ -1377,8 +1544,8 @@ def test_a_load_only_run_reading_an_outside_pod_through_a_live_wrapper_is_refuse (through a source's ``live_source_inputs``) is refused, as for a direct input, before any scope is taken, any source checked or anything written (delta review of 047dbe290: it reached an unscoped write of the pod's results).""" - on_pod = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) - cache = ConnectorArrowDatabase(SpiralDBConnector("p", "c", writable=True)) + on_pod = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) + cache = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "c", writable=True)) computed: list[int] = [] @@ -1441,7 +1608,7 @@ def test_an_interrupted_hold_is_let_go_of(monkeypatch: pytest.MonkeyPatch) -> No """An interruption once a scope is attached to a database's tables (before the scope has recorded them) still lets go of it: the next run on the same databases is not refused.""" - from orcapod.databases.spiraldb_tables import SpiralDBTables + from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables real = SpiralDBTables.attach_run interrupted: list[None] = [] @@ -1515,7 +1682,7 @@ def test_a_held_table_does_not_scope_its_upstream_pods_database() -> None: """A run over a table that holds its rows reads no pod behind it (ITL-1121), so it takes no scope of that pod's database: it runs while another writer holds it, and the pod is not called.""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) called: list[int] = [] def add(x: int, y: int) -> int: @@ -1545,7 +1712,7 @@ def add(x: int, y: int) -> int: def test_a_cached_source_behind_a_held_table_is_still_scoped() -> None: """A run checks every source it finds, also behind a held table, and a check can write a cached source's cache: its database stays among the run's scoped databases.""" - connector = SpiralDBConnector("p", "g", writable=True) + connector = SpiralDBKeyedConnector("p", "g", writable=True) cache = ConnectorArrowDatabase(connector) node = _twice_over(_held_table_over(_cached(cache.at("c"), _rows()))) databases = node_run.write_scope_databases([node], load_only=False) diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 942734ada..7786c6d41 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -24,13 +24,19 @@ from orcapod.core.operators import SelectDataColumns from orcapod.databases import ( ConnectorArrowDatabase, - SpiralDBConnector, - spiral_database_identity, - spiraldb_connector, - spiraldb_write_scope, + SpiralDBKeyedConnector, ) -from orcapod.databases.spiraldb_tables import SpiralDBTables -from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.databases.spiraldb_keyed import ( + connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed import ( + identity as spiral_database_identity, +) +from orcapod.databases.spiraldb_keyed import ( + write_scope as spiraldb_write_scope, +) +from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables +from orcapod.databases.spiraldb_keyed.write_scope import database_writes from orcapod.errors import OrcapodDatabaseWriteError, SpiralDBScopeOpenError from orcapod.invocation import InvocationContext from orcapod.protocols.core_protocols import ( @@ -100,7 +106,7 @@ def _database( dataset: str = "d", lock: RecordingLock | None = None ) -> ConnectorArrowDatabase: return ConnectorArrowDatabase( - SpiralDBConnector("p", dataset, writable=True, write_lock=lock) + SpiralDBKeyedConnector("p", dataset, writable=True, write_lock=lock) ) @@ -248,7 +254,7 @@ def test_kept_reads_stay_within_their_byte_budget( """Finding M2: a run keeps whole reads within ``KEPT_ROWS_BUDGET_BYTES``: the oldest is dropped to make room, a read that does not fit is not kept, and a dropped table is read again with the same rows.""" - from orcapod.databases import spiraldb_tables + from orcapod.databases.spiraldb_keyed import tables as spiraldb_tables database = _database() with database_writes([database]): diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index e8f08384d..bac786e00 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -49,7 +49,9 @@ PostgreSQLConnector, SQLiteConnector, ) -from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] +from orcapod.databases.delta_arrow_types import ( + _is_recorded, # pyright: ignore[reportPrivateUsage] +) from orcapod.databases.utils import identity_node from orcapod.utils.arrow_utils import normalize_to_large_types @@ -1108,8 +1110,8 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB and writes it only as a writable SpiralDB database ([SpiralDB as a Job's -Database](../concepts/spiraldb-database.md)), not compared here. See [The +SpiralDB and writes it only as a writable SpiralDB database ([Keyed SpiralDB as a Job's +Database](../concepts/spiraldb-keyed-database.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/tests/test_dev_scripts/test_itl_1903_rename.py b/tests/test_dev_scripts/test_itl_1903_rename.py new file mode 100644 index 000000000..24677c382 --- /dev/null +++ b/tests/test_dev_scripts/test_itl_1903_rename.py @@ -0,0 +1,69 @@ +"""Check the keyed SpiralDB rename in release documentation.""" + +from __future__ import annotations + +import runpy +from collections.abc import Callable +from importlib.util import find_spec +from pathlib import Path +from typing import cast + +ROOT = Path(__file__).resolve().parents[2] + + +def test_rename_updates_release_guide_references() -> None: + script = runpy.run_path(str(ROOT / "docs/dev/scripts/itl_1903/rename.py")) + replace_text = cast("Callable[[str], str]", script["replace_text"]) + extra_text = cast("set[Path]", script["EXTRA_TEXT"]) + previous = ( + "`tests/test_databases/test_spiraldb_connector_" + "integration.py`\n" + "`spiraldb_connector" + "._ignore_keyed_table_deprecation`" + ) + expected = ( + "`tests/test_databases/test_spiraldb_keyed_connector_integration.py`\n" + "`spiraldb_keyed.connector._ignore_keyed_table_deprecation`" + ) + + assert replace_text(previous) == expected + assert replace_text(expected) == expected + assert Path("RELEASING.md") in extra_text + guide = (ROOT / "RELEASING.md").read_text(encoding="utf-8") + assert all(reference in guide for reference in expected.splitlines()) + + +def test_rename_updates_dotted_test_module_references() -> None: + script = runpy.run_path(str(ROOT / "docs/dev/scripts/itl_1903/rename.py")) + replace_text = cast("Callable[[str], str]", script["replace_text"]) + old_module = "test_spiraldb_connector_integration" + previous = f"import tests.test_databases.{old_module}" + expected = "import tests.test_databases.test_spiraldb_keyed_connector_integration" + + assert replace_text(previous) == expected + assert replace_text(expected) == expected + + +def test_rename_preserves_the_migration_fallback_and_guide_redirect() -> None: + """Rerunning the rename keeps the old import and the old route where needed.""" + script = runpy.run_path(str(ROOT / "docs/dev/scripts/itl_1903/rename.py")) + replace_file_text = cast("Callable[[Path, str], str]", script["replace_file_text"]) + for name in ( + "scripts/migrate_spiral_schemas.py", + "tests/test_databases/test_migrate_spiral_schemas.py", + "site/astro.config.mjs", + "tests/test_docs/test_site_content.py", + ): + path = Path(name) + original = (ROOT / path).read_text(encoding="utf-8") + assert replace_file_text(path, original) == original + + +def test_developer_import_recipe_uses_an_existing_module() -> None: + plan = ROOT / "docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md" + step = plan.read_text(encoding="utf-8").split( + "Verify the file still imports cleanly", 1 + )[1] + module = step.split('uv run python -c "import ', 1)[1].split('"', 1)[0] + + assert find_spec(module) is not None diff --git a/tests/test_docs/test_api_reference.py b/tests/test_docs/test_api_reference.py index fbb340f9f..7fac05af0 100644 --- a/tests/test_docs/test_api_reference.py +++ b/tests/test_docs/test_api_reference.py @@ -5,12 +5,16 @@ import re from collections.abc import Sequence from importlib import import_module +from inspect import getdoc from pathlib import Path from typing import cast import griffe +import pytest from griffe import Alias, Module, Object +from orcapod.databases import SpiralDatabase + REPO_ROOT = Path(__file__).resolve().parents[2] PUBLIC_MODULES = ( "orcapod", @@ -140,3 +144,23 @@ def reference_key(path: str) -> tuple[str, str]: assert not missing, ( "Add API reference entries or reasoned exclusions for:\n" + "\n".join(missing) ) + + +@pytest.mark.parametrize( + "module_name", + [ + "orcapod.databases.spiraldb_keyed.connector", + "orcapod.databases.connector_arrow_database", + ], +) +def test_database_module_examples_use_google_style(module_name: str) -> None: + docstring = getdoc(import_module(module_name)) + assert docstring is not None + assert "Examples:" in docstring.splitlines() + assert "Example::" not in docstring + + +def test_spiral_database_documents_connector_options() -> None: + docstring = getdoc(SpiralDatabase) + assert docstring is not None + assert " **connector_options:" in docstring diff --git a/tests/test_docs/test_doc_samples.py b/tests/test_docs/test_doc_samples.py index f2c55199f..2c92cd97a 100644 --- a/tests/test_docs/test_doc_samples.py +++ b/tests/test_docs/test_doc_samples.py @@ -280,7 +280,7 @@ def test_doc_pages_are_discovered(): def test_spiraldb_limits_describe_when_key_scans_are_needed(): """The key index and full-row reads have different scan costs.""" - page = (REPO_ROOT / "docs/concepts/spiraldb-database.md").read_text( + page = (REPO_ROOT / "docs/concepts/spiraldb-keyed-database.md").read_text( encoding="utf-8" ) limits = " ".join(page.split("## Limits\n", 1)[1].split("\n## ", 1)[0].split()) diff --git a/tests/test_docs/test_site_content.py b/tests/test_docs/test_site_content.py index 9219f9fee..89105b619 100644 --- a/tests/test_docs/test_site_content.py +++ b/tests/test_docs/test_site_content.py @@ -589,6 +589,16 @@ def test_an_invalid_address_is_refused(env: dict[str, str]): assert variable in proc.stderr +def test_the_site_redirects_the_old_spiraldb_guide(): + """External links to the previous guide route follow the renamed guide.""" + config = (REPO_ROOT / "site" / "astro.config.mjs").read_text(encoding="utf-8") + assert ( + "redirects: {\n" + "\t\t'/concepts/spiraldb-database': `${base}concepts/spiraldb-keyed-database/`,\n" + "\t}," in config + ) + + def test_the_site_shows_code_comments_as_written(): """A printed value that looks like a file name (`# 1.58`) stays in its code block. 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 4cdae3771..633947fd4 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -26,14 +26,14 @@ ConnectorArrowDatabase, DeltaTableDatabase, PostgreSQLConnector, - SpiralDBConnector, + SpiralDBKeyedConnector, 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") +KINDS = ("sqlite", "postgresql", "spiraldb_keyed") MARKER = "marker-in-dsn" @@ -52,7 +52,7 @@ def make(self, kind: str, name: str) -> ConnectorArrowDatabase: return ConnectorArrowDatabase( PostgreSQLConnector(f"postgresql://u:{MARKER}@h/{name}") ) - return ConnectorArrowDatabase(SpiralDBConnector(name)) + return ConnectorArrowDatabase(SpiralDBKeyedConnector(name)) @pytest.fixture @@ -151,6 +151,28 @@ def test_load_without_the_database_names_the_slot_and_what_to_pass( assert MARKER not in message +@pytest.mark.parametrize("slot", ["database", "result_database"]) +@pytest.mark.parametrize("supply_connector", [False, True]) +def test_load_refuses_the_retired_connector_type( + databases: Databases, tmp_path: Path, slot: str, supply_connector: bool +) -> None: + path = tmp_path / "job.json" + _save(path, database=databases.make("sqlite", "a")) + supplied = databases.make("spiraldb_keyed", "b") + data = json.loads(path.read_text()) + config = supplied.to_config() + retired_kind = "spiraldb" + config["connector"]["connector_type"] = retired_kind + data["bindings"][slot] = config + path.write_text(json.dumps(data)) + + given = {slot: supplied} if supply_connector else {} + with pytest.raises( + ValueError, match=rf"bindings\.{slot}: .*'spiraldb'.*'spiraldb_keyed'" + ): + PipelineJob.load(path, **given) + + def test_legacy_connector_dsn_is_ignored_when_the_database_is_supplied( databases: Databases, tmp_path: Path ) -> None: diff --git a/tests/test_pipeline/test_observer_databases.py b/tests/test_pipeline/test_observer_databases.py index 508189494..b81fd2688 100644 --- a/tests/test_pipeline/test_observer_databases.py +++ b/tests/test_pipeline/test_observer_databases.py @@ -17,7 +17,8 @@ ExtensionAwareDatabase, InMemoryArrowDatabase, NoOpArrowDatabase, - SpiralDBConnector, + SpiralDatabase, + SpiralDBKeyedConnector, SQLiteConnector, ) from orcapod.errors import SpiralDBObserverNotSupportedError @@ -40,7 +41,7 @@ class _DerivedExtensionWrapper(ExtensionAwareDatabase): """An extension wrapper subclass must be unwrapped too.""" -class _DerivedSpiralConnector(SpiralDBConnector): +class _DerivedSpiralConnector(SpiralDBKeyedConnector): """A SpiralDB connector subclass still uses the same database.""" @@ -83,11 +84,11 @@ def __getattribute__(self, name: str) -> object: @pytest.fixture -def spiral_connector(tmp_path: Path) -> Iterator[SpiralDBConnector]: +def spiral_connector(tmp_path: Path) -> Iterator[SpiralDBKeyedConnector]: """Open a real connector backed by the fake SpiralDB SDK.""" with ( fake_spiral_sdk.install(tmp_path / "spiral"), - SpiralDBConnector("p") as connector, + SpiralDBKeyedConnector("p") as connector, ): yield connector @@ -101,7 +102,7 @@ def capture_install() -> Iterator[Mock]: @pytest.fixture(params=["wrapper-slot", "connector-slot"]) def slotted_spiral_database( - request: pytest.FixtureRequest, spiral_connector: SpiralDBConnector + request: pytest.FixtureRequest, spiral_connector: SpiralDBKeyedConnector ) -> ArrowDatabaseProtocol: """Build a SpiralDB database with one of the inspected references in a slot.""" if cast(str, request.param) == "wrapper-slot": @@ -151,7 +152,7 @@ def database_view( @pytest.mark.parametrize("observer_class", _OBSERVERS) def test_spiral_database_is_refused_at_setup( observer_class: type[StatusObserver] | type[LoggingObserver], - spiral_connector: SpiralDBConnector, + spiral_connector: SpiralDBKeyedConnector, database_view: Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol], capture_install: Mock, ) -> None: @@ -287,7 +288,7 @@ def test_wrapper_without_stored_database_is_accepted( def test_composite_refusal_does_not_install_capture( logging_first: bool, nested: bool, - spiral_connector: SpiralDBConnector, + spiral_connector: SpiralDBKeyedConnector, monkeypatch: pytest.MonkeyPatch, capture_install: Mock, ) -> None: @@ -325,7 +326,7 @@ def resolve( @pytest.mark.parametrize("observer_class", _OBSERVERS) def test_spiral_database_resolved_from_config_is_refused( observer_class: type[StatusObserver] | type[LoggingObserver], - spiral_connector: SpiralDBConnector, + spiral_connector: SpiralDBKeyedConnector, monkeypatch: pytest.MonkeyPatch, capture_install: Mock, ) -> None: @@ -367,7 +368,21 @@ def test_other_databases_are_accepted( assert capture_install.call_count == int(observer_class is LoggingObserver) -def test_every_database_class_exported_from_orcapod_databases_is_classified() -> None: +@pytest.mark.parametrize("observer_class", _OBSERVERS) +def test_spiral_database_factory_is_refused_at_observer_setup( + observer_class: type[StatusObserver] | type[LoggingObserver], + tmp_path: Path, + capture_install: Mock, +) -> None: + with fake_spiral_sdk.install(tmp_path / "spiral"): + database = SpiralDatabase("p", "d") + with pytest.raises(SpiralDBObserverNotSupportedError, match=_REFUSAL): + _ = observer_class(database) + + capture_install.assert_not_called() + + +def test_every_database_export_from_orcapod_databases_is_classified() -> None: """Require an explicit classification for names exported through ``__all__``.""" assert set(databases.__all__) == { # Roots kept as-is by the observer check. @@ -377,8 +392,10 @@ def test_every_database_class_exported_from_orcapod_databases_is_classified() -> # The wrapper is unwrapped, then the connector decides the result. "ExtensionAwareDatabase", "ConnectorArrowDatabase", + # The factory returns a keyed connector database, refused at setup. + "SpiralDatabase", # Connectors: SpiralDB is refused; SQLite and PostgreSQL pass. - "SpiralDBConnector", + "SpiralDBKeyedConnector", "SQLiteConnector", "PostgreSQLConnector", }