From cf33c2071776736b5a63742a4a74020b23144b4b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 15:54:18 -0800 Subject: [PATCH 1/7] feat(spiraldb)!: read SpiralDB through spiral-sdk (ITL-1186) (#550) * docs(spiraldb): design the switch to spiral-sdk (ITL-1186) Co-Authored-By: Claude Opus 5.5 * docs(spiraldb): state the evidence exactly (ITL-1186) Co-Authored-By: Claude Opus 5.5 * feat(spiraldb)!: read SpiralDB through spiral-sdk (ITL-1186) Reading only: table source, connector reads, listing, pins, where and counts. Tests are being ported. Writes are refused. Co-Authored-By: Claude Opus 5.5 * feat(spiraldb): migration tool, sign-in check, review fixes (ITL-1186) Co-Authored-By: Claude Opus 5.5 * feat(spiraldb): freeze the schema table's form, version 1 (ITL-1186) Co-Authored-By: Claude Opus 5.5 * fix(spiraldb): name a changed table in the migration tool; test its steps (ITL-1186) Co-Authored-By: Claude Opus 5.5 * fix(spiraldb): withdraw the migration marker on any failure after it; SpiralDB out of the write matrices (ITL-1186) Co-Authored-By: Claude Opus 5.5 * test(spiraldb): reading, refusals and the review findings (ITL-1186) Co-Authored-By: Claude Opus 5.5 * docs(spiraldb): spiral-sdk, the schema table and the migration; conformance on fake and service (ITL-1186) Co-Authored-By: Claude Opus 5.5 * fix(scripts): import spiral dynamically in the migration tool (ITL-1186) Co-Authored-By: Claude Opus 5.5 * docs(spiraldb): say which reads refuse an incomplete record (ITL-1186) Co-Authored-By: Claude Opus 5.5 * fix(spiraldb): refuse a source in a forked child before its inherited lock (ITL-1186) Co-Authored-By: Claude Opus 5.5 * fix(spiraldb): CodeRabbit's review of the reading path (ITL-1186) Co-Authored-By: Claude Opus 5.5 * fix(spiraldb): never adopt another program's schema table; hold the warning's lock (ITL-1186) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- README.md | 2 +- RELEASING.md | 60 +- changelog.d/ITL-1186.md | 24 + docs/concepts/data-tags.md | 2 +- docs/concepts/pipeline-job.md | 14 +- docs/concepts/sources.md | 188 +-- .../itl_1371_logical_identity_appends.py | 2 +- docs/dev/specs/itl-1186-switch.md | 167 ++ docs/dev/specs/itl-926-live/inspect_tables.py | 2 +- docs/dev/specs/itl-926-live/live_verify.py | 2 +- .../dev/specs/itl-926-live/scan_cost_probe.py | 2 +- docs/dev/specs/itl-926-live/size_probe.py | 2 +- .../specs/itl-936-live/live_nullability.py | 10 +- docs/reference/database-types.md | 242 ++- docs/reference/hashing.md | 2 +- pyproject.toml | 4 +- scripts/migrate_spiral_schemas.py | 654 ++++++++ .../core/sources/spiraldb_table_source.py | 128 +- src/orcapod/databases/__init__.py | 3 - src/orcapod/databases/spiraldb_connector.py | 1439 +++++++---------- src/orcapod/databases/spiraldb_nullability.py | 340 +--- .../databases/spiraldb_schema_table.py | 475 ++++++ src/orcapod/databases/spiraldb_sign_in.py | 63 + src/orcapod/errors.py | 54 +- tests/test_core/alignment/test_spiraldb.py | 8 +- .../data_tags/test_database_capability.py | 245 +-- .../operators/test_filter_pipeline.py | 17 +- .../test_large_normalization_sources.py | 6 +- .../sources/test_source_check_for_new_data.py | 24 +- .../sources/test_spiraldb_lookups.py | 157 +- .../sources/test_spiraldb_table_source.py | 8 +- .../test_spiraldb_table_source_fake.py | 62 +- .../test_spiraldb_table_source_live.py | 95 +- .../test_spiraldb_table_source_streaming.py | 68 +- ...test_spiraldb_table_source_tags_as_data.py | 20 +- .../test_spiraldb_table_source_where.py | 79 +- .../sources/test_tag_only_columns.py | 6 +- tests/test_core/streams/test_explain.py | 14 +- tests/test_core/test_order_invariance.py | 6 +- tests/test_databases/fake_pyspiral.py | 877 ---------- tests/test_databases/fake_spiral_sdk.py | 1034 ++++++++++++ tests/test_databases/spiraldb_schema_v1.b64 | 11 + tests/test_databases/test_append_by_name.py | 34 +- .../test_appended_field_attributes.py | 9 +- .../test_logical_identity_appends.py | 83 +- .../test_migrate_spiral_schemas.py | 457 ++++++ .../test_databases/test_spiraldb_connector.py | 807 --------- .../test_spiraldb_connector_fake.py | 702 -------- .../test_spiraldb_connector_integration.py | 790 ++++----- .../test_spiraldb_metadata_helpers.py | 381 ----- .../test_spiraldb_nullability.py | 208 --- tests/test_databases/test_spiraldb_reading.py | 850 ++++++++++ .../test_spiraldb_schema_table.py | 339 ++++ tests/test_databases/test_spiraldb_sign_in.py | 154 ++ .../test_databases/test_unstorable_columns.py | 199 +-- tests/test_databases/type_matrix.py | 33 +- .../test_run_warnings_caller_globals.py | 6 +- uv.lock | 446 +---- 58 files changed, 5833 insertions(+), 6283 deletions(-) create mode 100644 changelog.d/ITL-1186.md create mode 100644 docs/dev/specs/itl-1186-switch.md create mode 100644 scripts/migrate_spiral_schemas.py create mode 100644 src/orcapod/databases/spiraldb_schema_table.py create mode 100644 src/orcapod/databases/spiraldb_sign_in.py delete mode 100644 tests/test_databases/fake_pyspiral.py create mode 100644 tests/test_databases/fake_spiral_sdk.py create mode 100644 tests/test_databases/spiraldb_schema_v1.b64 create mode 100644 tests/test_databases/test_migrate_spiral_schemas.py delete mode 100644 tests/test_databases/test_spiraldb_connector.py delete mode 100644 tests/test_databases/test_spiraldb_connector_fake.py delete mode 100644 tests/test_databases/test_spiraldb_metadata_helpers.py delete mode 100644 tests/test_databases/test_spiraldb_nullability.py create mode 100644 tests/test_databases/test_spiraldb_reading.py create mode 100644 tests/test_databases/test_spiraldb_schema_table.py create mode 100644 tests/test_databases/test_spiraldb_sign_in.py diff --git a/README.md b/README.md index 9beb91fca..b810cfef3 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ Optional features are installed as extras, for example `uv add "orcapod[spiraldb | `orcapod[ray]` | Distributed execution with `RayExecutor` (Ray 2.60 or later, which has no wheel for Intel macOS) | | `orcapod[redis]` | `RedisCacher`, a Redis-backed hash cache | | `orcapod[postgresql]` | The PostgreSQL connector, table source and file hash cache (psycopg 3.1.17 or later) | -| `orcapod[spiraldb]` | The SpiralDB connector and table source | +| `orcapod[spiraldb]` | The SpiralDB connector and table source, read only (spiral-sdk) | | `orcapod[torch]` | PyTorch, for `torch.Tensor` values (any installed `torch` works) | | `orcapod[all]` | All of the above | diff --git a/RELEASING.md b/RELEASING.md index 5bdb631d4..72aa1fd26 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -299,24 +299,23 @@ repository of the organization. The `spiral-integration` job of `Run Tests` runs on every push to `main` and by hand (`workflow_dispatch`) on `metamorphic-labs/orcapod-python`, never on pull requests. It runs -beside the test jobs, not after them, so its result comes in minutes. It authenticates to SpiralDB with a workload private key (ITL-1185): pyspiral reads +beside the test jobs, not after them, so its result comes in minutes. It authenticates to SpiralDB with a workload private key (ITL-1185): spiral-sdk reads `SPIRAL_CLIENT_ID` (the workload id) and `SPIRAL_PRIVATE_KEY` (the private key as a JSON Web -Key) from the environment, signs a client assertion with the key, and requests a token from -`https://auth.spiraldb.com/oauth/token` with the `client_credentials` grant. It requests no -GitHub OIDC token: pyspiral's workload identity path posts a token exchange that the server -rejects. Client secrets are not used: the server no longer issues them. The job fails at its +Key) from the environment. It requests no GitHub OIDC token. The job fails at its first step, naming each missing setting, when one of the three below is not set or the key is not a private JWK naming its `kid`. No agent creates, reads or sets any of them. +The tests read through Orcapod and write their fixed tables through spiral-sdk, in the dataset +`orcapod_conformance` of the test project. spiral-sdk cannot drop a keyed table, so they stay; +each run writes the same rows. + On `metamorphic-labs/orcapod-python` and in SpiralDB, the developer sets: 1. The SpiralDB workload the job runs as (today `orcapod-gha`) holds the **editor** role on - the test project ("Orcapod testing"): the tests create, write, read and drop tables there. -2. A key pair registered for that workload. pyspiral's own CLI has no command for this; use - Studio or the newer SpiralDB CLI, in an environment of its own and never installed beside - pyspiral (both provide a top-level `spiral` module): - `spiral workloads keys add --kid --output -` prints the private key - as a JWK that names its `kid`. A PEM key is not accepted. + the test project ("Orcapod testing"): the tests create, write and read tables there. +2. A key pair registered for that workload, made in Studio or with + `spiral workloads keys add --kid --output -`, which prints the private + key as a JWK that names its `kid`. A PEM key is not accepted. 3. Repository secrets (`Settings → Secrets and variables → Actions → Secrets`): `SPIRAL_CLIENT_ID`, the workload id (`work_...`), and `SPIRAL_PRIVATE_KEY`, the private JWK as one line of JSON. Keep the key file out of the repository and delete it once the secret @@ -335,6 +334,45 @@ If the key may have been exposed (for example printed in a log), remove it from first (`spiral workloads keys rm`), so it stops signing in at once, then add a new key and replace the secret as above. The job fails in between; that is the price of containment. +### Moving the spiral-sdk pin + +`pyproject.toml` pins one version of `spiral-sdk` (the `spiraldb` extra): a pre-alpha that +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 +value that changed is a change of `tests/test_databases/fake_spiral_sdk.py` (its `RULES`) first. + +### Migrating a SpiralDB dataset from pyspiral + +Once per dataset that an Orcapod release on pyspiral wrote, by a person who may write there. +Nothing else may write to the dataset meanwhile. The two clients cannot share an environment, so +each step has its own; `` is the last commit on pyspiral +(`7a2248bfb3867a3ccb6dd55e21cb0e2a90769a9f`), `` the commit or release being used. + +```bash +uv run --no-project --isolated --python 3.12 \ + --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ + --with pyspiral==0.16.33 scripts/migrate_spiral_schemas.py \ + dry-run --project --dataset --plan plan.json + +uv run --no-project --isolated --python 3.12 \ + --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ + --with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \ + write --project --dataset --plan plan.json --digest + +uv run --no-project --isolated --python 3.12 \ + --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ + --with spiral-sdk==0.16.74 scripts/migrate_spiral_schemas.py \ + verify --project --dataset --plan plan.json +``` + +`--dataset` can be repeated. `write` refuses unless the plan and every table are as the dry run +found them; an interrupted `write` is refused by every read of the dataset and is finished by +running it again (one stopped while it created the schema table asks for `--adopt `, for +a table you know that run made). `verify` compares schemas, table ids, versions, source ids, content and pipeline +hashes and each table's first rows with the plan; it does not read every row. + ## Pre-releases A pre-release is a version with an alpha, beta or release candidate part, or a development diff --git a/changelog.d/ITL-1186.md b/changelog.d/ITL-1186.md new file mode 100644 index 000000000..01dc142c2 --- /dev/null +++ b/changelog.d/ITL-1186.md @@ -0,0 +1,24 @@ +### 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`. +- Orcapod only reads SpiralDB for now. Every write of `SpiralDBConnector` (`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. Writing is a follow-up of ITL-1186. +- 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. +- `overrides` takes `server.url` only; other keys are refused. `~/.spiral.toml` is not read. +- A pinned version (`asof=`) whose columns differ from the table's recorded schema is refused. + +### Added + +- `scripts/migrate_spiral_schemas.py`: the one-time migration of a dataset's schemas (dry run, write, verify). +- `SpiralDBSignInError`: raised when no SpiralDB sign-in is found, instead of starting one. +- `TableSchemaError` and `UnrecordedTableSchemaWarning` for a table whose recorded schema is missing, incomplete or disagrees with it. + +### Changed + +- A `where` condition on a `uint64` column, which `pyspiral` could not compare, is answered. + +### 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. diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index 82afb73bb..dcc4d2fec 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -351,7 +351,7 @@ the stores keep it on every write (first write, append, merge, schema evolution; memory and on Delta). A database states whether it keeps field metadata with `keeps_field_metadata` (`orcapod.protocols.database_protocols.FieldMetadataKeepingDatabaseProtocol`): the -in-memory, Delta and SpiralDB databases do; the SQLite and PostgreSQL databases keep no +in-memory and Delta databases do; the SQLite and PostgreSQL databases keep no Arrow metadata at all. A node that would store a data-tag in a database that does not state it (a database without the member included) is refused when its database is attached, before anything is written. Use a database that keeps field metadata, or keep diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 83bf7acf3..499cbd724 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -236,11 +236,9 @@ A non-null column is created `NOT NULL` and reads back non-null. SQLite refuses other type (lists, structs, dates or timestamps on SQLite, narrower integers and floats, logical types) is refused. PostgreSQL also refuses a column name or a table name longer than -63 bytes, which it would truncate (`UnstorableTableNameError` for a table). `SpiralDBConnector` stores other types as written, except a -timestamp with a time zone (SpiralDB drops the zone), a logical (extension) type such as -`File`, `Path`, `UUID`, a user class or `set[int]` (SpiralDB drops the field metadata that -names it), and a null struct; SpiralDB reserves the `__` prefix on -value columns (the `__record_id` key is allowed) and `.` in any column name. The full list, +63 bytes, which it would truncate (`UnstorableTableNameError` for a table). A database on +`SpiralDBConnector` refuses every write for now (`SpiralDBWriteNotSupportedError`): Orcapod +reads SpiralDB only. 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 @@ -248,9 +246,9 @@ list-valued executor columns and `__`-prefixed columns. A side-effect node's log timestamp and `__data_context`, and an operator cache and a cached source hold `__data_context` too. So a job refuses these nodes when it is built, before anything runs: -- every function node, on all three connectors; -- every side-effect node, on SQLite and SpiralDB; -- every operator cache (an operator node with caching on) and cached source, on SpiralDB. +- every function node, on SQLite and PostgreSQL; +- every side-effect node, on SQLite; +- every node that stores anything, on SpiralDB. An operator cache or cached source on a SQL connector is refused when it is written, before anything is stored, if one of its columns has a type or name the connector does not store. On diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 2607c9f8e..4ed1897b1 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -296,17 +296,27 @@ A source never saves a schema it would read back differently. ### SpiralDB tables `SpiralDBTableSource` exposes a table in a [SpiralDB](https://spiraldb.com) project as a -source. Install the extra and log in once; the `spiral` command comes with the extra, and -pyspiral keeps the login in its per-user directory (`~/Library/Application Support/pyspiral/` -on macOS, `~/.config/pyspiral/` on Linux): +source. It reads SpiralDB's keyed tables through +[spiral-sdk](https://docs.spiraldb.com/docs/sdks/python). Install the extra and log in once; +the `spiral` command comes with the extra: ```bash uv add "orcapod[spiraldb]" # or, without uv: pip install "orcapod[spiraldb]" uv run spiral login ``` -Log in before you build a source. Without a saved login, pyspiral starts a sign-in in the -browser and waits until it is completed. +`pyspiral`, the older client, provides a Python module of the same name: never install both +in one environment. spiral-sdk has wheels for macOS on Apple silicon and for Linux. + +spiral-sdk takes credentials from the environment (`SPIRAL_TOKEN`, or `SPIRAL_CLIENT_ID` with +`SPIRAL_PRIVATE_KEY` for a workload, or `SPIRAL_WORKLOAD_ID` with a platform identity), then +from the saved login. With neither, Orcapod raises `SpiralDBSignInError` instead of letting +the client start a sign-in. A saved login that has expired is not detected: the client may +then print a sign-in prompt and wait. Stop it and run `uv run spiral login` again. + +Orcapod only reads SpiralDB for now. Writing a SpiralDB table (`SpiralDBConnector`, or a job +whose database is on one) raises `SpiralDBWriteNotSupportedError`; store a job's results in +another database, such as `DeltaTableDatabase`. To find the tables of a project and their key columns: @@ -333,18 +343,16 @@ sessions.as_df() # also as_polars_df(), as_pandas_df(), as_lazy_frame(), as_tab Things to know about Spiral tables: -- **Nullability comes from the table's nullability record.** See - [Nullability of Spiral columns](#nullability-of-spiral-columns): a recorded non-nullable - column has the type `T`, every other column `T | None`. +- **The schema is recorded beside the tables.** See + [The schema of a Spiral table](#the-schema-of-a-spiral-table): a column recorded as + non-nullable has the type `T`, every other column `T | None`. - **Types are kept.** Arrow types come through unchanged (`uint32` stays `uint32`), except that strings, binaries and lists become their large variants. Joining two Spiral tables on their shared key columns works; joining with another source requires the same Arrow types on both sides (`uint32` against `int64` is an error, not a conversion). - **Not supported:** columns of type `map`, which the Arrow hasher does not hash. Building the source raises `ValueError` naming each such column and its type; drop or convert - those columns first. `fixed_size_list` columns are supported. Also not supported: time zones (SpiralDB stores - timestamps without one) and Orcapod logical types such as `Path` (they come back as their - storage type). + those columns first. `fixed_size_list` columns are supported. - **Source identity.** A Spiral source is identified by where its table is, never by its rows. The default `source_id` is `spiraldb_table_v1:..
@`, for example @@ -371,7 +379,8 @@ them, and every read scans the table again: the rows into memory and return them all. To read part of a table, say so when you build the source. SpiralDB applies both -restrictions before any row is transferred: +restrictions before any row is transferred (except a condition on a `float16` column, which +Orcapod applies to the rows it receives, and then the limit): ```python @@ -379,7 +388,7 @@ first = SpiralDBTableSource("edi-tutorial-v1-841226", "spike_event", limit=1000) unit = SpiralDBTableSource( "edi-tutorial-v1-841226", "spike_event", where={"unit_id": 106} ) -print(first.row_count_estimate) # rows in the whole table, without reading any +print(first.row_count_estimate) # rows in the whole table; reads every key to count them ``` - `limit=n` reads the first `n` rows in key order. @@ -392,12 +401,11 @@ print(first.row_count_estimate) # rows in the whole table, without reading any `head()`, `as_table()` and the preview outside a run never move it. **The row cap.** One read returns at most `max_rows` rows (default 100,000). A read that -would return more raises `SourceTooLargeError`, which gives the row count and the ways out: +would return more raises `SourceTooLargeError`, which says so and gives the ways out: `limit=`, `where=`, or a larger `max_rows` (`max_rows=None` removes the cap). When nothing -but `limit=` bounds the read, the source decides before reading any row, from the row count -SpiralDB records for the table. That count can include deleted rows that are not yet -compacted, so a table near the cap can be refused although a scan would return fewer rows; -the error says so. The cap is there +but `limit=` bounds the read, the source decides before it hands on any row, by counting the +table's keys. SpiralDB keeps no row count of a keyed table, so the count is a read of one key +column; it stops one past the cap and is remembered for the version. The cap is there because a pipeline job keeps every row it processes in memory, about 5 KB per row for each node, so 100,000 rows cost about 0.5 GB per node. A table of millions of rows can be iterated with `max_rows=None`, but it cannot yet be run through a job on a laptop. @@ -409,7 +417,8 @@ at; `head(n)` reads `n`. The preview shows the rows it read in tag order (it ask `sort_by_tags`, as does `head(columns={"sort_by_tags": True})` or `all_info=True`): the rows read, sorted, not the first `n` of the table in tag order. The header line says what is shown, for example `SpiralDBTableSource[spike_event] — 10 rows read, sorted by tags, of -about 63,349` (the table's recorded row count, read without scanning), `all 4 rows, sorted +about 63,349` (the table's row count, from its keys; above 100,000 rows, or `max_rows` when +that is smaller, it says `of more than 100,000`), `all 4 rows, sorted by tags` when the source reads no more than that, or `10 matching rows read, sorted by tags (where unit_id=106); the table has about 63,349 rows` with `where=`. The unsorted `head()` says `first 10 rows of about 63,349`. Tag columns come first, and the line above the table @@ -548,10 +557,12 @@ print(Condition.of(day=day, started=started, recorded=recorded)) Anything else raises `TypeError`, naming the column and both types. Columns of other types (lists, structs) take no condition. - **The table system's equality.** Each condition is sent to SpiralDB as `column == value`, - and which rows it selects is SpiralDB's own equality, not Orcapod's. For a float column, - whether a NaN value selects the NaN rows and whether `0.0` selects the `-0.0` rows is - decided by SpiralDB; under the usual floating-point rule a NaN equals nothing, so such a - condition may select no row. To select rows by such values as Orcapod matches them, filter + and which rows it selects is SpiralDB's own equality, not Orcapod's. For a float column, NaN + selects the NaN rows and `0.0` does not select the `-0.0` rows (seen on the service, not + documented by it). A value that no `float32` is exactly, such as `0.1`, selects no row of a + `float32` column. SpiralDB cannot compare a `float16` column, so Orcapod reads the rows the + other conditions select and compares them itself, by the same rule and before `limit`. To + select rows by such values as Orcapod matches them, filter inside the pipeline (`PolarsFilter`). A NaN or infinite value is saved as `{"float": "nan"}`, `{"float": "inf"}` or `{"float": "-inf"}`, since JSON has no such number. - **One restriction per table in a pipeline.** A restricted source has the unrestricted @@ -665,102 +676,43 @@ whose schema is known without a scan. - A table that has only its key columns (for example one never written to) has no data column and cannot be a source. -#### Nullability of Spiral columns +#### The schema of a Spiral table SpiralDB reports every column as nullable, key columns included, and every field of a struct -column too, whatever nullability the data was written with; only list items keep a non-null -flag. Orcapod therefore keeps a **nullability record** for each table: the list of the table's -non-nullable columns and nested fields. The nullability record is an entry in the table's -key-value metadata, next to the data; it is not a row of the table. - -- **A table with a nullability record** (written by `SpiralDBConnector`, by a - `ConnectorArrowDatabase` on SpiralDB, or given one with `write_nullability_record`, as the - tables of the workshop project are): the columns it lists have the type `T`, so a function - pod can take `x: float`. Every batch read is checked: a null in a listed column raises - `NullInNonNullableColumnError` naming the table and the column, so a wrong nullability - record never hides a null. A nullability record that cannot be read in full (unknown - version, missing part, a column the table does not have) raises `NullabilityRecordError`. -- **A table without a nullability record** (for example the EDI sample tables): every column - has the type `T | None` (`str | None`, `datetime.datetime | None`, ...). A function pod - receiving such a column must accept `None`: annotate the parameter `x: float | None`, not - `x: float`, or the pod refuses the stream. Such a table reads exactly as it did before - nullability records existed: same schema, same hashes. -- **Joins are type strict.** A key column that is `T` in a table with a nullability record and - `T | None` in a table without one is an error, not a conversion. - -`SpiralDBConnector` writes the nullability record on a table's first write, before the rows. -It refuses a write that holds a null in a column its schema declares non-nullable, nested -fields included (SpiralDB would store a null written to a non-nullable struct field as `0`), -and a later write whose non-nullable columns differ from the nullability record. It never adds -a nullability record to a table that already holds rows, and never changes one. - -SpiralDB cannot store a null struct column. pyspiral refuses one (`Spiral does not support -null column groups`) unless the writer passes `push_down_nulls=True`, and then the null struct -reads back as a struct whose fields are all null: a different value with a different hash. (Both -were seen for a top-level struct column; nested structs were not tested.) `SpiralDBConnector` -refuses a write holding a null struct at any depth (a struct column, a struct field of a -struct, a struct inside a list) with `UnsupportedValueError` naming the table and the column, -and writes nothing. Null lists, null list items and null struct fields are stored as written. - -Writes are not coordinated between writers: SpiralDB has no lock for them. If two writers make -the first write to the same new table at once and one of them fails, the table can be left -without a nullability record although rows were written. It then reads as a table without one -(every column `T | None`); a null is never hidden. To repair it, check that the non-nullable -columns hold no null and call `write_nullability_record` as below. - -Other writers give a table its nullability record with `write_nullability_record`, passing the -Arrow schema the data was written with. It reads no data, so check first that no non-nullable -column holds a null. The same call replaces a wrong nullability record. - - -```python -import pyarrow as pa -import spiral - -from orcapod.databases import read_nullability_record, write_nullability_record - -table = spiral.Spiral().project("my-project-123456").table("default.session") -schema = pa.schema( - [ - pa.field("subject_id", pa.string(), nullable=False), - pa.field("weight", pa.float64(), nullable=False), - pa.field("booth", pa.string(), nullable=True), - ] -) -write_nullability_record(table, schema) # True if it was written, False if already current -print(read_nullability_record(table.get_metadata())) -# frozenset({('subject_id',), ('weight',)}) -``` - -**Adding or changing a nullability record changes the table's identity in Orcapod.** The -nullability is part of the schema, and the schema is part of a source's `pipeline_hash` and -`content_hash`. For the `session` table above: - - -```python -from orcapod.sources import SpiralDBTableSource - -# Before write_nullability_record: -SpiralDBTableSource("my-project-123456", "session").output_schema() -# (Schema({'subject_id': str | None}), Schema({'weight': float | None, 'booth': str | None})) - -# After it: -SpiralDBTableSource("my-project-123456", "session").output_schema() -# (Schema({'subject_id': str}), Schema({'weight': float, 'booth': str | None})) -``` - -The two sources have different `pipeline_hash` and `content_hash` values, and so do the nodes -built on them. A pipeline built on the table before it had a nullability record keeps its -stored results under its old identity: after the change, those nodes compute again under new -identities, and the earlier results are not reused (nothing stored is changed or deleted). -Pods annotated `weight: float | None` keep working, since they also accept `float`. So the -practical rule is: **write the nullability record when the table is created, before anyone -builds pipelines on it.** - -The nullability record is stored under the metadata key `__orcapod_nullability__` (format -`orcapod.nullability`, version 1), split over further keys when a wide table needs more than -SpiralDB's 8 KiB per metadata entry. Other SpiralDB clients ignore it and still see every -column as nullable. +column too, whatever nullability the data was written with; and it keeps no Arrow metadata. +Orcapod therefore reads each table with a schema that is recorded in one more table of its +dataset, `__orcapod_schemas__`: a row per table, with its column names, types, nullability at +every depth and metadata. The name is reserved, and listings leave it out. + +- **A recorded table** is read with exactly that schema. A non-nullable column has the type + `T`, so a function pod can take `x: float`. Every batch read is checked: a null in such a + column raises `NullInNonNullableColumnError` naming the table and the column, so a wrong + record never hides a null. +- **A table that disagrees with its row** is refused with `TableSchemaError`, which names both + sides: other columns or types, other key columns, another name. The row belongs to the + table's id, so a table dropped and created again is not read with the old row. An older + version (`asof=`) whose columns differ from the row is refused too. +- **A table that is not recorded** (its dataset has no `__orcapod_schemas__`, or no row for + it) reads as SpiralDB reports it: every column has the type `T | None` and no metadata, and + a function pod must accept `None` (`x: float | None`). `UnrecordedTableSchemaWarning` says + so, once per table and process. +- **A record that is not complete** is refused: the last row written says for which project + and dataset, how many tables, and a digest of their rows. When it is missing or does not + fit, every read that opens a table of the dataset raises `TableSchemaError`, and so does a + schema table that cannot be read. A connector's table handle that has already read one + version keeps the schema it read it with. +- **Joins are type strict.** A key column that is `T` in a recorded table and `T | None` in one + that is not is an error, not a conversion. + +The schema is part of a source's `pipeline_hash` and `content_hash`. So a table that becomes +recorded with non-nullable columns gets other hashes, as do the nodes built on it: they compute +again, and nothing stored is changed or deleted. + +**Tables written by an Orcapod release on pyspiral** kept this in the table's own metadata, +which spiral-sdk does not read. Until their dataset is migrated they read as not recorded. +`scripts/migrate_spiral_schemas.py` migrates a dataset once: it records for every table the +schema that release read it with, so schemas, hashes and source ids stay the same +([the steps](https://github.com/metamorphic-labs/orcapod-python/blob/main/RELEASING.md#migrating-a-spiraldb-dataset-from-pyspiral)). ### `DerivedSource` @@ -916,7 +868,7 @@ and neither does a source's own `run()` outside a job (`source.run()` does what | `ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource` | nothing: data held in memory cannot change; build a new source and bind it to run on new data | | `PollingSource` | polls once (and fetches when the poll reports new data); its modified time moves only when the fetch returned rows, to the moment it found them (a cursor's `modified_at` is informational) | | `DeltaTableSource` | reads the Delta log only; when the table's version moved, reads the table again and, if its rows changed (row order counts only without key columns, see below; a version that only compacted files changes nothing), holds the new rows | -| `SpiralDBTableSource` | holds no rows (every read scans the pinned version); reads the table's current version (metadata only: no row, and `max_rows` does not apply) and pins it when it is newer, so the next read returns the new rows; an `asof` you gave never moves; record ids are the canonical JSON of the key columns, so only new or changed rows are new entries (a version that moves without a change, if SpiralDB moves it on compaction, re-runs the nodes below and reuses every stored result) | +| `SpiralDBTableSource` | holds no rows (every read scans the pinned version); reads the table's current version (no row of it, and `max_rows` does not apply) and pins it when it is newer, so the next read returns the new rows; an `asof` you gave never moves; record ids are the canonical JSON of the key columns, so only new or changed rows are new entries (a version that moves without a change, if SpiralDB moves it on compaction, re-runs the nodes below and reuses every stored result) | | `CSVSource` | reads the file's modification time and size; when either changed, reads the file again and holds the new rows if they changed (row order counts only without key columns) | | `SQLiteTableSource`, `PostgreSQLTableSource`, `DBTableSource` | reads the whole table again and holds the new rows if they changed (with key columns in any order, so an unordered `SELECT` is not a change) | | `CachedSource` | checks the source it wraps; when that source's modified time moved since the cache last took in its rows (also when another source over it made the check), compares the rows' record hashes with the rows it presents (before its first read, with the cache: a read; nothing is written) and moves only when it will present new rows, (a row removed from the wrapped source stays cached); the check guarantees nothing for two cached sources that share one cache (the same `cache_path` or table): give each its own cache (ITL-1143) | diff --git a/docs/dev/scripts/itl_1371_logical_identity_appends.py b/docs/dev/scripts/itl_1371_logical_identity_appends.py index 1559c82c4..b874d36a9 100644 --- a/docs/dev/scripts/itl_1371_logical_identity_appends.py +++ b/docs/dev/scripts/itl_1371_logical_identity_appends.py @@ -149,7 +149,7 @@ def main() -> None: warnings.simplefilter("ignore") kinds = ["in-memory", "Delta", "SQLite", "SpiralDB"] with tempfile.TemporaryDirectory() as tmp: - from tests.test_databases import fake_pyspiral + 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/specs/itl-1186-switch.md b/docs/dev/specs/itl-1186-switch.md new file mode 100644 index 000000000..b340f6e16 --- /dev/null +++ b/docs/dev/specs/itl-1186-switch.md @@ -0,0 +1,167 @@ +# ITL-1186: the switch to spiral-sdk — design + +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 +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. + +## 1. The schema table + +One keyed table per dataset, `__orcapod_schemas__` (reserved). Key: `table_name`. + +| Column | Content | +|---|---| +| `table_name` (key), `table_id` | the table, and SpiralDB's id of it | +| `format` / `format_version` | `orcapod.table_schema` / 1; another value is refused | +| `nullability` | `recorded`, or `service` (metadata only: flags as the SDK reports them) | +| `schema` | Arrow IPC bytes of the newest schema: names, order, types, flags at every depth, field and schema metadata, extension identity in storage form | +| `earlier_schemas` | list of IPC bytes: the table's earlier column sets, oldest first | +| `key_columns`, `nullable_columns` | readable form (list, JSON of paths); must agree with `schema`, else refused | +| `written_at`, `written_by` | ISO UTC text; `orcapod , spiral-sdk ` or the tool (no user, host) | + +- The schema is the one Orcapod **presents today**: large variants, key columns in key order, + then the others by name, fields of a struct (and of a struct in it) by name. Anything else + would move hashes or row layout. The declared order can be a later format version. +- Deserialising brings a registered extension type to life; the reader puts every schema + through `canonical_form.storage_form_schema`, so metadata stays what was written. +- Size: a 5 MB cell was written and read back (measured), so the 8 KiB metadata limit is gone. +- Reserved: lookup, source, create, write and delete of the name raise `ValueError`; + `get_table_names` leaves it out. It has no row of its own; its columns are fixed and checked. +- **Cost.** Each lookup opens the schema table (0.1 to 0.2 s) and reuses the rows it read while + the version is unchanged (a snapshot is immutable). A changed version costs one whole read, + about 2 s. One cache per shared client, under a lock. Today's metadata read was 0.1 s. + A dataset with no schema table costs one refused lookup (0.1 s). +- The table is opened **before** the row is read, so a row is never older than its table. +- **Versions.** The current row serves every version. A snapshot must equal exactly one listed + column set, so a pinned read finds its own. Reading the schema table `asof` would lose every + pin older than the migration. + +## 2. Writes + +1. Validate as today; refuse a column name holding NUL (silently cut: measured). +2. Stage the rows (`writer().append`): the client's own refusals come here, nothing written. +3. If the row must change, write it. 4. `finish()`. 5. If the row changed, compare the returned + snapshot with it and raise on a difference, saying the rows are stored. + +A snapshot holding only key columns was never written (the service refuses key-only writes): +its row, **of any id or content**, is ignored on read and replaced on the first write. + +| Event | Result | +|---|---| +| killed or failed between create, row and first rows | key-only table; the leftover row is inert; the retry works. The `NullabilityRecordError` brick is gone | +| key-only table in `ConnectorArrowDatabase` | today refused for good (`Schema mismatch existing={__record_id}`). Proposed: the connector reports no columns yet through one method and the flush treats the table as new. Small; see Q3 | +| added nullable column, killed before the rows | the new set is listed, the table equals an earlier one: reads work | +| append that loosens a recorded column | refused (`NullabilityRecordMismatchError`), as today | +| changed metadata only | the row is replaced, put back if the rows fail, as today | +| non-empty table without a row | gets no nullability, as today; if the rows carry metadata, a `service` row (today's metadata entry) | +| two writers, different tables | two keys, independent | +| two writers, one table, equal schemas | equal rows; no harm | +| two writers, one table, different new columns | the rows race, last wins; the union is in neither row: the writer's check or the next read refuses, naming both. Nothing is mis-read. Repair: the tool | +| same data key, two writers | last wins, no conflict (measured), as today | +| lost reply of a commit | unknown outcome is said; an identical retry is safe | + +No row is written at create time. Zero rows: validated, then nothing written (pyspiral +panicked). `exist_ok` with another key gives a bare 409: the connector compares the keys and says so. + +## 3. Reads + +- Row found, id equal, columns (names, types) equal one listed set: that schema. Nulls in a + non-null path refused per batch, as now. +- Other id, extra, missing or differently typed column, unknown format, disagreeing readable + form: refused, naming the table's and the row's side. +- No row: as the SDK reports it. **An Orcapod table not yet migrated therefore reads nullable + and changes its pipeline and content hash, silently: migrate before upgrading.** +- "No schema table" is accepted only for the exact text `resource not found: + ..__orcapod_schemas__`. 401, 404 of a project, transport failure: raised + (measured: each has another text). Wrapped errors keep the SDK's text. + +## 4. What does not change, and the exceptions + +Unchanged: `table_` (resource_id equals it: reported by the earlier live study, rechecked by the conformance run), so default source +ids; `SOURCE_VERSION` 1; record ids; hashes; schema; key order; `limit`, `where`, `asof`, +streaming, pinning; saved jobs and configs. The SDK's schema of pyspiral tables equals +pyspiral's, with zoned timestamps, times and timestamp/date keys (measured). + +`where`: literals take the column's storage type (the SDK refuses a mismatch; `large_string` +becomes `string`). Results equal pyspiral's on 0.0, -0.0, NaN, bool, text, int, date32/64, zoned +and ns timestamps. A value a float32 column cannot hold exactly matches nothing in pyspiral but +matches after rounding in the SDK: the connector yields no row, as today. + +Exceptions, all user-visible: +1. `delete_table` of an existing table is refused (section 5). +2. Row counts (section 5): exact, dearer, and unknown above a bound in a preview. +3. `overrides`: `server.url` maps to `api_url`; any other key is refused. `~/.spiral.toml` and + `SPIRAL__*` are not read; sign-in is the SDK's. +4. New tables cannot have timestamp, date, fixed-size binary (or decimal) keys. Existing ones read. +5. An unmigrated table (section 3); a pinned version whose columns predate the migration. +6. Two processes by fork cannot share a client (hangs, measured); spawn works. + +## 5. What the SDK lacks + +| Need | Becomes | +|---|---| +| list | documented `GET /api/keyed-tables/projects/

/tables?dataset=`, all pages (also empty ones), token from the SDK client. One function; the token accessor is not public API, hence the exact pin | +| drop | `NotImplementedError` naming SpiralDB's own tools; absent table stays a no-op. Nothing in `src` calls it | +| rename | not offered today, not offered | +| count | a read of one key column. `row_count_estimate` is now exact but reads every key (1.3 s at 20,000 rows; grows). The `max_rows` check reads at most `max_rows + 1` keys (1 to 3 s) and remembers it per table version. `head()` counts at most as many; above that the total is unknown ("more than 100,000 rows") | +| key types | refused at create, naming the column | +| error bodies | status only; the connector adds operation and table as a note | +| threads, first call | 8 threads opening on a fresh client: 8 of 8 (one trial; opens, whereas the 7 of 8 pyspiral failures were first writes, not yet tried). A test; a lock around client creation only if it is ever seen | +| maps, null structs, zoned or extension columns, `__`, `.` | today's refusals kept, also where the SDK would store more | + +## 6. Fake and tests + +`tests/test_databases/fake_spiral_sdk.py`: `Client`, `Project`, `KeyedTable`, writer, scan, +expressions, HTTP list, `SpiralError`; every rule cites its evidence. `fake_pyspiral.py` goes. +One conformance module runs unchanged on the fake and, opt-in, the service. Live tests cannot +drop tables: they reuse fixed names, reset by `delete_keys` and column drops (documented in +the SDK, to be probed first); throwaway tables of my runs are dropped with pyspiral in its own +environment. Tests: every row of sections 2 to 5, many tables and columns, composite keys in +several orders, nested nullability, sync and async (sets), saved jobs from the pyspiral release, +crash at each write step, two writers, threads, early close, clean exit. + +## 7. Packaging + +`spiral-sdk==0.16.74`, exact: pre-alpha, six releases on one day, one private accessor. A bump +is a PR that reruns the live conformance. abi3 wheels cover 3.11 to 3.13 on macOS arm64 and +glibc Linux; no sdist. pyspiral leaves pyproject, lock, docs, probes' imports. A plain error +names pyspiral if it is installed instead. + +CI sign-in: `SPIRAL_CLIENT_ID` and `SPIRAL_PRIVATE_KEY` work unchanged (measured as the workload); +no workflow edit needed except comments that name pyspiral (Q5). Licence `MIT AND +LicenseRef-Spiral-libspiral`: the licence job installs no extras so never sees it, and its +partial match would accept it for the "MIT": a decision, not a pass (Q5). + +Telemetry: the SDK has a usage reporter, flushed at exit, with no documented off switch. One +keyed read through a proxy made 3 API calls, none to a usage route, also after a forced flush; +other hosts were not proxied, so "sends nothing" is **not** established. + +## 8. Migration tool, run by the developer + +`scripts/migrate_spiral_schemas.py`, three pinned commands, explicit project and datasets, no +login step; the principal found is printed first, and with no credentials it stops (the SDK +would start a device sign-in). + +1. `dry-run` (`uv run --with` Orcapod's last pyspiral commit): reads schema, record and metadata + with that Orcapod, records schema, content hash, pipeline hash, source id and table id per + table into a local file; prints per dataset the count and table names; prints a digest. +2. `write --digest ` (SDK environment): recomputes the summary from the live tables and the + schema table, refuses another digest, writes one row at a time, reading each back; stops at + the first disagreement, leaving whole rows; equal rows are skipped, so a rerun finishes. +3. `verify` (SDK only): builds each source and compares with the file, every value. + +It touches the schema table only and refuses what it cannot represent (broken record, record +naming absent columns, a row of another id or content). Tables with no record and no metadata +get no row. Tested on the throwaway project, with a run stopped half way and resumed. + +## Questions + +1. Branch: the issue's branch is PR 548's head. I propose `eywalker/itl-1186-spiral-sdk-switch`. +2. Counts as in section 5 (bounded check, unknown total in a preview)? Recommended. +3. Fix `ConnectorArrowDatabase` for a key-only table here? Recommended (one method). +4. Exact pin? Recommended. +5. May I edit only the comments of `run-tests.yml` that name pyspiral (else I leave them), and + who decides the licence and the unproven telemetry? diff --git a/docs/dev/specs/itl-926-live/inspect_tables.py b/docs/dev/specs/itl-926-live/inspect_tables.py index faf83ae54..b651880bc 100644 --- a/docs/dev/specs/itl-926-live/inspect_tables.py +++ b/docs/dev/specs/itl-926-live/inspect_tables.py @@ -39,7 +39,7 @@ def main() -> None: import spiral # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) - sp = spiral.Spiral() + sp = spiral.Spiral() # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 project = sp.project(args.project) names = sorted(r.table for r in project.list_tables() if r.dataset == args.dataset) if args.tables: diff --git a/docs/dev/specs/itl-926-live/live_verify.py b/docs/dev/specs/itl-926-live/live_verify.py index 6a81329ff..8a4927859 100644 --- a/docs/dev/specs/itl-926-live/live_verify.py +++ b/docs/dev/specs/itl-926-live/live_verify.py @@ -165,7 +165,7 @@ def __init__(self, args: argparse.Namespace) -> None: self.args = args self.overrides = {"server.url": args.server_url} if args.server_url else None - self.sp = sp.Spiral(overrides=self.overrides) + self.sp = sp.Spiral(overrides=self.overrides) # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 self.project = self.sp.project(args.project) self.prefix = f"itl926_{args.run_id}" self.created: list[str] = [] diff --git a/docs/dev/specs/itl-926-live/scan_cost_probe.py b/docs/dev/specs/itl-926-live/scan_cost_probe.py index 8a3fc00b1..df8c2065a 100644 --- a/docs/dev/specs/itl-926-live/scan_cost_probe.py +++ b/docs/dev/specs/itl-926-live/scan_cost_probe.py @@ -24,7 +24,7 @@ def main() -> None: import spiral # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) project_id, tables = sys.argv[1], sys.argv[2:] - sp = spiral.Spiral() + sp = spiral.Spiral() # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 project = sp.project(project_id) for name in tables: table = project.table(f"default.{name}") diff --git a/docs/dev/specs/itl-926-live/size_probe.py b/docs/dev/specs/itl-926-live/size_probe.py index 1379a5e1f..ef5fdc6a5 100644 --- a/docs/dev/specs/itl-926-live/size_probe.py +++ b/docs/dev/specs/itl-926-live/size_probe.py @@ -55,7 +55,7 @@ def _sizes(project_id: str, dataset: str) -> dict[str, dict[str, Any]]: """Return each table's manifest row count and sizes, without scanning data.""" import spiral # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) - sp = spiral.Spiral() + sp = spiral.Spiral() # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 project = sp.project(project_id) out: dict[str, dict[str, Any]] = {} for resource_ in sorted(project.list_tables(), key=lambda r: r.table): diff --git a/docs/dev/specs/itl-936-live/live_nullability.py b/docs/dev/specs/itl-936-live/live_nullability.py index 906fc3e2f..dc0521259 100644 --- a/docs/dev/specs/itl-936-live/live_nullability.py +++ b/docs/dev/specs/itl-936-live/live_nullability.py @@ -195,8 +195,8 @@ def write_mode(project: str, dataset: str, report: dict[str, Any]) -> bool: from orcapod.databases import ( SpiralDBConnector, - read_nullability_record, - write_nullability_record, + 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 ) from orcapod.errors import ( NullabilityRecordMismatchError, @@ -207,7 +207,7 @@ def write_mode(project: str, dataset: str, report: dict[str, Any]) -> bool: from orcapod.types import ColumnInfo run = time.strftime("%Y%m%d%H%M%S") - client = sp.Spiral() + client = sp.Spiral() # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 proj = client.project(project) names = { n: f"itl936_{run}_{n}" @@ -456,10 +456,10 @@ 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 + 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) + proj = sp.Spiral().project(project) # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 ok = True for name in tables: tbl = proj.table(f"{dataset}.{name}") diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index c7dd0063e..a60973db0 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -43,29 +43,25 @@ appended, which every database must refuse, naming the column; for a logical typ the same values under another logical type identifier (another extension name over the same storage), which would otherwise read back as the stored type. Every batch written is read back with `get_all_records`. -The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which -models what SpiralDB does to a column (no SpiralDB is used). No database tells tag +No database tells tag columns from data columns, so a type is kept or refused the same way in either role. The library value types (NumPy, pandas, Polars, torch) are [provisional](../concepts/arrays.md): their stored form may change in a later release. The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and -`ConnectorArrowDatabase` over `SQLiteConnector`, `PostgreSQLConnector` and -`SpiralDBConnector`. See [The database](../concepts/pipeline-job.md#the-database) for how a +`ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads +SpiralDB but does not write it for now (`SpiralDBWriteNotSupportedError`). 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: -- SpiralDB cannot store a null struct, so a struct column with a null row is refused - (the rows below have one); a struct column with no null row is kept. - SQLite reads a NaN back as NULL and `-0.0` as `0.0`, so a `double` column holding one is refused (the float rows below hold both); one without them is kept. - Delta has no `null` type: a new column, or a new nested field, holding only nulls with no type is refused (the `null` row below), while a `null`-typed value is kept where the table already stores a type. -- Delta and SpiralDB give a map's key and item fields back as `key` and `value`, so a map - with other names is refused. SpiralDB does not keep metadata on a map's key or item - field, so a map with such metadata is refused there. +- Delta gives a map's key and item fields back as `key` and `value`, so a map with other + names is refused. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. - Delta refuses a column whose name holds a backtick, or is one deltalake's MERGE reserves @@ -130,162 +126,158 @@ order, each field equal to the held one (the same type at every depth, the same type, the same field attributes), are put in the held order, whether the table was flushed in between or not. The in-memory database matches them to the rows still pending, else the stored table; Delta to the rows still pending (it matches a stored table by name -itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, +itself); a connector database (SQLite, PostgreSQL) to the rows it has pending, and to the stored table when it writes or reads them, checking them first against the table as it is then, by exact name and type (a column with field metadata stays in its -queued order at a flush; SpiralDB, which keeps field metadata, matches a write by name -itself). A table keeps the column -order the database gave its first write: the first write's order, except in SpiralDB, -which stores and reads a table's key columns first and then its other columns sorted by -name, whatever the order written (measured on SpiralDB itself). An append that also +queued order at a flush). A table keeps the column order of its first write. An append that also adds, omits or retypes a column keeps each database's own rule. The order of a struct's fields is not covered: a struct whose fields are in another order is another type here. ## Integer -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `int8` | kept | kept | refused | refused | kept | -| `int16` | kept | kept | refused | refused | kept | -| `int32` | kept | kept | refused | kept (by rule) | kept | -| `int64` | kept | kept | kept | kept (by rule) | kept | -| `uint8` | kept | kept (recorded type) | refused | refused | kept | -| `uint16` | kept | kept (recorded type) | refused | refused | kept | -| `uint32` | kept | kept (recorded type) | refused | refused | kept | -| `uint64` | kept | kept (recorded type) | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `int8` | kept | kept | refused | refused | +| `int16` | kept | kept | refused | refused | +| `int32` | kept | kept | refused | kept (by rule) | +| `int64` | kept | kept | kept | kept (by rule) | +| `uint8` | kept | kept (recorded type) | refused | refused | +| `uint16` | kept | kept (recorded type) | refused | refused | +| `uint32` | kept | kept (recorded type) | refused | refused | +| `uint64` | kept | kept (recorded type) | refused | refused | ## Float -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `halffloat (float16)` | kept | kept (recorded type) | refused | refused | kept | -| `float (float32)` | kept | kept | refused | kept (by rule) | kept | -| `double (float64)` | kept | kept | refused | kept (by rule) | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `halffloat (float16)` | kept | kept (recorded type) | refused | refused | +| `float (float32)` | kept | kept | refused | kept (by rule) | +| `double (float64)` | kept | kept | refused | kept (by rule) | ## Decimal -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `decimal128(10, 2)` | kept | kept | refused | refused | kept | -| `decimal128(38, 4)` | kept | kept | refused | refused | kept | -| `decimal256(40, 2)` | kept | refused | refused | refused | kept | -| `decimal256(76, 10)` | kept | refused | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `decimal128(10, 2)` | kept | kept | refused | refused | +| `decimal128(38, 4)` | kept | kept | refused | refused | +| `decimal256(40, 2)` | kept | refused | refused | refused | +| `decimal256(76, 10)` | kept | refused | refused | refused | ## Boolean -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `bool` | kept | kept | kept | kept (by rule) | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `bool` | kept | kept | kept | kept (by rule) | ## Null -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `null` | kept | refused | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `null` | kept | refused | refused | refused | ## Temporal -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `date32` | kept | kept | refused | kept (by rule) | kept | -| `date64` | kept | kept (recorded type) | refused | refused | kept | -| `time32[s]` | kept | kept (recorded type) | refused | refused | kept | -| `time32[ms]` | kept | kept (recorded type) | refused | refused | kept | -| `time64[us]` | kept | kept (recorded type) | refused | refused | kept | -| `time64[ns]` | kept | kept (recorded type) | refused | refused | kept | -| `timestamp[s]` | kept | kept (recorded type) | refused | refused | kept | -| `timestamp[ms]` | kept | kept (recorded type) | refused | refused | kept | -| `timestamp[us]` | kept | kept | refused | kept (by rule) | kept | -| `timestamp[ns]` | kept | kept (recorded type) | refused | refused | kept | -| `timestamp[s, tz=UTC]` | kept | kept (recorded type) | refused | refused | refused | -| `timestamp[ms, tz=UTC]` | kept | kept (recorded type) | refused | refused | refused | -| `timestamp[us, tz=UTC]` | kept | kept | refused | kept (by rule) | refused | -| `timestamp[ns, tz=UTC]` | kept | kept (recorded type) | refused | refused | refused | -| `timestamp[s, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | -| `timestamp[ms, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | -| `timestamp[us, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | -| `timestamp[ns, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | -| `duration[s]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[ms]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[us]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[ns]` | kept | kept (recorded type) | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `date32` | kept | kept | refused | kept (by rule) | +| `date64` | kept | kept (recorded type) | refused | refused | +| `time32[s]` | kept | kept (recorded type) | refused | refused | +| `time32[ms]` | kept | kept (recorded type) | refused | refused | +| `time64[us]` | kept | kept (recorded type) | refused | refused | +| `time64[ns]` | kept | kept (recorded type) | refused | refused | +| `timestamp[s]` | kept | kept (recorded type) | refused | refused | +| `timestamp[ms]` | kept | kept (recorded type) | refused | refused | +| `timestamp[us]` | kept | kept | refused | kept (by rule) | +| `timestamp[ns]` | kept | kept (recorded type) | refused | refused | +| `timestamp[s, tz=UTC]` | kept | kept (recorded type) | refused | refused | +| `timestamp[ms, tz=UTC]` | kept | kept (recorded type) | refused | refused | +| `timestamp[us, tz=UTC]` | kept | kept | refused | kept (by rule) | +| `timestamp[ns, tz=UTC]` | kept | kept (recorded type) | refused | refused | +| `timestamp[s, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | +| `timestamp[ms, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | +| `timestamp[us, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | +| `timestamp[ns, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | +| `duration[s]` | kept | kept (recorded type) | refused | refused | +| `duration[ms]` | kept | kept (recorded type) | refused | refused | +| `duration[us]` | kept | kept (recorded type) | refused | refused | +| `duration[ns]` | kept | kept (recorded type) | refused | refused | ## String and binary -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `string` | kept | kept | kept | kept (by rule) | kept | -| `large_string` | kept | kept | kept | kept (by rule) | kept | -| `binary` | kept | kept | kept | kept (by rule) | kept | -| `large_binary` | kept | kept | kept | kept (by rule) | kept | -| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `string` | kept | kept | kept | kept (by rule) | +| `large_string` | kept | kept | kept | kept (by rule) | +| `binary` | kept | kept | kept | kept (by rule) | +| `large_binary` | kept | kept | kept | kept (by rule) | +| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | ## List -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `list` | kept | kept (recorded type) | refused | refused | kept | -| `list` | kept | kept (recorded type) | refused | refused | kept | -| `large_list` | kept | kept (recorded type) | refused | refused | kept | -| `large_list` | kept | kept (recorded type) | refused | refused | kept | -| `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | kept | -| `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | kept | -| `large_list` | kept | kept (recorded type) | refused | refused | kept | -| `fixed_size_list[0]` | kept | kept (recorded type) | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `list` | kept | kept (recorded type) | refused | refused | +| `list` | kept | kept (recorded type) | refused | refused | +| `large_list` | kept | kept (recorded type) | refused | refused | +| `large_list` | kept | kept (recorded type) | refused | refused | +| `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | +| `fixed_size_list[2]` | kept | kept (recorded type) | refused | refused | +| `large_list` | kept | kept (recorded type) | refused | refused | +| `fixed_size_list[0]` | kept | kept (recorded type) | refused | refused | ## Struct and map -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `struct` | kept | kept | refused | refused | refused | -| `struct<> (no fields)` | kept | refused | refused | refused | refused | -| `uuid (Arrow's canonical extension type)` | kept | refused | refused | refused | refused | -| `struct[2]>` | kept | kept (recorded type) | refused | refused | refused | -| `map` | kept | kept (recorded type) | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `struct` | kept | kept | refused | refused | +| `struct<> (no fields)` | kept | refused | refused | refused | +| `uuid (Arrow's canonical extension type)` | kept | refused | refused | refused | +| `struct[2]>` | kept | kept (recorded type) | refused | refused | +| `map` | kept | kept (recorded type) | refused | refused | ## Names and metadata -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `large_list` | kept | kept (recorded type) | refused | refused | kept | -| `struct` | kept | kept (recorded type) | refused | refused | refused | -| `map, keys sorted` | kept | kept (recorded type) | refused | refused | kept | -| `map, keys sorted` | kept | refused | refused | refused | refused | -| `map (item metadata)` | kept | kept (recorded type) | refused | refused | refused | -| `map (key metadata)` | kept | kept (recorded type) | refused | refused | refused | -| `map> (metadata inside the item)` | kept | kept (recorded type) | refused | refused | refused | -| `int64 {unit: s} (field metadata)` | kept | kept | refused | refused | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `large_list` | kept | kept (recorded type) | refused | refused | +| `struct` | kept | kept (recorded type) | refused | refused | +| `map, keys sorted` | kept | kept (recorded type) | refused | refused | +| `map, keys sorted` | kept | refused | refused | refused | +| `map (item metadata)` | kept | kept (recorded type) | refused | refused | +| `map (key metadata)` | kept | kept (recorded type) | refused | refused | +| `map> (metadata inside the item)` | kept | kept (recorded type) | refused | refused | +| `int64 {unit: s} (field metadata)` | kept | kept | refused | refused | ## Nullability -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `int64 not null` | kept | kept | kept | kept (by rule) | kept | -| `string not null` | kept | kept | kept | kept (by rule) | kept | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `int64 not null` | kept | kept | kept | kept (by rule) | +| `string not null` | kept | kept | kept | kept (by rule) | ## Orcapod logical type -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `File` | kept | kept | refused | refused | refused | -| `Directory` | kept | kept | refused | refused | refused | -| `Path` | kept | kept | refused | refused | refused | -| `UPath` | kept | kept | refused | refused | refused | -| `uuid.UUID` | kept | kept | refused | refused | refused | -| `list[Path]` | kept | kept | refused | refused | refused | -| `set[int]` | kept | kept | refused | refused | refused | -| `set[uuid.UUID]` | kept | kept | refused | refused | refused | -| `dict[str, int]` | kept | kept (recorded type) | refused | refused | kept | -| `user class, exact (dataclass)` | kept | kept | refused | refused | refused | -| `user class, structural (orcapod.dataclass)` | kept | kept | refused | refused | refused | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `File` | kept | kept | refused | refused | +| `Directory` | kept | kept | refused | refused | +| `Path` | kept | kept | refused | refused | +| `UPath` | kept | kept | refused | refused | +| `uuid.UUID` | kept | kept | refused | refused | +| `list[Path]` | kept | kept | refused | refused | +| `set[int]` | kept | kept | refused | refused | +| `set[uuid.UUID]` | kept | kept | refused | refused | +| `dict[str, int]` | kept | kept (recorded type) | refused | refused | +| `user class, exact (dataclass)` | kept | kept | refused | refused | +| `user class, structural (orcapod.dataclass)` | kept | kept | refused | refused | ## Library value type -| Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | -|---|---|---|---|---|---| -| `numpy.ndarray` (provisional) | kept | kept | refused | refused | refused | -| `pandas.DataFrame` (provisional) | kept | kept | refused | refused | refused | -| `pandas.Series` (provisional) | kept | kept | refused | refused | refused | -| `polars.DataFrame` (provisional) | kept | kept | refused | refused | refused | -| `polars.Series` (provisional) | kept | kept | refused | refused | refused | -| `torch.Tensor` (provisional) | kept | kept | refused | refused | refused | +| Type | in-memory | Delta | SQLite | PostgreSQL | +|---|---|---|---|---| +| `numpy.ndarray` (provisional) | kept | kept | refused | refused | +| `pandas.DataFrame` (provisional) | kept | kept | refused | refused | +| `pandas.Series` (provisional) | kept | kept | refused | refused | +| `polars.DataFrame` (provisional) | kept | kept | refused | refused | +| `polars.Series` (provisional) | kept | kept | refused | refused | +| `torch.Tensor` (provisional) | kept | kept | refused | refused | diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 0a1ff215c..6130f2dd5 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -329,7 +329,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 nullability record | the nullability path list | SHA-256 hex | chunk key and checksum of a stored record (a name) | `databases/spiraldb_nullability.py:_encode`, `databases/spiraldb_nullability.py:read_nullability_record` | +| 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` | | 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` | | random ids | nothing | `uuid4`, `uuid7` | run ids, datagram and record uuids, observer ids, correlation keys | (not hashes) | | unused code | Arrow tables | SHA-256, SHA3, BLAKE2b | no caller; removal is ITL-1156 | (not reached) `hashing/arrow_utils.py`, `hashing/arrow_serialization.py` | diff --git a/pyproject.toml b/pyproject.toml index 8913e2945..ff983e388 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,9 @@ redis = ["redis>=6.2.0"] ray = ["ray[default]>=2.60.0,<3", "ipywidgets>=8.1.7"] postgresql = ["psycopg[binary]>=3.1.17"] spiraldb = [ - "pyspiral>=0.16.33", + # Exact: a pre-alpha that releases daily, and Orcapod reads two attributes that are + # not its public API (ITL-1186). How to move it: RELEASING.md. + "spiral-sdk==0.16.74", ] # Convenience extra that installs PyTorch. Orcapod's torch.Tensor support depends only on # torch being importable, however it was installed (ITL-871). 2.6 is the first version whose diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py new file mode 100644 index 000000000..811de8d79 --- /dev/null +++ b/scripts/migrate_spiral_schemas.py @@ -0,0 +1,654 @@ +"""Move the schemas of SpiralDB tables written by Orcapod on pyspiral to spiral-sdk. + +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. + +Three steps, each in an environment of its own (the two clients cannot be installed +together); ``RELEASING.md`` has the exact commands: + +1. ``dry-run``, with the last Orcapod on pyspiral: writes the plan to a file (what each + table is read as: schema, content hash, pipeline hash, source id) and prints its digest. +2. ``write --digest ``, with Orcapod on spiral-sdk: refuses unless the plan has that + digest and every table still is as it was planned, then writes one row per table and the + completion marker last. Run again after an interruption, it continues the same plan. +3. ``verify``, with Orcapod on spiral-sdk alone: every source is what the plan says. + +No step signs in: each uses the credentials that are there, names the principal, and stops +without any. +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import importlib +import json +import os +import sys +import warnings +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +SCHEMA_TABLE = "__orcapod_schemas__" +PLAN_FORMAT = "orcapod.spiral_migration" +PLAN_VERSION = 1 +ROW_FORMAT = "orcapod.table_schema" +ROW_FORMAT_VERSION = 1 +FIRST_ROWS = 20 +CREATING = "creating" +REFUSED = "refused" + + +class MigrationError(Exception): + """The step cannot go on; the message says why.""" + + +def canonical(value: Any) -> str: + """Return ``value`` as JSON in one form.""" + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + +def plan_digest(plan: dict[str, Any]) -> str: + """Return the SHA-256 (hex) of the plan's canonical bytes.""" + return hashlib.sha256(canonical(plan).encode()).hexdigest() + + +def spiral_module() -> Any: + """Return the ``spiral`` module of this environment: pyspiral's or spiral-sdk's.""" + return importlib.import_module("spiral") + + +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 + Orcapod does not have it. + """ + env = os.environ + if env.get("SPIRAL_TOKEN") or env.get("SPIRAL_WORKLOAD_ID"): + return + if env.get("SPIRAL_CLIENT_ID") and env.get("SPIRAL_PRIVATE_KEY"): + return + if given := env.get("SPIRAL_AUTH_FILE"): + path = Path(given) + elif sys.platform == "darwin": + path = Path.home() / "Library/Application Support/pyspiral/auth.json" + else: + config = env.get("XDG_CONFIG_HOME") or Path.home() / ".config" + path = Path(config) / "pyspiral/auth.json" + try: + saved = path.stat().st_size > 0 + except OSError: + saved = False + if not saved: + raise MigrationError( + f"no SpiralDB sign-in was found ({path}). Run 'spiral login' first" + ) + + +def principal_of(token: str) -> str: + """Return the principal a token names; the token itself is never shown.""" + body = token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4))) + return str(claims.get("sub", "unknown")) + + +# ------------------------------------------------------------------------------ dry run + + +def nullable_paths(schema: Any) -> list[list[str]]: + """Return the nullable paths of a schema, as the schema table holds them.""" + import pyarrow as pa + + out: list[list[str]] = [] + + def walk(field: Any, path: list[str]) -> None: + if field.nullable: + out.append(path) + t = field.type + if pa.types.is_struct(t): + for i in range(t.num_fields): + walk(t.field(i), [*path, t.field(i).name]) + elif ( + pa.types.is_list(t) + or pa.types.is_large_list(t) + or pa.types.is_fixed_size_list(t) + ): + walk(t.value_field, [*path, "[]"]) + + for field in schema: + walk(field, [field.name]) + return sorted(out) + + +def unrepresentable(schema: Any) -> str | None: + """Return why a schema cannot be recorded, or ``None``.""" + import pyarrow as pa + + def walk(t: Any, where: str) -> str | None: + if isinstance(t, pa.BaseExtensionType): + return f"{where} is an extension type" + if pa.types.is_string_view(t) or pa.types.is_binary_view(t): + return f"{where} is {t}, which spiral-sdk does not read" + for i in range(t.num_fields): + if (why := walk(t.field(i).type, f"{where}.{t.field(i).name}")) is not None: + return why + return None + + for field in schema: + if (why := walk(field.type, field.name)) is not None: + return why + return None + + +def source_values(project: str, dataset: str, name: str) -> dict[str, Any]: + """Return the identity of the default source on a table, or why there is none.""" + from orcapod.sources import SpiralDBTableSource + + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + source = SpiralDBTableSource(project, name, dataset=dataset) + except (ValueError, TypeError) as exc: + return {"refused": type(exc).__name__} + with source: + tags, data = source.output_schema(all_info=True) + return { + "source_id": source.source_id, + "content_hash": source.content_hash().to_string(), + "pipeline_hash": source.pipeline_hash().to_string(), + "tag_schema": {k: str(v) for k, v in tags.items()}, + "data_schema": {k: str(v) for k, v in data.items()}, + } + + +def first_rows_digest(connector: Any, name: str) -> str | None: + """Return Orcapod's hash of a table's first rows (``FIRST_ROWS``) as it reads them; + ``None`` for a table it cannot hash (a map column). + + Args: + connector: The connector of the table's dataset. + name: The table. + """ + import pyarrow as pa + + from orcapod.contexts import get_default_context + + handle = connector.lookup_table(name) + batches = list(handle.scan_batches(limit=FIRST_ROWS)) + rows = pa.Table.from_batches(batches, schema=handle.arrow_schema()) + if any(pa.types.is_map(field.type) for field in rows.schema): + return None + return get_default_context().arrow_hasher.hash_table(rows).to_string() + + +def describe_table( + connector: Any, project: str, dataset: str, name: str +) -> dict[str, Any]: + """Return one table's part of the plan (the pyspiral Orcapod).""" + handle = connector.lookup_table(name) + schema = handle.arrow_schema() + if (why := unrepresentable(schema)) is not None: + raise MigrationError(f"{project}/{dataset}/{name} cannot be recorded: {why}") + metadata = handle._table.get_metadata() + recorded = any(k.startswith("__orcapod_nullability__") for k in metadata) + return { + "row": { + "table_id": handle.table_id, + "table_name": name, + "format": ROW_FORMAT, + "format_version": ROW_FORMAT_VERSION, + "nullability": "record" + if recorded or "__arrow_metadata__" in metadata + else "service", + "captured_version": handle.version(), + "schema": base64.b64encode(schema.serialize().to_pybytes()).decode(), + "key_columns": handle.key_columns, + "nullable_columns": nullable_paths(schema), + }, + "source": source_values(project, dataset, name), + "first_rows": first_rows_digest(connector, name), + } + + +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 + + sp = spiral_module() + + if hasattr(sp, "keyed_tables") or not hasattr(sp, "Spiral"): + raise MigrationError( + "this environment has spiral-sdk; the dry run needs the last Orcapod on " + "pyspiral (see RELEASING.md)" + ) + client = sp.Spiral() + token = client.authn.token() + print( + "principal:", "none" if token is None else principal_of(token.expose_secret()) + ) + project = client.project(args.project) + tables: dict[str, list[str]] = {} + schema_tables: dict[str, str] = {} + for found in project.list_tables(): + if found.table == SCHEMA_TABLE: + schema_tables[found.dataset] = found.id + else: + tables.setdefault(found.dataset, []).append(found.table) + if missing := [d for d in args.dataset if d not in tables]: + raise MigrationError( + f"no table in dataset(s) {missing}; the project has {sorted(tables)}" + ) + plan: dict[str, Any] = { + "format": PLAN_FORMAT, + "version": PLAN_VERSION, + "project": args.project, + "datasets": {}, + } + for dataset in sorted(set(args.dataset)): + connector = SpiralDBConnector(args.project, dataset) + described = [] + for name in sorted(tables[dataset]): + described.append(describe_table(connector, args.project, dataset, name)) + print(".", end="", flush=True) + print() + present = schema_tables.get(dataset) + plan["datasets"][dataset] = {"schema_table": present, "tables": described} + print(f"{dataset}: {len(described)} table rows and 1 completion marker") + print( + f" {SCHEMA_TABLE}: " + + ("absent, as expected" if present is None else f"EXISTS ({present})") + ) + for table in described: + row, source = table["row"], table["source"] + note = f", no source: {source['refused']}" if "refused" in source else "" + print(f" {row['table_name']} (nullability: {row['nullability']}{note})") + Path(args.plan).write_text(canonical(plan)) + print("wrote the plan to", args.plan) + print("digest:", plan_digest(plan)) + + +# --------------------------------------------------------------------- write and verify + + +def read_plan(path: str) -> dict[str, Any]: + """Return the plan in a file.""" + try: + plan = json.loads(Path(path).read_text()) + except (OSError, ValueError) as exc: + raise MigrationError(f"the plan {path} cannot be read: {exc}") from exc + if plan.get("format") != PLAN_FORMAT or plan.get("version") != PLAN_VERSION: + raise MigrationError(f"{path} is not a plan this tool reads") + return plan + + +def require_scope(plan: dict[str, Any], args: argparse.Namespace) -> None: + """Refuse a plan for another project or other datasets than the arguments name.""" + if plan["project"] != args.project or set(plan["datasets"]) != set(args.dataset): + raise MigrationError( + f"the plan is for project {plan['project']!r}, datasets " + f"{sorted(plan['datasets'])}; the arguments name {args.project!r}, " + f"{sorted(set(args.dataset))}" + ) + + +def sdk_client() -> Any: + """Return a spiral-sdk client and print its principal.""" + spiral = spiral_module() + + if not hasattr(spiral, "Client"): + raise MigrationError( + "this environment has pyspiral; this step needs Orcapod on spiral-sdk (see " + "RELEASING.md)" + ) + client = spiral.Client() + print("principal:", principal_of(client._native.access_token())) + return client + + +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 + + rows = [] + for table in tables: + planned = table["row"] + row = SchemaRow( + planned["table_id"], + planned["table_name"], + tuple(planned["key_columns"]), + base64.b64decode(planned["schema"]), + planned["nullability"], + planned["captured_version"], + ) + # Read as the stored row will be, and equal to the plan, byte for byte. + if SchemaRow.from_stored(row.stored()) != row or row.content() != planned: + raise MigrationError( + f"the plan's row of {planned['table_name']} is invalid" + ) + rows.append(row) + return rows + + +def require_unchanged( + client: Any, + project: str, + dataset: str, + tables: list[dict[str, Any]], + rows: list[Any], +) -> None: + """Refuse unless every table of the dataset is as the plan found it.""" + from orcapod.databases.spiraldb_connector import _list_keyed_tables + from orcapod.databases.spiraldb_schema_table import ( + compared_columns, + describe_difference, + ) + + # Not the connector's listing: it refuses a dataset whose migration was interrupted. + listed = _list_keyed_tables(client, project, dataset) + names = sorted(name for name in listed.values() if name != SCHEMA_TABLE) + planned = sorted(row.table_name for row in rows) + if names != planned: + raise MigrationError( + f"{dataset}: tables were added or removed since the dry run: " + f"{sorted(set(names) ^ set(planned))}" + ) + for table, row in zip(tables, rows): + handle = client.keyed_table(project, dataset, row.table_name) + where = f"{dataset}/{row.table_name}" + if handle.resource_id != row.table_id: + raise MigrationError(f"{where} is another table than in the dry run") + if int(handle.version_id) != table["row"]["captured_version"]: + raise MigrationError( + f"{where} was written since the dry run (version {handle.version_id}, " + f"planned {row.captured_version})" + ) + if list(handle.key_columns) != list(row.key_columns): + raise MigrationError( + f"{where} has key columns {list(handle.key_columns)}, planned " + f"{list(row.key_columns)}" + ) + found = handle.schema() + if compared_columns(found) != compared_columns(row.schema): + raise MigrationError( + f"{where} differs from the plan: {describe_difference(found, row.schema)}" + ) + + +def note_path(args: argparse.Namespace) -> Path: + """Return where the schema tables this plan's write created are noted.""" + return Path(f"{args.plan}.created.json") + + +def read_note(args: argparse.Namespace) -> dict[str, str]: + """Return the schema tables this plan's write created: dataset to table id.""" + try: + note = json.loads(note_path(args).read_text()) + except OSError: + return {} + return note["created"] if note["digest"] == args.digest else {} + + +def write_note(args: argparse.Namespace, dataset: str, value: str) -> None: + """Note what this plan's write creates in a dataset: ``CREATING``, then the table id, + or ``REFUSED``. + + The note is replaced as a whole, so it is never half written. + """ + created = {**read_note(args), dataset: value} + new = Path(f"{note_path(args)}.new") + new.write_text(canonical({"digest": args.digest, "created": created})) + os.replace(new, note_path(args)) + + +def require_own_schema_table( + client: Any, args: argparse.Namespace, dataset: str, planned: dict[str, Any] +) -> 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 + + if planned["schema_table"] is not None: + raise MigrationError( + f"{dataset}: {SCHEMA_TABLE} existed at the dry run ({planned['schema_table']})" + ) + table = _open_keyed_table(client, args.project, dataset, SCHEMA_TABLE) + noted = read_note(args).get(dataset) + if ( + table is not None + and noted == CREATING + and list(table.key_columns) == ["table_id"] + and int(table.version_id) == 0 + ): + # Stopped around the creation. An empty table looks the same whoever made it, so + # a person says that it is this plan's. + if args.adopt != table.resource_id: + raise MigrationError( + f"{dataset}: an earlier run stopped while creating {SCHEMA_TABLE}, and " + f"there is an empty one ({table.resource_id}). If that run made it, and " + f"nobody else, run again with --adopt {table.resource_id}" + ) + write_note(args, dataset, table.resource_id) + return table + if noted == REFUSED or (table is not None and noted != table.resource_id): + found = "none now" if table is None else table.resource_id + raise MigrationError( + f"{dataset}: {SCHEMA_TABLE} ({found}) was not created by this " + f"plan's write ({note_path(args)} does not name it)" + ) + return 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 + + table = _open_keyed_table(client, project, dataset, SCHEMA_TABLE) + if table is None or not require_schema_table(table): + return {}, None + return read_rows(table.scan().to_table().to_pylist()) + + +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 + + plan = read_plan(args.plan) + require_scope(plan, args) + if plan_digest(plan) != args.digest: + raise MigrationError( + f"the plan's digest is {plan_digest(plan)}, not {args.digest}" + ) + client = sdk_client() + project = plan["project"] + prepared = {} + # Everything is checked before anything is written. + for dataset, planned in plan["datasets"].items(): + tables = planned["tables"] + rows = planned_rows(tables) + require_unchanged(client, project, dataset, tables, rows) + _ = require_own_schema_table(client, args, dataset, planned) + stored, _ = open_rows(client, project, dataset) + wanted = {row.table_id: row for row in rows} + for table_id, row in stored.items(): + if table_id not in wanted: + raise MigrationError( + f"{dataset}: the schema table has a row of table {table_id!r} " + f"({row.table_name!r}), which is not in the plan" + ) + if row.content() != wanted[table_id].content(): + raise MigrationError( + f"{dataset}: the schema table's row of {row.table_name!r} differs " + "from the plan's" + ) + prepared[dataset] = rows + by = f"migrate_spiral_schemas, plan {args.digest[:12]}" + + def put(dataset: str, values: dict[str, Any]) -> None: + handle = require_own_schema_table( + client, args, dataset, plan["datasets"][dataset] + ) + if handle is None: + # Created once, exclusively; the note is there before and after. + write_note(args, dataset, CREATING) + try: + handle = client.project(project).create_keyed_table( + dataset, SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=False + ) + except Exception as exc: + if "status 409" not in str(exc): + raise + # Another's: never to be adopted, by this run or a later one. + write_note(args, dataset, REFUSED) + raise MigrationError( + f"{dataset}: another program created {SCHEMA_TABLE} just now" + ) from exc + write_note(args, dataset, handle.resource_id) + now = datetime.now(timezone.utc).isoformat(timespec="seconds") + values = {**values, "written_at": now, "written_by": by} + handle.append(pa.Table.from_pylist([values], schema=st.ROW_SCHEMA)) + + written = 0 + for dataset, rows in prepared.items(): + present, marker = open_rows(client, project, dataset) + for row in rows: + if row.table_id in present: + continue + put(dataset, row.stored()) + written += 1 + present, marker = open_rows(client, project, dataset) + if ( + row.table_id not in present + or present[row.table_id].content() != row.content() + ): + raise MigrationError( + f"{dataset}: the row of {row.table_name!r} does not read back as " + "written" + ) + print(f"{dataset}: wrote {row.table_name}", flush=True) + if args.stop_after is not None and written >= args.stop_after: + raise MigrationError("stopped as asked (--stop-after)") + # Again just before the marker, and after it. + require_unchanged( + client, project, dataset, plan["datasets"][dataset]["tables"], rows + ) + final = st.marker_values(st.Scope(project, dataset, args.digest), rows) + if marker is None or any(marker[k] != v for k, v in final.items()): + put(dataset, final) + try: + require_unchanged( + client, project, dataset, plan["datasets"][dataset]["tables"], rows + ) + present, marker = open_rows(client, project, dataset) + st.require_complete(project, dataset, present, marker) + if {i: r.content() for i, r in present.items()} != { + r.table_id: r.content() for r in rows + }: + raise MigrationError( + f"{dataset}: the schema table is not what was planned" + ) + except BaseException as exc: + # Whatever happened, no valid marker is left: reads of the dataset are + # refused until a write step ends well. + put(dataset, {**final, "rows_digest": "withdrawn: not checked to the end"}) + raise MigrationError( + f"{exc or type(exc).__name__}. The completion marker was withdrawn: run " + "write again, or the dry run if the dataset changed" + ) from exc + print(f"{dataset}: complete, {len(rows)} tables") + print(f"wrote {written} rows; now run verify") + + +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 + + plan = read_plan(args.plan) + require_scope(plan, args) + from orcapod.databases import spiraldb_schema_table as st + + client = sdk_client() + project = plan["project"] + wrong: list[str] = [] + checked = refused = 0 + for dataset, planned in plan["datasets"].items(): + tables = planned["tables"] + connector = SpiralDBConnector(project, dataset) + rows = planned_rows(tables) + require_unchanged(client, project, dataset, tables, rows) + present, marker = open_rows(client, project, dataset) + st.require_complete(project, dataset, present, marker) + if ( + present != {row.table_id: row for row in rows} + or marker is None + or marker["plan_digest"] != plan_digest(plan) + ): + raise MigrationError(f"{dataset}: the schema table is not the plan's") + for row in rows: + schema = connector.get_arrow_schema(row.table_name) + if not schema.equals(row.schema, check_metadata=True): + wrong.append(f"{dataset}/{row.table_name}: schema") + for table in tables: + name, expected = table["row"]["table_name"], table["source"] + found = source_values(project, dataset, name) + for key in sorted(set(expected) | set(found)): + if expected.get(key) != found.get(key): + wrong.append( + f"{dataset}/{name}: {key}: planned {expected.get(key)!r}, found " + f"{found.get(key)!r}" + ) + rows_found = first_rows_digest(connector, name) + if rows_found != table["first_rows"]: + wrong.append(f"{dataset}/{name}: its first {FIRST_ROWS} rows") + checked += 1 + refused += "refused" in expected + print(f"{dataset}: checked {len(tables)} tables", flush=True) + if wrong: + raise MigrationError("not equal:\n " + "\n ".join(wrong)) + print( + f"verified: {checked} tables; schemas equal, and the source ids, content hashes and " + f"pipeline hashes of {checked - refused} sources ({refused} tables have none, " + "before and after). Table ids, versions and the completion marker are the plan's, " + f"and so are the first {FIRST_ROWS} rows of each table. Rows beyond them were not " + "read." + ) + + +def main() -> int: + """Run one step.""" + parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n")[0]) + steps = parser.add_subparsers(dest="step", required=True) + for name, run in (("dry-run", dry_run), ("write", write), ("verify", verify)): + step = steps.add_parser(name, help=run.__doc__) + step.add_argument("--project", required=True) + step.add_argument("--dataset", action="append", required=True) + step.add_argument("--plan", default="spiral-migration-plan.json") + step.set_defaults(run=run) + if name == "write": + step.add_argument("--digest", required=True) + step.add_argument( + "--adopt", + help="the id of an empty schema table that an earlier, stopped run of " + "this plan created", + ) + step.add_argument("--stop-after", type=int, help=argparse.SUPPRESS) + args = parser.parse_args() + try: + require_credentials() + args.run(args) + except (MigrationError, ValueError, ImportError) as exc: + # ValueError: what Orcapod refuses, a damaged schema table among it. + print("STOPPED:", exc, file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index a139dc2f4..5dd3d41a1 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -6,9 +6,8 @@ primary-key (key-schema) columns are the tag columns by default. Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``. -Authentication is handled externally — run ``spiral login`` once; pyspiral keeps -the credentials in its per-user application directory -(``~/Library/Application Support/pyspiral/`` on macOS, ``~/.config/pyspiral/`` on Linux). +Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials +``spiral login`` saved. The SDK client is reused for reads and freshness checks, including on restricted copies. Use a new source after changing the SDK endpoint, credentials or options. Use the source as a context manager or call ``close()`` after its reads and jobs have finished. @@ -42,7 +41,9 @@ import asyncio import copy import dataclasses +import os from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping +from concurrent.futures import ThreadPoolExecutor from threading import Lock from types import TracebackType from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING @@ -67,6 +68,7 @@ SpiralDBConnector, SpiralDBTable, SpiralDBTableNotFoundError, + require_same_process, ) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError from orcapod.types import ColumnConfig, Condition @@ -97,16 +99,18 @@ class _Head(NamedTuple): rows: The rows read; zero rows (the source's columns) when ``rows_read`` is false. rows_read: Whether rows were read at all. - total_rows: The rows the source reads or, as an estimate, the table's recorded - row count. - total_is_estimate: Whether ``total_rows`` is the recorded row count rather than - an exact count. + total_rows: The rows the source reads or, as an estimate, the table's row count; + ``None`` when it is above the bound that was counted. + total_is_estimate: Whether ``total_rows`` is the table's row count rather than + that of the rows the source reads. + counted_to: With no ``total_rows``, the rows the table has at least. """ rows: "pa.Table" rows_read: bool - total_rows: int + total_rows: int | None total_is_estimate: bool + counted_to: int = 0 def _schema_difference(found: "pa.Schema", expected: "pa.Schema") -> str: @@ -194,7 +198,7 @@ class SpiralDBTableSource(RootSource): """A read-only Source over a table in a SpiralDB dataset, read in batches. Building the source reads the table's metadata only: that the table exists, its - key columns, its schema (with the table's nullability record applied) and + key columns, its schema (with the table's row in the dataset's schema table applied) and SpiralDB's own id of the table. No row is read. ``output_schema``, ``keys``, ``content_hash``, ``pipeline_hash`` and ``to_config`` never read a row either. @@ -263,8 +267,8 @@ class SpiralDBTableSource(RootSource): label: Human-readable label for this source node. data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. - overrides: Optional pyspiral client config overrides passed through to - ``SpiralDBConnector``, e.g. ``{"server.url": "https://api.spiraldb.dev"}``. + overrides: Optional: ``{"server.url": "https://api.spiraldb.dev"}``, the + address of the service, passed to ``SpiralDBConnector``. 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). @@ -345,6 +349,7 @@ def __init__( self._overrides = None if overrides is None else dict(overrides) self._connection: SpiralDBConnector | None = None self._connection_lock = Lock() + self._pid = os.getpid() self._closed = False self._condition = Condition() self._limit = limit @@ -587,6 +592,7 @@ def _copy(self) -> "SpiralDBTableSource": The modified time is carried over until ``_apply_restriction`` moves it. A SpiralDB source holds no rows it read. """ + require_same_process(self._pid) # before a lock inherited by a fork with self._connection_lock: connection = self._connection if connection is None: @@ -686,6 +692,7 @@ def identity_structure(self) -> Any: def _connector(self) -> SpiralDBConnector: """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") @@ -699,6 +706,7 @@ def _connector(self) -> SpiralDBConnector: def close(self) -> None: """Release this source's reference to the SDK client after its reads finish.""" + require_same_process(self._pid) # before a lock inherited by a fork with self._connection_lock: self._closed = True if self._connection is not None: @@ -737,12 +745,12 @@ def _lookup_table(self) -> SpiralDBTable: @property def row_count_estimate(self) -> int: - """The whole table's row count as SpiralDB's manifests record it. + """The whole table's row count, exact: every key is read to count it. The count is of the version this source reads (the one it was built at, or - the given ``asof``). No row is read. ``where`` and ``limit`` are not taken into - account, and the count can be above what a scan returns when rows were - deleted or overwritten and not yet compacted. + the given ``asof``), and is remembered while the source is open. ``where`` and + ``limit`` are not taken into account. SpiralDB offers no recorded count, so the + cost grows with the table. """ asof = self._asof return self._lookup_table().row_count_estimate(asof=asof) @@ -862,16 +870,13 @@ def _read_batches( and (limit is None or limit > max_rows) ): # Nothing but limit bounds the read, and the limit does not keep it - # under the cap: the table's recorded row count decides, before any - # row is read (so no row reaches a function of a job that would fail). - # The count can be above the rows a scan returns, never below. - recorded = table.row_count_estimate(asof=asof) - bound = recorded if limit is None else min(limit, recorded) - if bound > max_rows: + # under the cap: the table's row count decides, before any row is + # handed on (so no row reaches a function of a job that would fail). + # Counting stops one past the cap. + if table.count_rows(asof=asof, at_most=max_rows + 1) > max_rows: + bound = "" if limit is None else f" (limit={limit:,})" raise self._too_large( - f"the read may return up to {bound:,} rows: the table records " - f"about {recorded:,} rows (SpiralDB's count, which can include " - "deleted rows not yet compacted)" + f"the table has more than {max_rows:,} rows{bound}" ) seen = 0 # Keys must be unique across the whole read, not only within a slice. @@ -926,22 +931,24 @@ def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: async def async_iter_data( self, ) -> AsyncIterator["tuple[TagProtocol, DataProtocol]"]: - """Yield the table's ``(tag, data)`` pairs, reading each batch off the event loop.""" + """Yield the table's ``(tag, data)`` pairs, reading each batch off the event loop. + + One thread owns the reader for its whole life. When the consumer stops or is + cancelled, that thread closes it, after a read in progress has ended. + """ streams = self._batch_streams() + owner = ThreadPoolExecutor(max_workers=1, thread_name_prefix="spiraldb-read") + loop = asyncio.get_running_loop() try: while True: - stream = await asyncio.to_thread(next, streams, None) + stream = await loop.run_in_executor(owner, next, streams, None) if stream is None: break for pair in stream.iter_data(): yield pair finally: - try: - streams.close() - except ValueError: - # Cancelled while a batch was being read in the worker thread: the - # scan cannot be closed from here and ends with that read. - pass + _ = owner.submit(streams.close) + owner.shutdown(wait=False) def as_table( self, @@ -988,7 +995,8 @@ def _head( At most ``n`` rows are read (fewer when the source's ``limit`` is smaller), with ``where`` and the pinned version applied and ``max_rows`` not, so a table of any size can be looked at. When these are not all the rows the source reads, the - size is the table's recorded row count (no scan), an estimate. + size is the table's row count, counted from its keys up to ``max_rows`` (at most + 100,000) rows; above that it is unknown. Args: n: The most rows to read. @@ -997,7 +1005,8 @@ def _head( """ if not self._preview_reads_rows: schema_only = self._stream.as_table(columns=columns, all_info=all_info) - return _Head(schema_only, False, self.row_count_estimate, True) + bound, total = self._bounded_count(PREVIEW_ROWS) + return _Head(schema_only, False, total, True, bound) limit = self._limit head_limit = n if limit is None else min(n, limit) asof = self._asof @@ -1009,10 +1018,32 @@ def _head( ) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) - recorded = table.row_count_estimate(asof=asof) + bound, total = self._bounded_count(n, table) if limit is not None and not self._condition: - recorded = min(limit, recorded) - return _Head(rows, True, recorded, True) + total = limit if total is None and limit <= bound else total + total = None if total is None else min(limit, total) + return _Head(rows, True, total, True, bound) + + def _bounded_count( + self, shown: int, table: SpiralDBTable | None = None + ) -> tuple[int, int | None]: + """Return how far the table's rows were counted for a preview, and their number, + or ``None`` when there are more. + + A preview counts at most ``DEFAULT_MAX_ROWS`` keys: never every key of a table of + any size. One that shows more rows than that counts none. + + Args: + shown: The rows the preview shows. + table: The handle resolved for this read; looked up when not given. + """ + if shown > DEFAULT_MAX_ROWS: + return shown, None + allowed = min(self._max_rows or DEFAULT_MAX_ROWS, DEFAULT_MAX_ROWS) + bound = max(allowed, shown) + handle = self._lookup_table() if table is None else table + total = handle.count_rows(asof=self._asof, at_most=bound + 1) + return bound, (None if total > bound else total) def _head_note(self, head: "_Head", sorted_by_tags: bool = False) -> str: """Return the words a notebook display puts after the header: the one place. @@ -1021,8 +1052,17 @@ def _head_note(self, head: "_Head", sorted_by_tags: bool = False) -> str: rows of the table in tag order, and the words say so. """ shown = head.rows.num_rows + total = ( + ( + f"at least {head.counted_to:,}" + if head.counted_to > DEFAULT_MAX_ROWS + else f"more than {head.counted_to:,}" + ) + if head.total_rows is None + else f"about {head.total_rows:,}" + ) if not head.rows_read: - return f"rows not read; the table has about {head.total_rows:,} rows" + return f"rows not read; the table has {total} rows" if not head.total_is_estimate: all_rows = f"all {shown:,} row{'' if shown == 1 else 's'}" return f"{all_rows}, sorted by tags" if sorted_by_tags else all_rows @@ -1033,13 +1073,10 @@ def _head_note(self, head: "_Head", sorted_by_tags: bool = False) -> str: if sorted_by_tags else f"first {shown:,} matching rows" ) - return ( - f"{read} (where {condition}); the table has " - f"about {head.total_rows:,} rows" - ) + return f"{read} (where {condition}); the table has {total} rows" if sorted_by_tags: - return f"{shown:,} rows read, sorted by tags, of about {head.total_rows:,}" - return f"first {shown:,} rows of about {head.total_rows:,}" + return f"{shown:,} rows read, sorted by tags, of {total}" + return f"first {shown:,} rows of {total}" def head( self, @@ -1053,7 +1090,8 @@ def head( At most ``n`` rows are read (fewer when the source's ``limit`` is smaller), with ``where`` and the pinned version applied and ``max_rows`` not, so a table of any size can be looked at. The total is exact when these are all the rows the - source reads, else the table's recorded row count (an estimate). The notebook + source reads, else the table's row count (an estimate of what is read), unknown + above the bound that is counted. The notebook preview is this head. See ``StreamBase.head``. """ check_head_size(n) diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index 3894cb5a0..ce7cfbdb2 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -5,7 +5,6 @@ from .noop_database import NoOpArrowDatabase from .postgresql_connector import PostgreSQLConnector from .spiraldb_connector import SpiralDBConnector -from .spiraldb_nullability import read_nullability_record, write_nullability_record from .sqlite_connector import SQLiteConnector __all__ = [ @@ -17,8 +16,6 @@ "SpiralDBConnector", "SQLiteConnector", "PostgreSQLConnector", - "read_nullability_record", - "write_nullability_record", ] # Relational DB connector implementations satisfy DBConnectorProtocol diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index be80d8919..768c698a6 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1,53 +1,60 @@ -"""SpiralDBConnector — DBConnectorProtocol implementation backed by SpiralDB (pyspiral). +"""SpiralDBConnector — DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``. -Authentication is handled externally via the ``spiral login`` CLI command, -which stores credentials in pyspiral's per-user application directory (``~/Library/Application Support/pyspiral/`` on -macOS, ``~/.config/pyspiral/`` on Linux). +Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials +``spiral login`` saved. The connector is dataset-scoped: all tables are read from and written to -a single ``(project_id, dataset)`` pair. +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``). Example:: connector = SpiralDBConnector(project_id="my-project-123456", dataset="default") - db = ConnectorArrowDatabase(connector) - db.add_record(("results", "my_fn"), record_id="abc", record=table) - db.flush() + rows = pa.Table.from_batches(connector.scan_batches("units")) """ from __future__ import annotations -import base64 import json import logging +import math +import os import re -from collections.abc import Callable, Iterator, Mapping +import urllib.parse +import urllib.request +import warnings +from collections.abc import Iterator, Mapping from contextlib import contextmanager from copy import copy -from typing import TYPE_CHECKING, Any +from threading import RLock +from typing import TYPE_CHECKING, Any, cast import pyarrow as pa +import pyarrow.compute as pc +from typing_extensions import override from orcapod.databases.spiraldb_nullability import ( - apply_nullability_record, cast_changed_columns, check_no_nulls, - enforce_nullability_record, - read_nullability_record, - remove_nullability_record, - render_path, schema_paths, - write_nullability_record, ) +from orcapod.databases.spiraldb_schema_table import ( + SCHEMA_TABLE, + SchemaTable, + compared_columns, + describe_difference, +) +from orcapod.databases.spiraldb_sign_in import require_sign_in from orcapod.errors import ( - NullabilityRecordError, - NullabilityRecordMismatchError, NullInNonNullableColumnError, - UnsupportedValueError, + SpiralDBWriteNotSupportedError, + TableSchemaError, + UnrecordedTableSchemaWarning, ) from orcapod.types import ColumnInfo from orcapod.utils import arrow_utils +from orcapod.utils.warning_utils import outside_orcapod_stacklevel if TYPE_CHECKING: import spiral as sp @@ -58,228 +65,17 @@ logger = logging.getLogger(__name__) -_ARROW_METADATA_KEY = "__arrow_metadata__" - - -def _serialize_field_meta_tree(field: pa.Field) -> dict | None: - """Recursively build the metadata tree for a single ``pa.Field``. - - Walks the field's type tree, collecting ``field.metadata`` at each level. - Covers struct inner fields, list/large_list/fixed_size_list value fields. - Map key/item fields are not recursed (``pa.map_`` constructor does not - accept field-level metadata on key/item). - - Args: - field: The ``pa.Field`` to serialize. - - Returns: - A dict with optional ``"meta"`` (base64-encoded k/v pairs) and - ``"children"`` (recursive trees for composite type children) keys, - or ``None`` if this field and all its descendants have no metadata. - """ - import pyarrow as _pa # noqa: PLC0415 - - node: dict = {} - - if field.metadata: - node["meta"] = { - base64.b64encode(k).decode(): base64.b64encode(v).decode() - for k, v in field.metadata.items() - } - - ftype = field.type - child_fields: list = [] - if _pa.types.is_struct(ftype): - child_fields = [ftype.field(i) for i in range(ftype.num_fields)] - elif ( - _pa.types.is_fixed_size_list(ftype) - or _pa.types.is_list(ftype) - or _pa.types.is_large_list(ftype) - ): - child_fields = [ftype.value_field] - - if child_fields: - children: dict = {} - for child in child_fields: - child_tree = _serialize_field_meta_tree(child) - if child_tree is not None: - children[child.name] = child_tree - if children: - node["children"] = children - - return node if node else None - - -def _serialize_arrow_metadata(table: pa.Table) -> dict[str, bytes] | None: - """Encode all Arrow metadata from ``table`` into a single SpiralDB KV entry. - - Serializes both schema-level (``table.schema.metadata``) and per-field - metadata (including nested struct/list field metadata) into a single JSON - blob stored under ``_ARROW_METADATA_KEY``. - - Args: - table: The Arrow table whose metadata to encode. - - Returns: - ``{"__arrow_metadata__": blob_bytes}`` if any metadata exists anywhere - in the schema, or ``None`` if the schema and all fields (at every depth) - have no metadata. - """ - blob: dict = {} - - if table.schema.metadata: - blob["schema"] = { - base64.b64encode(k).decode(): base64.b64encode(v).decode() - for k, v in table.schema.metadata.items() - } - - field_trees: dict = {} - for field in table.schema: - tree = _serialize_field_meta_tree(field) - if tree is not None: - field_trees[field.name] = tree - if field_trees: - blob["fields"] = field_trees - - if not blob: - return None - - return {_ARROW_METADATA_KEY: json.dumps(blob).encode("utf-8")} - - -def _load_arrow_metadata( - kv: dict[str, bytes], -) -> tuple[dict[bytes, bytes] | None, dict[str, dict]]: - """Decode Arrow metadata from a SpiralDB table KV store. - - Parses the JSON blob stored under ``_ARROW_METADATA_KEY`` and returns - the schema-level metadata and per-field metadata trees for the caller - to apply to a reconstructed Arrow schema. - - Args: - kv: The dict returned by ``tbl.get_metadata()`` on a SpiralDB table - handle. May be empty or lack the ``_ARROW_METADATA_KEY`` key. - - Returns: - A 2-tuple ``(schema_meta, field_trees)`` where: - - ``schema_meta`` is a ``dict[bytes, bytes]`` of schema-level metadata - (base64-decoded), or ``None`` if no schema metadata was stored. - - ``field_trees`` is a ``dict[str, dict]`` mapping top-level column - name to its raw metadata tree dict (as stored in the blob), or - ``{}`` if no field metadata was stored. - """ - if _ARROW_METADATA_KEY not in kv: - return (None, {}) - - try: - blob = json.loads(kv[_ARROW_METADATA_KEY].decode("utf-8")) - except (json.JSONDecodeError, UnicodeDecodeError) as exc: - logger.warning( - "Ignoring malformed Arrow metadata in SpiralDB KV store " - "(%s: %s); table will be read without metadata restoration.", - type(exc).__name__, - exc, - ) - return (None, {}) - - schema_meta: dict[bytes, bytes] | None = None - if "schema" in blob: - schema_meta = { - base64.b64decode(k): base64.b64decode(v) for k, v in blob["schema"].items() - } - - field_trees: dict[str, dict] = blob.get("fields", {}) - - return (schema_meta, field_trees) - - -def _restore_field(field: pa.Field, stored: dict | None) -> tuple[pa.Field, bool]: - """Recursively restore a field's metadata and rebuild its nested type. - - Walks the stored metadata tree in parallel with the field's type tree, - reattaching ``field.metadata`` at every level and reconstructing composite - types bottom-up when any descendant has metadata to restore. - - Handles: struct inner fields, list/large_list/fixed_size_list value fields. - Map key/item fields are not recursed (consistent with serialization). - - Args: - field: The ``pa.Field`` from the Arrow schema returned by SpiralDB. - stored: The metadata tree dict for this field (as stored in the blob), - or ``None`` if no metadata was stored for this field. - - Returns: - A 2-tuple ``(restored_field, changed)`` where: - - ``restored_field`` is the field with metadata restored (new object - if any change was made, original object if not). - - ``changed`` is True if any metadata or nested type was modified. - """ - import pyarrow as _pa # noqa: PLC0415 - - if stored is None or stored == {}: - return (field, False) - - # Decode own metadata from stored tree if present - new_meta: dict[bytes, bytes] | None = None - has_new_meta = False - if "meta" in stored: - new_meta = { - base64.b64decode(k): base64.b64decode(v) for k, v in stored["meta"].items() - } - has_new_meta = True - else: - new_meta = field.metadata - - ftype = field.type - children = stored.get("children", {}) - type_changed = False - new_type = ftype - - if _pa.types.is_struct(ftype): - restored_children = [] - any_child_changed = False - for i in range(ftype.num_fields): - child = ftype.field(i) - child_stored = children.get(child.name) - restored_child, child_changed = _restore_field(child, child_stored) - restored_children.append(restored_child) - if child_changed: - any_child_changed = True - if any_child_changed: - new_type = _pa.struct(restored_children) - type_changed = True - elif _pa.types.is_fixed_size_list(ftype): - value_field = ftype.value_field - child_stored = children.get(value_field.name) - restored_vf, child_changed = _restore_field(value_field, child_stored) - if child_changed: - new_type = _pa.list_(restored_vf, ftype.list_size) - type_changed = True - elif _pa.types.is_list(ftype): - value_field = ftype.value_field - child_stored = children.get(value_field.name) - restored_vf, child_changed = _restore_field(value_field, child_stored) - if child_changed: - new_type = _pa.list_(restored_vf) - type_changed = True - elif _pa.types.is_large_list(ftype): - value_field = ftype.value_field - child_stored = children.get(value_field.name) - restored_vf, child_changed = _restore_field(value_field, child_stored) - if child_changed: - new_type = _pa.large_list(restored_vf) - type_changed = True - - meta_changed = has_new_meta and new_meta != field.metadata - changed = meta_changed or type_changed - - if not changed: - return (field, False) - - if type_changed: - return (_pa.field(field.name, new_type, field.nullable, new_meta), True) - else: - return (field.with_metadata(new_meta), True) +# The largest batch a scan hands out. SpiralDB's default is 1,024 rows. +_SCAN_BATCH_ROWS = 8_192 +_LIST_TIMEOUT_S = 60 +_NO_WRITES = ( + "Orcapod does not write SpiralDB tables through spiral-sdk yet; it reads them. Writing " + "is a follow-up of ITL-1186. Nothing was written. Store a job's results in another " + "database, for example DeltaTableDatabase." +) +# Tables a warning was issued for in this process (``UnrecordedTableSchemaWarning``). +_warned_unrecorded: set[tuple[str, str]] = set() +_warned_lock = RLock() # a warning hook may read a table itself # --------------------------------------------------------------------------- @@ -311,63 +107,19 @@ def _parse_table_name(query: str) -> str: return m.group(1) -def _null_struct_path(data: pa.Table) -> str | None: - """Return the path of the first struct (at any depth) holding a struct-level null. - - SpiralDB cannot store a null struct: pyspiral refuses one unless written with - ``push_down_nulls=True``, which turns it into a struct of null fields (live, ITL-936). - - Args: - data: The rows to be written. - - Returns: - The path (``g``, ``outer.inner``, ``items[]``), or ``None`` if there is none. - """ - import pyarrow as _pa # noqa: PLC0415 - - def walk(arrays: list[Any], t: pa.DataType, path: str) -> str | None: - arrays = [a.storage if isinstance(a, _pa.ExtensionArray) else a for a in arrays] - if isinstance(t, _pa.ExtensionType): - t = t.storage_type - if _pa.types.is_struct(t): - if any(a.null_count for a in arrays): - return path - for i in range(t.num_fields): - child = t.field(i) - found = walk( - [a.field(i) for a in arrays], child.type, f"{path}.{child.name}" - ) - if found is not None: - return found - elif ( - _pa.types.is_list(t) - or _pa.types.is_large_list(t) - or _pa.types.is_fixed_size_list(t) - ): - return walk([a.flatten() for a in arrays], t.value_type, f"{path}[]") - return None - - for name in data.column_names: - column = data.column(name) - found = walk(list(column.chunks), column.type, name) - if found is not None: - return found - return None - - @contextmanager def _about_table(table: str) -> Iterator[None]: - """Re-raise a nullability error that does not name its table with ``table`` added. + """Re-raise a schema or null error that does not name its table with ``table`` added. Args: table: The table, as ``"//

"``. """ try: yield - except NullabilityRecordError as exc: + except TableSchemaError as exc: if exc.table is not None: raise - raise NullabilityRecordError(exc.reason, table=table) from exc + raise TableSchemaError(exc.reason, table=table) from exc except NullInNonNullableColumnError as exc: if exc.table is not None: raise @@ -379,129 +131,326 @@ def _about_table(table: str) -> Iterator[None]: # --------------------------------------------------------------------------- -def _holds_zone_aware_timestamp(arrow_type: pa.DataType) -> bool: - """Whether ``arrow_type`` is or nests a timestamp with a time zone (ITL-1162). +class SpiralDBTableNotFoundError(ValueError): + """An exact table lookup found no matching table.""" + + +@contextmanager +def _service_call(doing: str) -> Iterator[None]: + """Note on a failing SDK call what Orcapod was doing: SpiralDB's errors often hold a + status only. Args: - arrow_type: The column's Arrow type. + doing: What the call does, and to what. + """ + try: + yield + except Exception as exc: + # The SDK's own error class is not named here: it may not be installed. + if not isinstance(exc, (TableSchemaError, NullInNonNullableColumnError)): + exc.add_note(f"SpiralDB: could not {doing}") + raise - Returns: - ``True`` for a zone-aware timestamp at any depth of lists, structs and maps. + +def _open_keyed_table( + client: Any, project_id: str, dataset: str, name: str +) -> Any | None: + """Return the latest snapshot of a keyed table, or ``None`` if there is none. + + SpiralDB has no error class for a missing table. Only its exact message for this + name means "no such table"; a missing project, a refused sign-in or a transport + failure has another and is raised. """ - if pa.types.is_timestamp(arrow_type): - return arrow_type.tz is not None - if isinstance(arrow_type, pa.ExtensionType): - return _holds_zone_aware_timestamp(arrow_type.storage_type) - return any( - _holds_zone_aware_timestamp(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) - ) + with _service_call(f"open table {project_id}/{dataset}/{name}"): + try: + return client.keyed_table(project_id, dataset, name) + except sp.SpiralError as exc: + if str(exc).strip() != f"resource not found: {project_id}.{dataset}.{name}": + raise + return None -def _holds_extension_type(arrow_type: pa.DataType) -> bool: - """Whether ``arrow_type`` is or nests an extension (logical) type (ITL-1334). +def _warn_unrecorded(table: str, table_id: str) -> None: + """Warn once per table and process that its schema is not recorded. Args: - arrow_type: The column's Arrow type. - - Returns: - ``True`` for an extension type at any depth of lists, structs and maps. + table: The table, as ``"//
"``. + table_id: SpiralDB's id of it. """ - # BaseExtensionType: Python-defined types and Arrow's canonical ones (uuid, json). - if isinstance(arrow_type, pa.BaseExtensionType): - return True - return any( - _holds_extension_type(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) + _warn_once( + (table, table_id), + f"SpiralDB table {table} has no row in its dataset's {SCHEMA_TABLE}: every column " + "is read as nullable and without Arrow metadata. If an Orcapod release on " + "pyspiral wrote it, migrate the dataset with scripts/migrate_spiral_schemas.py " + "(its schema and hashes differ until then).", ) -def _holds_map_field_metadata(arrow_type: pa.DataType) -> bool: - """Whether ``arrow_type`` is or nests a map with field metadata at any depth below - it: on its key or item field, or on a field inside them. +def _warn_once(about: tuple[str, str], message: str) -> None: + """Issue an ``UnrecordedTableSchemaWarning`` once per ``about`` and process. + + Args: + about: What the warning is about. + message: The warning. + """ + # Held over the check, the warning and the record: while one thread's warning is + # turned into an error, another does not pass as if it had been shown. + with _warned_lock: + if about in _warned_unrecorded: + return + warnings.warn( + message, + UnrecordedTableSchemaWarning, + stacklevel=outside_orcapod_stacklevel(), + ) + _warned_unrecorded.add(about) - The connector's metadata record (``_serialize_field_meta_tree``) does not descend - into a map, so such metadata would read back dropped (ITL-1334). + +# --------------------------------------------------------------------------- +# The client +# --------------------------------------------------------------------------- + + +def require_same_process(pid: int) -> None: + """Refuse a SpiralDB client made in another process: after a fork a call of it hangs, + and a lock another thread held stays locked. Args: - arrow_type: The column's Arrow type. + pid: The process that made the client. - Returns: - ``True`` for such a map at any depth of lists, structs and maps. + Raises: + RuntimeError: If this is another process. """ - if pa.types.is_map(arrow_type): - return any( - field.metadata or _holds_nested_field_metadata(field.type) - for field in (arrow_type.key_field, arrow_type.item_field) + if pid != os.getpid(): + raise RuntimeError( + "this SpiralDB client was made in another process, and cannot be used after " + "a fork. Make a new one in a process started with 'spawn'" ) - return any( - _holds_map_field_metadata(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) - ) -def _holds_nested_field_metadata(arrow_type: pa.DataType) -> bool: - """Whether a field nested in ``arrow_type``, at any depth, has metadata.""" - return any( - arrow_type.field(i).metadata - or _holds_nested_field_metadata(arrow_type.field(i).type) - for i in range(arrow_type.num_fields) +def _api_url(overrides: Mapping[str, str] | None) -> str | None: + """Return the service address that saved ``overrides`` name, if any. + + Args: + overrides: ``None``, or a mapping with the one key ``server.url``. + + Raises: + ValueError: For any other key: spiral-sdk has no such option, and ignoring it + could read another service than the one named. + """ + options = dict(overrides or {}) + api_url = options.pop("server.url", None) + if options: + raise ValueError( + f"SpiralDB overrides {sorted(options)} are not options of spiral-sdk; the " + "only override is 'server.url'" + ) + return api_url + + +def _new_client(overrides: Mapping[str, str] | None) -> Any: + """Return a spiral-sdk client. + + Raises: + SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. + ImportError: If spiral-sdk is not installed, or another package provides the + ``spiral`` module (``pyspiral``, which must not be installed beside it). + """ + api_url = _api_url(overrides) + try: + client_class = sp.Client + except AttributeError as exc: + raise ImportError( + "the installed 'spiral' module is not spiral-sdk (pyspiral has the same " + "module name and must not be installed beside it): uninstall both, then " + 'install "orcapod[spiraldb]"' + ) from exc + require_sign_in() + return client_class(api_url=api_url) + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Follows no redirect, so a token is never sent to another address.""" + + @override + def redirect_request( + self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str + ) -> None: + return None + + +def _http_get_json(url: str, token: str | None) -> dict[str, Any]: + """Return the JSON object at ``url``. + + Args: + url: The address. + token: The bearer token; ``None`` sends none. + """ + headers = {"Accept": "application/json", "User-Agent": "orcapod"} + if token is not None: + headers["Authorization"] = f"Bearer {token}" + opener = urllib.request.build_opener(_NoRedirect) + request = urllib.request.Request(url, headers=headers) + with opener.open(request, timeout=_LIST_TIMEOUT_S) as response: + return json.load(response) + + +def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, str]: + """Return a dataset's keyed tables: their names by table id. + + spiral-sdk offers no listing of keyed tables, so this is the documented endpoint + (docs.spiraldb.com, "List Keyed tables"), called with the client's address and + sign-in. These two are not public API of the SDK: the pinned version has them. + + Args: + client: A spiral-sdk client. + project_id: The project. + dataset: The dataset; matched exactly by the service. + """ + native = client._native # no public accessor of the address and sign-in + base = ( + f"{str(native.api_url).rstrip('/')}/api/keyed-tables/projects/" + f"{urllib.parse.quote(project_id, safe='')}/tables" ) + names: dict[str, str] = {} + token: str | None = None + seen: set[str] = set() + while True: + query = {"dataset": dataset} + if token is not None: + query["pageToken"] = token + page = _http_get_json( + f"{base}?{urllib.parse.urlencode(query)}", native.access_token() + ) + # A page can be empty before the last one. + names.update( + (t["id"], t["table"]) for t in page["items"] if t["dataset"] == dataset + ) + following = page.get("nextPageToken") + if following is None: + return names + if not following or following in seen: + raise RuntimeError("SpiralDB's table listing does not advance") + seen.add(following) + token = following -class SpiralDBTableNotFoundError(ValueError): - """An exact table lookup found no matching table.""" +def _literal(value: Any, arrow_type: pa.DataType) -> Any: + """Return ``value`` as a scan literal of exactly ``arrow_type`` (the service refuses + another type), or ``None`` when the SDK has no literal that filters as Orcapod does. + + Args: + value: A condition value checked against the column. + arrow_type: The column's type as SpiralDB stores it. + """ + if pa.types.is_large_string(arrow_type): + arrow_type = pa.string() + elif pa.types.is_large_binary(arrow_type): + arrow_type = pa.binary() + if pa.types.is_float64(arrow_type): + return sp.literal(value, arrow_type) + if pa.types.is_float32(arrow_type) and ( + math.isnan(value) or pa.scalar(value, pa.float32()).as_py() == value + ): + return sp.literal(value, arrow_type) + if pa.types.is_timestamp(arrow_type): + # As a count of the unit: the SDK takes no datetime between two of them. + return sp.literal(pa.scalar(value, type=arrow_type).value, arrow_type) + if ( + pa.types.is_string(arrow_type) + or pa.types.is_binary(arrow_type) + or pa.types.is_boolean(arrow_type) + or pa.types.is_integer(arrow_type) + or pa.types.is_date(arrow_type) + ): + return sp.literal(value, arrow_type) + return None + + +def _equals(array: Any, value: Any) -> Any: + """Return where ``array`` equals ``value``, as SpiralDB compares: floats as 64-bit + numbers, ``0.0`` not equal to ``-0.0`` and NaN equal to NaN; a null is no match. + + Args: + array: The column. + value: A condition value checked against the column. + """ + compute: Any = pc # pyarrow's stubs take no plain Python scalar + if not pa.types.is_floating(array.type): + mask = compute.equal(array, pa.scalar(value, type=array.type)) + return compute.fill_null(mask, False) + doubles = array.cast(pa.float64()) + if math.isnan(value): + return compute.fill_null(compute.is_nan(doubles), False) + mask = compute.equal(doubles, pa.scalar(value, pa.float64())) + if value == 0.0: + negative = compute.less(compute.divide(1.0, doubles), 0.0) + wanted = math.copysign(1.0, value) < 0 + mask = compute.and_(mask, compute.equal(negative, wanted)) + return compute.fill_null(mask, False) class SpiralDBTable: """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). - Every lookup of a table by name is a round trip to SpiralDB, and so is each item of - metadata. A caller that needs several items of one table (a source's id, key, schema - and version when it is built, and each run's check) takes them from one handle - instead of looking the table up for each (ITL-1350). The id and the key columns come - with the lookup; the schema and the version are read when asked, in the caller's - order, from the table the lookup found. The handle reads the table as it was when - looked up: look it up again to see a table dropped and created again since. + 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, + and each run's check) takes them from one handle instead of looking the table up for + each (ITL-1350). The handle is a snapshot: the id, key columns and version come with + the lookup, and the schema and rows are those of that version. Look the table up + again to see a newer version, or a table dropped and created again since. """ def __init__( self, connector: SpiralDBConnector, table: Any, table_name: str ) -> None: - """Wrap the pyspiral ``table`` that ``connector`` looked up as ``table_name``.""" + """Wrap the keyed ``table`` that ``connector`` looked up as ``table_name``.""" self._connector = connector self._table = table self._table_name = table_name + self._readings: dict[str, _Reading] = {} + + def _reading(self, table: Any) -> _Reading: + """Return how a snapshot of this table is read, worked out once per version.""" + self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle + version = str(table.version_id) + if version not in self._readings: + self._readings[version] = self._connector._reading(table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle + return self._readings[version] @property def table_id(self) -> str: """SpiralDB's own id of the table (no round trip).""" - return str(self._table.table_id) + return str(self._table.resource_id) @property def key_columns(self) -> list[str]: """The primary-key column names in declaration order (no round trip).""" - return list(self._table.key_schema.names) + return list(self._table.key_columns) def arrow_schema(self) -> pa.Schema: """The schema of the batches ``scan_batches`` yields (``get_arrow_schema``). Raises: - NullabilityRecordError: If the table's nullability record cannot be read or - names a column the table does not have. + TableSchemaError: If the table's row in the schema table cannot be read, or + disagrees with the table. """ - import pyarrow as _pa # noqa: PLC0415 + return self._reading(self._table).schema + def version(self) -> int: + """The table's version at the lookup (``get_table_version``).""" self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle - declared = self._table.schema().to_arrow() - empty = _pa.RecordBatch.from_pylist([], schema=declared) - preparer = self._connector._batch_preparer(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # the connector's own preparer - return preparer(empty).schema + return int(self._table.version_id) - def version(self) -> int: - """The table's current version (``get_table_version``).""" + def _at(self, asof: int | None) -> Any: + """Return the SDK's handle of this same table at version ``asof``.""" self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle - return int(self._table.last_modified_at()) + if asof is None or str(asof) == str(self._table.version_id): + return self._table + with self._connector._service_call("open a version of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + return self._connector._client.keyed_table_by_id( # pyright: ignore[reportPrivateUsage] # owns the handle + self.table_id, asof=asof + ) def scan_batches( self, @@ -512,42 +461,159 @@ def scan_batches( ) -> Iterator[pa.RecordBatch]: """Yield prepared Arrow batches from this resolved table in key order.""" connector = self._connector - connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle - table = self._table - prepare = connector._batch_preparer(table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle + table = self._at(asof) + reading = self._reading(table) predicate = None + local: dict[str, object] = {} for column, value in (where or {}).items(): - equals = table[column] == value - predicate = equals if predicate is None else predicate & equals - scan = connector._spiral.scan( # pyright: ignore[reportPrivateUsage] # owns the handle - table.select(), where=predicate, limit=limit, asof=asof - ) - for batch in scan.to_record_batches(): - yield prepare(batch) + column_type = reading.found.field(column).type + literal = _literal(value, column_type) + if literal is None and pa.types.is_float32(column_type): + # No float32 is exactly this value. The SDK would round it, so 0.1 would + # match the float32 nearest to it; a comparison of the values does not. + return + if literal is None: + local[column] = value + continue + equals = sp.eq(sp.column(column), literal) + predicate = equals if predicate is None else sp.and_(predicate, equals) + with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + reader = table.scan( + filter=predicate, + # The limit counts rows that match every condition. + limit=None if local else limit, + batch_rows=_SCAN_BATCH_ROWS, + ).to_reader() + left = limit + try: + while left is None or left > 0: + with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + batch = next(reader, None) + if batch is None: + return + batch = reading.prepare(batch) + for column, value in local.items(): + batch = batch.filter(_equals(batch.column(column), value)) + if local and left is not None: + batch = batch.slice(0, left) + left -= batch.num_rows + if batch.num_rows or not local: + yield batch + finally: + reader.close() + + def count_rows(self, *, asof: int | None = None, at_most: int | None = None) -> int: + """Count the table's rows by reading one key column. + + SpiralDB offers no count of a keyed table, so this reads every key, or the first + ``at_most``. A version never changes, so what was counted is remembered by the + connector and those that share its client. - def row_count_estimate(self, asof: int | None = None) -> int: - """Return this resolved table's manifest row count at the requested version.""" + Args: + asof: Count this version; ``None`` for the version of the lookup. + at_most: Stop at this many rows; ``None`` counts them all. + + Returns: + The number of rows, or ``at_most`` when there are at least that many. + """ connector = self._connector - connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle - snapshot = self._table.core.get_snapshot(asof=asof) - stats = connector._spiral.core.manifest_stats(snapshot) # pyright: ignore[reportPrivateUsage] # owns the handle - return int(stats.key_space_stats.total_rows) + table = self._at(asof) + # Refuses what a read would: a schema table that is not complete. + _ = self._reading(table) + counts = connector._counts # pyright: ignore[reportPrivateUsage] # owns the handle + known = (self.table_id, str(table.version_id)) + counted, exact = counts.get(known, (0, False)) + if not exact and (at_most is None or counted < at_most): + with connector._service_call("count the rows of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + reader = table.scan( + [self.key_columns[0]], limit=at_most, batch_rows=_SCAN_BATCH_ROWS + ).to_reader() + try: + counted = sum(batch.num_rows for batch in reader) + finally: + reader.close() + exact = at_most is None or counted < at_most + counts[known] = (counted, exact) + return counted if at_most is None else min(counted, at_most) + + def row_count_estimate(self, asof: int | None = None) -> int: + """Return the table's row count, exact, by reading every key (``count_rows``).""" + return self.count_rows(asof=asof) + + +class _Reading: + """How one snapshot is read: its schema, and each batch's preparation. + + Attributes: + found: The snapshot's schema, as SpiralDB reports it. + schema: The schema it is read with. + """ + + def __init__( + self, found: pa.Schema, recorded: pa.Schema | None, table: str + ) -> None: + """Prepare reading a snapshot. + + Args: + found: The snapshot's schema, as SpiralDB reports it. + recorded: The schema its row records, or ``None``: as SpiralDB reports it. + table: The table, as ``"//
"``. + """ + self.found = found + if recorded is None: + self.schema = pa.schema( + [ + f.with_type( + arrow_utils.normalize_to_large_types(f.type, keep_null=True) + ) + for f in found + ], + metadata=cast("dict[bytes | str, bytes | str] | None", found.metadata), + ) + self._paths = frozenset[tuple[str, ...]]() + else: + self.schema = recorded + self._paths = schema_paths(recorded) + self._table = table + # The batch schema last found to have the snapshot's columns. + self._accepted = found + + def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: + """Return a scanned batch under ``schema``, its non-null columns checked. + + Raises: + TableSchemaError: If the batch's columns are not the snapshot's. + NullInNonNullableColumnError: If a non-nullable column holds a null. + """ + if not batch.schema.equals(self._accepted, check_metadata=True): + # By name, and only a batch with exactly the snapshot's columns. + if sorted(batch.schema.names) == sorted(self.found.names): + batch = batch.select(self.found.names) + if compared_columns(batch.schema) != compared_columns(self.found): + raise TableSchemaError( + "a batch's columns are not those of the version it was read from: " + f"{describe_difference(batch.schema, self.found)}", + table=self._table, + ) + self._accepted = batch.schema + with _about_table(self._table): + check_no_nulls(batch, self._paths) + if batch.schema.equals(self.schema, check_metadata=True): + return batch + return cast_changed_columns(batch, self.schema) class SpiralDBConnector: - """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). + """DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). - Scoped to a single dataset within a SpiralDB project. Auth is handled - externally — run ``spiral login`` once; pyspiral keeps the credentials in its - per-user application directory (``~/Library/Application Support/pyspiral/`` on - macOS, ``~/.config/pyspiral/`` on Linux). + Scoped to a single dataset within a SpiralDB project, and to its keyed tables. Auth + is spiral-sdk's: ``SPIRAL_*`` environment variables, or a saved ``spiral login``. Args: project_id: SpiralDB project identifier (e.g. ``"my-project-123456"``). dataset: Dataset within the project. Defaults to ``"default"``. - overrides: Optional pyspiral client config overrides, e.g. - ``{"server.url": "https://api.spiraldb.dev"}`` for the dev - environment. See the pyspiral config docs for full options. + overrides: Optional: ``{"server.url": "https://api.spiraldb.dev"}``, the address + of the service. Any other key is refused. """ def __init__( @@ -560,40 +626,72 @@ def __init__( self._dataset = dataset self._overrides = overrides self._closed = False - self._spiral = sp.Spiral(overrides=overrides) - self._project = self._spiral.project(project_id) + self._client = _new_client(overrides) + self._pid = os.getpid() + # Shared by every connector on this client (``share_client``). + self._counts: dict[tuple[str, str], tuple[int, bool]] = {} + client = self._client + self._schemas = SchemaTable( + project_id, + dataset, + lambda: _open_keyed_table(client, project_id, dataset, SCHEMA_TABLE), + lambda doing: _service_call(f"{doing} of {project_id}/{dataset}"), + ) def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" if self._closed: raise RuntimeError("SpiralDBConnector is closed") + require_same_process(self._pid) def share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope.""" self._require_open() return copy(self) - def _table_id(self, table_name: str) -> str: - """Return the dataset-qualified table identifier for a plain table name.""" - return f"{self._dataset}.{table_name}" - def _qualified(self, table_name: str) -> str: """Return ``"//
"``, the table as errors name it.""" return f"{self._project_id}/{self._dataset}/{table_name}" + def _service_call(self, doing: str, table_name: str) -> Any: + """Return a context that notes on a failing SDK call what it was doing.""" + return _service_call(f"{doing} {self._qualified(table_name)}") + + def _require_user_table(self, table_name: str) -> None: + """Refuse the reserved name of the dataset's schema table.""" + if table_name == SCHEMA_TABLE: + raise ValueError( + f"{SCHEMA_TABLE!r} is reserved: it is where Orcapod keeps the schemas of " + f"the tables of dataset {self._dataset!r}" + ) + def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. - Filters ``project.list_tables()`` to the connector's dataset. Only the - plain ``.table`` field is returned; the opaque ``.id`` handle is never - exposed. + The dataset's schema table is not one of them. A table it records that the + dataset no longer holds is warned about. + + Raises: + TableSchemaError: If the dataset's schema table is not complete. Returns: Sorted list of plain table name strings (no ``dataset.`` prefix). """ self._require_open() - resources = self._project.list_tables() - return sorted(r.table for r in resources if r.dataset == self._dataset) + with self._service_call("list the tables of", "*"): + listed = _list_keyed_tables(self._client, self._project_id, self._dataset) + with _about_table(f"{self._project_id}/{self._dataset}"): + recorded = ( + (self._schemas.rows() or {}) if SCHEMA_TABLE in listed.values() else {} + ) + gone = sorted(row.table_name for i, row in recorded.items() if i not in listed) + if gone: + _warn_once( + (f"{self._project_id}/{self._dataset}", str(gone)), + f"the {SCHEMA_TABLE} of SpiralDB dataset {self._project_id}/" + f"{self._dataset} records tables that the dataset no longer holds: {gone}", + ) + return sorted(name for name in listed.values() if name != SCHEMA_TABLE) def lookup_table(self, table_name: str) -> SpiralDBTable: """Look the table up once, for several items of its metadata (ITL-1350). @@ -603,29 +701,78 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Returns: The table: its id and key columns, and its schema and version when asked. + + Raises: + SpiralDBTableNotFoundError: If there is no such table. + ValueError: If the name is the schema table's. """ self._require_open() - identifier = self._table_id(table_name) + self._require_user_table(table_name) + missing = f"Table not found: {self._project_id}.{self._dataset}.{table_name}" if ( not self._dataset or not table_name or "." in self._dataset or "." in table_name ): - # The SDK omits empty filters and treats dots as identifier separators. - raise SpiralDBTableNotFoundError( - f"Table not found: {self._project_id}.{identifier}" - ) - try: - table = self._project.table(identifier) - except ValueError as exc: - # pyspiral raises this exact ValueError for an empty name lookup. Preserve - # other failures, including errors in loading the returned table handle. - if str(exc) != f"Table not found: {self._project_id}.{identifier}": - raise - raise SpiralDBTableNotFoundError(str(exc)) from exc + raise SpiralDBTableNotFoundError(missing) + table = _open_keyed_table( + self._client, self._project_id, self._dataset, table_name + ) + if table is None: + raise SpiralDBTableNotFoundError(missing) return SpiralDBTable(self, table, table_name) + def _recorded_schema( + self, table: Any, table_name: str, found: pa.Schema + ) -> pa.Schema | None: + """Return the schema recorded for an opened table; ``None``: as SpiralDB reports. + + Args: + table: The SDK's handle. + table_name: Plain table name. + found: The handle's schema, as SpiralDB reports it. + + Raises: + TableSchemaError: If the dataset's schema table cannot be read or is not + complete, or the table's row disagrees with the table. + """ + row = self._schemas.row(str(table.resource_id)) + if row is None: + _warn_unrecorded(self._qualified(table_name), str(table.resource_id)) + return None + if row.table_name != table_name: + raise TableSchemaError( + f"its row in {SCHEMA_TABLE} is of table {row.table_name!r}, which has " + "this id: the table was renamed since it was recorded" + ) + if row.key_columns != tuple(table.key_columns): + raise TableSchemaError( + f"its row in {SCHEMA_TABLE} has key columns {list(row.key_columns)}, " + f"but the table has {list(table.key_columns)}" + ) + if compared_columns(row.schema) != compared_columns(found): + raise TableSchemaError( + f"the columns of version {table.version_id} are not those of the table's " + f"row in {SCHEMA_TABLE}: " + f"{describe_difference(found, row.schema)}" + ) + return row.schema + + def _reading(self, table: Any, table_name: str) -> _Reading: + """Return how an opened snapshot of ``table_name`` is read. + + Raises: + TableSchemaError: If the table's row cannot be read or disagrees with it. + """ + self._require_open() + qualified = self._qualified(table_name) + with self._service_call("read the schema of", table_name): + found = table.schema() + with _about_table(qualified): + recorded = self._recorded_schema(table, table_name, found) + return _Reading(found, recorded, qualified) + def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in declaration order. @@ -633,58 +780,37 @@ def get_pk_columns(self, table_name: str) -> list[str]: table_name: Plain table name (no dataset prefix). Returns: - List of PK column names; empty list if the table has no key schema. + List of PK column names. """ return self.lookup_table(table_name).key_columns def get_column_info(self, table_name: str) -> list[ColumnInfo]: """Return column metadata with Arrow types. - SpiralDB is Arrow-native; types are taken directly from the table's - Arrow schema and normalized to their large variants at every nesting - level (``arrow_utils.normalize_to_large_types``: ``string`` to - ``large_string``, ``binary`` to ``large_binary``, ``list`` to - ``large_list``). SpiralDB hands back ``string`` / ``binary`` whatever - layout was written, so this gives the same types as ``iter_batches`` - and as the other connectors. Only layouts change: widths, nullability - and nested field names are kept, and hashes are unaffected. + SpiralDB is Arrow-native; types are the table's own, normalized to their large + variants at every nesting level (``arrow_utils.normalize_to_large_types``), the + same types ``iter_batches`` gives. Only layouts change: widths and nested field + names are kept, and hashes are unaffected. - Note: SpiralDB also silently drops timezone information from timestamp - columns at storage time — ``timestamp[us, tz=UTC]`` is returned as - ``timestamp[us]``. - - SpiralDB reports every top-level column and every struct field nullable. When - the table carries a nullability record (``write_nullability_record``, written by - ``upsert_records`` on a table's first write), the recorded columns and nested - fields are reported non-nullable; without one, nullability is SpiralDB's. + SpiralDB reports every top-level column and every struct field nullable. The + columns and nested fields that the table's row in the dataset's schema table + records as non-nullable (written by ``scripts/migrate_spiral_schemas.py``) + are reported so; without a row, nullability is SpiralDB's, with a warning + (``UnrecordedTableSchemaWarning``). Args: table_name: Plain table name (no dataset prefix). Returns: - List of ColumnInfo objects. Propagates pyspiral exception if the - table does not exist (no empty-list fallback). + List of ColumnInfo objects. Raises: - NullabilityRecordError: If the table's nullability record cannot be read or - names a column the table does not have. + SpiralDBTableNotFoundError: If the table does not exist. + TableSchemaError: If the table's row cannot be read or disagrees with it. """ - self._require_open() - tbl = self._project.table(self._table_id(table_name)) - arrow_schema = tbl.schema().to_arrow() - with _about_table(self._qualified(table_name)): - paths = read_nullability_record(tbl.get_metadata()) - if paths is not None: - arrow_schema = apply_nullability_record(arrow_schema, paths) return [ - ColumnInfo( - name=field.name, - arrow_type=arrow_utils.normalize_to_large_types( - field.type, keep_null=True - ), - nullable=field.nullable, - ) - for field in arrow_schema + ColumnInfo(name=f.name, arrow_type=f.type, nullable=f.nullable) + for f in self.lookup_table(table_name).arrow_schema() ] def iter_batches( @@ -695,41 +821,26 @@ def iter_batches( ) -> Iterator[pa.RecordBatch]: """Execute a full-table scan and yield results as Arrow RecordBatches. - SpiralDB has no SQL engine. The table name is parsed from the query's - FROM clause (double-quoted or unquoted). Only ``SELECT * FROM "table"`` - patterns are supported; WHERE clauses and projections are silently ignored. - - The query must use a plain (non-qualified) table name — not - ``"dataset.table"``. Passing a qualified name would cause a pyspiral - lookup failure. + The table name is parsed from the query's FROM clause (double-quoted or + unquoted). Only ``SELECT * FROM "table"`` patterns are supported; WHERE clauses + and projections are silently ignored. The query must use a plain + (non-qualified) table name — not ``"dataset.table"``. Args: query: SQL-style query. Must contain ``FROM "table_name"``. - params: Accepted for protocol compliance. SpiralDB has no parameterised - interface — if not ``None``, a warning is logged and params are - not used. - batch_size: Accepted for protocol compliance. SpiralDB does not - support caller-controlled batch sizing — the Spiral execution - engine determines batch sizes. A warning is logged if a - non-default value is passed. + params: Accepted for protocol compliance. If not ``None``, a warning is + logged and params are not used. + batch_size: Accepted for protocol compliance: SpiralDB determines batch + sizes. A warning is logged if a non-default value is passed. Yields: - Arrow RecordBatch objects. Each batch has: - - Every column's type normalized to its large variants at every - nesting level (``arrow_utils.normalize_to_large_types``), the same - types ``get_column_info`` reports. - - Field metadata (including nested struct/list field metadata) - restored from the SpiralDB native KV store, if any was written - by ``upsert_records``. - - Schema-level metadata restored from the KV store. - - The nullability ``get_column_info`` reports: when the table carries a - nullability record, every batch is checked and its recorded columns are - non-nullable. Tables without a record pay no per-batch check. - Yields nothing for an empty table. + Arrow RecordBatch objects. Each batch has the schema + ``get_arrow_schema`` gives: types in their large variants, and the metadata + and nullability the table's row in the schema table records. Yields nothing + for an empty table. Raises: - NullabilityRecordError: If the table's nullability record cannot be read or - names a column the table does not have. + TableSchemaError: If the table's row cannot be read or disagrees with it. NullInNonNullableColumnError: If a batch holds a null in a recorded non-nullable column (naming the table and the column). """ @@ -749,68 +860,6 @@ def iter_batches( ) yield from self.scan_batches(_parse_table_name(query)) - def _batch_preparer( - self, tbl: Any, table_name: str - ) -> Callable[[pa.RecordBatch], pa.RecordBatch]: - """Return the function that gives a scanned batch the types Orcapod reports. - - The function restores field and schema metadata from the table's key-value - store, normalizes every type to its large variants and applies the table's - nullability record, exactly as ``iter_batches`` documents. - - Args: - tbl: The pyspiral table. - table_name: Plain table name (no dataset prefix). - - Returns: - A function from a scanned batch to the prepared batch. - - Raises: - NullabilityRecordError: If the table's nullability record cannot be read. - """ - import pyarrow as _pa # noqa: PLC0415 - - kv = tbl.get_metadata() - schema_meta, field_trees = _load_arrow_metadata(kv) - qualified = self._qualified(table_name) - with _about_table(qualified): - paths = read_nullability_record(kv) - - def prepare(batch: pa.RecordBatch) -> pa.RecordBatch: - schema = batch.schema - new_fields = [] - needs_rebuild = False - for field in schema: - # Recursively restore field metadata (including nested struct/list). - restored_field, field_changed = _restore_field( - field, field_trees.get(field.name) - ) - # Normalize to the large variants at every depth (layout only). - normalized_type = arrow_utils.normalize_to_large_types( - restored_field.type, keep_null=True - ) - if normalized_type != restored_field.type: - restored_field = restored_field.with_type(normalized_type) - field_changed = True - new_fields.append(restored_field) - needs_rebuild = needs_rebuild or field_changed - - restored_schema_meta = ( - schema_meta if schema_meta is not None else schema.metadata - ) - if restored_schema_meta != schema.metadata: - needs_rebuild = True - - if needs_rebuild: - target_schema = _pa.schema(new_fields, metadata=restored_schema_meta) - batch = cast_changed_columns(batch, target_schema) - if paths is not None: - with _about_table(qualified): - batch = enforce_nullability_record(batch, paths) - return batch - - return prepare - def scan_batches( self, table_name: str, @@ -822,9 +871,10 @@ def scan_batches( """Scan a table, optionally restricted, and yield prepared Arrow batches. The restrictions are applied by SpiralDB, before any row reaches this - process. Batches arrive in key order; their sizes follow SpiralDB's stored - fragments and cannot be chosen. Each batch has the types, metadata and - nullability ``iter_batches`` documents. + process, except a condition on a column its literals do not cover (``float16``): + that one is applied here, to the rows the other conditions select, and ``limit`` + after it, so rows are transferred that are not returned. Batches arrive in key order; their sizes are SpiralDB's. Each batch has + the types, metadata and nullability ``iter_batches`` documents. Args: table_name: Plain table name (no dataset prefix). @@ -837,8 +887,7 @@ def scan_batches( Arrow RecordBatch objects. Nothing for a table with no matching row. Raises: - NullabilityRecordError: If the table's nullability record cannot be read or - names a column the table does not have. + TableSchemaError: If the table's row cannot be read or disagrees with it. NullInNonNullableColumnError: If a batch holds a null in a recorded non-nullable column (naming the table and the column). """ @@ -853,12 +902,11 @@ def get_arrow_schema(self, table_name: str) -> pa.Schema: table_name: Plain table name (no dataset prefix). Returns: - The prepared Arrow schema: large-normalized types, restored metadata and - the nullability the table's nullability record gives. + The prepared Arrow schema: large-normalized types, and the metadata and + nullability the table's row in the schema table records. Raises: - NullabilityRecordError: If the table's nullability record cannot be read or - names a column the table does not have. + TableSchemaError: If the table's row cannot be read or disagrees with it. """ return self.lookup_table(table_name).arrow_schema() @@ -889,10 +937,10 @@ def get_table_version(self, table_name: str) -> int: return self.lookup_table(table_name).version() def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> int: - """Return the table's row count as SpiralDB's manifests record it, without scanning. + """Return the table's row count, exact, by reading every key. - The count is what the manifests hold: it can be above the number of rows a - scan returns when rows were deleted or overwritten and not yet compacted. + SpiralDB offers no recorded count of a keyed table. The cost grows with the + table; ``SpiralDBTable.count_rows`` takes a bound. Args: table_name: Plain table name (no dataset prefix). @@ -900,20 +948,18 @@ def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> in as ``scan_batches`` takes). If ``None`` (default), the current version. Returns: - The recorded row count. + The number of rows. """ return self.lookup_table(table_name).row_count_estimate(asof=asof) def delete_table(self, table_name: str) -> None: - """Drop a table from SpiralDB, if it exists. + """Refuse to drop a table: Orcapod does not write SpiralDB yet. - Args: - table_name: Plain table name (no dataset prefix). Silently ignored - if the table does not exist. + Raises: + SpiralDBWriteNotSupportedError: Always (ITL-1186). """ self._require_open() - if table_name in self.get_table_names(): - self._project.drop_table(self._table_id(table_name)) + raise SpiralDBWriteNotSupportedError(_NO_WRITES) def create_table_if_not_exists( self, @@ -921,39 +967,13 @@ def create_table_if_not_exists( columns: list[ColumnInfo], pk_column: str, ) -> None: - """Create a SpiralDB table with a single-column key schema, idempotently. - - Only the primary-key column's type is registered with Spiral at creation - time (via ``key_schema``). Non-PK columns in ``columns`` are ignored — - Spiral infers value column schemas from the first write. A second call - with the same table name is a no-op (``exist_ok=True``). - - Only single-column primary keys are supported via this method. Tables - with composite primary keys must be created outside this connector but - can be read and written through it. - - Args: - table_name: Plain table name (no dataset prefix). - columns: Full column list; must include ``pk_column``. Non-PK entries - are accepted but not used at creation time. - pk_column: Name of the single primary-key column. + """Refuse to create a table: Orcapod does not write SpiralDB yet. Raises: - ValueError: If ``pk_column`` is not found in ``columns`` (including - when ``columns`` is empty). + SpiralDBWriteNotSupportedError: Always (ITL-1186). """ self._require_open() - col_names = [c.name for c in columns] - if pk_column not in col_names: - raise ValueError( - f"pk_column {pk_column!r} not found in columns: {col_names}" - ) - pk_arrow_type = next(c.arrow_type for c in columns if c.name == pk_column) - self._project.create_table( - self._table_id(table_name), - key_schema=[(pk_column, pk_arrow_type)], - exist_ok=True, - ) + raise SpiralDBWriteNotSupportedError(_NO_WRITES) def upsert_records( self, @@ -962,256 +982,36 @@ def upsert_records( id_column: str, skip_existing: bool = False, ) -> None: - """Write records to a SpiralDB table. - - SpiralDB uses the table's key schema for conflict detection. ``id_column`` - is accepted for protocol compliance; it must appear in the table's key - schema (``tbl.key_schema.names``), but SpiralDB always uses the full - composite key schema — not just ``id_column`` — for conflict resolution. - - When ``skip_existing=False`` (default), all rows are written and existing - rows with matching keys are overwritten (upsert-by-key). When - ``skip_existing=True``, the entire table is scanned first and only rows - whose composite key is absent from the existing table are written. This - is O(n) in table size. - - Args: - table_name: Plain table name (no dataset prefix). - records: Arrow table to write. - id_column: Must be one of the table's key-schema columns. Validated - for correctness; the full composite key schema is used for - conflict detection. - skip_existing: If False (default), overwrite on key conflict. If - True, skip rows with already-existing composite keys (requires - full table scan). Note: unreliable when PK columns contain - timezone-aware timestamps — SpiralDB strips timezone at storage - time, so timezone-aware values in ``records`` will never match - the timezone-naive values returned by the existing-row scan, - causing all rows to appear novel and be re-written. - - Nullability: SpiralDB reports every top-level column and struct field - nullable, so the connector keeps the non-nullable paths of ``records.schema`` in - the table's nullability record (``write_nullability_record``). It writes the - record, before the rows, on the first write to a table that has no value columns - yet, and removes it again if those rows fail to write. A table that already holds - rows without a record gets none: recording it is a deliberate act. A later write - must declare exactly the recorded paths. - - Writers are not coordinated: SpiralDB offers no lock, and its metadata writes - are not versioned. If concurrent first writes to the same new table race with a - failed one, the table can end up without a record although rows were written: - it then reads as unrecorded (``T | None``), never with a hidden null. Repair it with - ``write_nullability_record`` after checking the data holds no null in the - non-nullable columns. - - Limitation: "no value columns yet" stands for "no rows yet", which saves a scan - on every first write. A table whose columns are all key columns, holding rows - and no record, is recorded by the next write; if that write adds value columns - declared non-nullable, the earlier rows hold nulls there and every read raises - ``NullInNonNullableColumnError`` (a null is never hidden). + """Refuse to write rows: Orcapod does not write SpiralDB yet. Raises: - ValueError: If ``id_column`` is not in the table key schema (including - empty key schema), or if any key-schema column is absent from - ``records``. - NullInNonNullableColumnError: If ``records`` holds a null in a column (or - nested field) its schema declares non-nullable. Nothing is written. - NullabilityRecordMismatchError: If the table's record lists different - non-nullable paths than ``records.schema``. Nothing is written. - NullabilityRecordError: If the table's record cannot be read, or - ``records`` has a non-nullable field inside a map. - UnsupportedValueError: If ``records`` holds a null struct at any depth, which - SpiralDB cannot store. Nothing is written; ``push_down_nulls`` is never - passed. + SpiralDBWriteNotSupportedError: Always (ITL-1186). """ self._require_open() - tbl = self._project.table(self._table_id(table_name)) - pk_cols = list(tbl.key_schema.names) - - # Guard 1: id_column must appear in the table's key schema. - # Also handles empty-key-schema tables: nothing is ever `in []`. - if id_column not in pk_cols: - raise ValueError( - f"id_column {id_column!r} is not in the table key schema {pk_cols}. " - "SpiralDB uses the table key schema for conflict detection." - ) - - # Guard 2: all PK columns must be present in the records table. - missing = [k for k in pk_cols if k not in records.schema.names] - if missing: - raise ValueError( - f"records is missing key column(s) {missing} required by the " - f"table key schema {pk_cols}." - ) - - # Nullability (ITL-936). SpiralDB keeps no non-null flag except on list items, and - # stores a null written to a non-null struct field as the type's zero, so every - # non-nullable path is checked here before anything is written. - qualified = self._qualified(table_name) - null_struct = _null_struct_path(records) - if null_struct is not None: - raise UnsupportedValueError( - f"table {qualified}: column {null_struct!r} holds a null struct, which " - "SpiralDB cannot store (it would read back as a struct of null fields); " - "nothing was written" - ) - with _about_table(qualified): - paths = schema_paths(records.schema) - check_no_nulls(records, paths) - recorded = read_nullability_record(tbl.get_metadata()) - if recorded is not None: - if recorded != paths: - raise NullabilityRecordMismatchError( - [render_path(p) for p in sorted(recorded - paths)], - [render_path(p) for p in sorted(paths - recorded)], - table=qualified, - ) - # A table with no value columns yet holds no rows Orcapod did not record (but see - # the limitation in the docstring: a table whose columns are all keys may). - record_first = recorded is None and set(tbl.schema().to_arrow().names) <= set( - pk_cols - ) - - meta_kv = _serialize_arrow_metadata(records) - - def write_rows(rows: pa.Table) -> None: - # The Arrow metadata entry as it was before this write, put back if the - # write fails. Read before anything is written, so a failed read leaves - # nothing to clean up. - previous_meta = ( - tbl.get_metadata().get(_ARROW_METADATA_KEY) - if meta_kv is not None - else None - ) - # Record first, so rows are never stored without their record; if the rows - # then fail, remove the record again, since it names columns the table lacks. - wrote_record = record_first and write_nullability_record( - tbl, records.schema - ) - try: - # The Arrow metadata too goes before the rows, so rows never land - # without the metadata that states them (a data-tag's marker, - # ITL-1019): a failed metadata write stores no row, and its retry - # writes both. - if meta_kv is not None: - tbl.set_metadata(meta_kv) - tbl.write(rows) - except BaseException: - # The Arrow metadata went in before the rows: put the entry back as it - # was, so the rows already stored keep theirs and a later write without - # metadata does not read back with this one. - if meta_kv is not None: - try: - if previous_meta is None: - tbl.drop_metadata([_ARROW_METADATA_KEY]) - else: - tbl.set_metadata({_ARROW_METADATA_KEY: previous_meta}) - except Exception as cleanup_exc: - logger.warning( - "Could not restore the Arrow metadata of %s after a failed " - "write (%s: %s); its rows may read back with the metadata " - "of the failed write.", - qualified, - type(cleanup_exc).__name__, - cleanup_exc, - ) - # Remove the record only while the table still has no value columns: - # once another writer's rows have landed, they rely on it. - if wrote_record: - try: - if set(tbl.schema().to_arrow().names) <= set(pk_cols): - remove_nullability_record(tbl) - except Exception as cleanup_exc: - logger.warning( - "Could not remove the nullability record of %s after a " - "failed first write (%s: %s); reads of the table will " - "raise NullabilityRecordError until a write succeeds.", - qualified, - type(cleanup_exc).__name__, - cleanup_exc, - ) - raise - - if not skip_existing: - # Always upsert-by-key: existing rows overwritten, novel rows inserted. - write_rows(records) - return - - # skip_existing=True: full scan → client-side key filter → write novel rows. - existing = self._spiral.scan(tbl.select()).to_table() - existing_keys = {tuple(row[k] for k in pk_cols) for row in existing.to_pylist()} - mask = pa.array( - [ - tuple(row[k] for k in pk_cols) not in existing_keys - for row in records.to_pylist() - ], - type=pa.bool_(), - ) - novel = records.filter(mask) - if len(novel) > 0: - write_rows(novel) + raise SpiralDBWriteNotSupportedError(_NO_WRITES) @property def keeps_field_metadata(self) -> bool: - """Whether this connector keeps Arrow field metadata: it does, in the native KV - store (ITL-1019). Verified against the pyspiral fake only; schema evolution - is refused by ``ConnectorArrowDatabase``.""" + """Whether this connector keeps Arrow field metadata: it does, in the + dataset's schema table (ITL-1186); schema evolution is refused by + ``ConnectorArrowDatabase``.""" return True def unstorable_column_reason( self, name: str, arrow_type: pa.DataType, *, primary_key: bool ) -> str | None: - """Say why SpiralDB cannot store a column, or ``None`` when it can (ITL-1162). - - SpiralDB stores Arrow tables natively, but not every column as written - (ITL-1164). It reserves ``.`` as its column-group separator in every name, - and the ``__`` prefix on value (column group) columns; a key column may - start with ``__`` (``__record_id``). It drops a timestamp's time zone, so a - time-zone-aware timestamp column (``timestamp[us, tz=UTC]``) would read - back as another type and is refused. It drops Arrow field metadata, so an - extension (logical) type at any depth (``File``, ``Path``, ``UUID``, a user - class, ``set[int]``, a NumPy array) would read back as its storage type and - is refused (ITL-1334; keeping it is a follow-up). A map whose key or item - field has another name than ``key`` / ``value`` reads back with those names, - and is refused too. + """Refuse every column: Orcapod does not write SpiralDB yet. A job whose database + is on this connector is refused when the database is attached, before it runs. Args: name: The column's name. arrow_type: The column's Arrow type. primary_key: Whether the column is the table's primary key. - Returns: - A short reason, or ``None`` when SpiralDB stores the column. + Raises: + SpiralDBWriteNotSupportedError: Always (ITL-1186). """ - if "." in name: - return "SpiralDB reserves '.' in column names as its column-group separator" - if name.startswith("__") and not primary_key: - return "SpiralDB reserves the '__' prefix on value columns" - if pa.types.is_timestamp(arrow_type) and arrow_type.tz is not None: - return ( - "SpiralDB drops a timestamp's time zone, so it reads back as " - f"timestamp[{arrow_type.unit}]" - ) - if _holds_zone_aware_timestamp(arrow_type): - return ( - "SpiralDB drops the time zone of a timestamp nested in it, so it " - "reads back as another type" - ) - if _holds_extension_type(arrow_type): - return ( - "SpiralDB drops Arrow field metadata, so a logical (extension) type " - "reads back as its storage type" - ) - if arrow_utils.holds_renamed_map(arrow_type): - return ( - "SpiralDB gives a map's key and item fields back as 'key' and 'value'" - ) - if _holds_map_field_metadata(arrow_type): - return ( - "the connector does not keep field metadata below a map (on its key " - "or item, or inside them), so it would read back without it" - ) - return None + raise SpiralDBWriteNotSupportedError(_NO_WRITES) def unstorable_table_name_reason(self, table_name: str) -> str | None: """Say why SpiralDB cannot hold a table of this name: it holds every name. @@ -1227,15 +1027,24 @@ def unstorable_table_name_reason(self, table_name: str) -> str | None: return None def validate_records(self, records: pa.Table) -> None: - """No-op: ``SpiralDBConnector`` preserves Arrow field metadata via the native KV store.""" + """Refuse the rows: Orcapod does not write SpiralDB yet. Called before a database + on this connector buffers them. + + Args: + records: The rows. + + Raises: + SpiralDBWriteNotSupportedError: Always (ITL-1186). + """ + raise SpiralDBWriteNotSupportedError(_NO_WRITES) def close(self) -> None: """Close this connector and release its SDK client. Idempotent.""" if not self._closed: self._closed = True - # pyspiral exposes no close method. Drop both owning references. - del self._project - del self._spiral + # spiral-sdk's client has no close method. Drop the owning references. + del self._client + del self._schemas def __enter__(self) -> SpiralDBConnector: return self diff --git a/src/orcapod/databases/spiraldb_nullability.py b/src/orcapod/databases/spiraldb_nullability.py index ec2d971b6..c021ae80d 100644 --- a/src/orcapod/databases/spiraldb_nullability.py +++ b/src/orcapod/databases/spiraldb_nullability.py @@ -1,69 +1,28 @@ -"""The nullability record of a SpiralDB table (ITL-936). +"""Nullability of SpiralDB tables: the non-nullable paths of a schema, and their check. 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. Orcapod therefore -records the non-nullable column paths of a table in the table's key-value metadata, and its -Spiral connector restores and enforces them on read. - -Format, version 1: - -* Header key ``__orcapod_nullability__``: compact JSON - ``{"format": "orcapod.nullability", "version": 1, "chunks": N, "sha256": ""}``. -* Chunk keys ``__orcapod_nullability__//`` for ``i`` in - ``0..N-1``: their values, concatenated, are the payload, whose SHA-256 is ``sha256``. -* Payload: a compact JSON list of the non-nullable paths, sorted, for example - ``[["g"],["g","x"],["k"],["l"],["l","[]"]]``. A path starts with a top-level column name; - each further segment is a struct field name, or ``"[]"`` for the item of a ``list``, - ``large_list`` or ``fixed_size_list``. - -A listed path asserts that the field is non-nullable in Arrow's sense: its array holds no -null. A path that is not listed keeps the nullability SpiralDB reports. Map interiors are -not recorded. Chunks are written before the header, and chunk keys are named by the payload -digest, so a reader sees either the previous record or the new one; chunks without a header -are no record. - -This module does not import pyspiral: ``write_nullability_record`` works on any object with -pyspiral's ``Table`` metadata methods. +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 +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 +``"[]"`` for the item of a ``list``, ``large_list`` or ``fixed_size_list``. Map interiors have +no path. """ from __future__ import annotations -import hashlib -import json -from collections.abc import Iterable, Mapping -from typing import Any, Protocol +from collections.abc import Iterable +from typing import Any import pyarrow as pa -from orcapod.errors import NullabilityRecordError, NullInNonNullableColumnError +from orcapod.errors import NullInNonNullableColumnError -RECORD_KEY = "__orcapod_nullability__" -_FORMAT = "orcapod.nullability" -_VERSION = 1 ITEM = "[]" -# SpiralDB limits a metadata key + value pair to 8 KiB; leave room for the chunk key. -_MAX_PAIR_BYTES = 8192 -_CHUNK_BYTES = _MAX_PAIR_BYTES - 128 - ColumnPath = tuple[str, ...] -class MetadataTable(Protocol): - """The metadata methods of a pyspiral ``Table`` that the record uses.""" - - def get_metadata(self) -> dict[str, bytes]: - """Return the table's key-value metadata.""" - ... - - def set_metadata(self, metadata: dict[str, bytes]) -> None: - """Upsert entries into the table's key-value metadata.""" - ... - - def drop_metadata(self, keys: list[str]) -> None: - """Remove keys from the table's key-value metadata.""" - ... - - def render_path(path: ColumnPath) -> str: """Return ``path`` as text: ``g.x`` for a struct field, ``l[]`` for a list item.""" out = path[0] @@ -80,26 +39,20 @@ def _storage(t: pa.DataType) -> pa.DataType: return t.storage_type if isinstance(t, pa.ExtensionType) else t -def _children(t: pa.DataType) -> list[tuple[str, pa.Field[Any]]]: - """Return ``(segment, field)`` for each child the record can address.""" +def field_members(t: pa.DataType) -> list[pa.Field[Any]]: + """Return the nested fields a path can address: struct fields, or a list's item.""" + t = _storage(t) if pa.types.is_struct(t): - return [(t.field(i).name, t.field(i)) for i in range(t.num_fields)] + return [t.field(i) for i in range(t.num_fields)] if ( pa.types.is_list(t) or pa.types.is_large_list(t) or pa.types.is_fixed_size_list(t) ): - return [(ITEM, t.value_field)] + return [t.value_field] return [] -def _has_non_nullable(field: pa.Field[Any]) -> bool: - """Return whether ``field`` or any field nested in it is non-nullable.""" - if not field.nullable: - return True - return any(_has_non_nullable(child) for _, child in _children(_storage(field.type))) - - def _collect(field: pa.Field[Any], path: ColumnPath, out: set[ColumnPath]) -> None: """Add the non-nullable paths at and below ``field`` to ``out``. @@ -107,254 +60,24 @@ def _collect(field: pa.Field[Any], path: ColumnPath, out: set[ColumnPath]) -> No field: The field to walk. path: The field's path. out: The set collecting non-nullable paths. - - Raises: - NullabilityRecordError: If a map holds a non-nullable field. """ if not field.nullable: out.add(path) - t = _storage(field.type) - if pa.types.is_map(t): - # Map keys are non-nullable by definition and are not recorded. - if _has_non_nullable(t.item_field): - raise NullabilityRecordError( - f"column {render_path(path)!r} has a non-nullable field inside a map, " - "which the record cannot express" - ) - return - for segment, child in _children(t): - _collect(child, (*path, segment), out) + is_struct = pa.types.is_struct(_storage(field.type)) + for member in field_members(field.type): + _collect(member, (*path, member.name if is_struct else ITEM), out) def schema_paths(schema: pa.Schema) -> frozenset[ColumnPath]: - """Return the non-nullable paths of ``schema``, nested fields included. - - Raises: - NullabilityRecordError: If a map holds a non-nullable field. - """ + """Return the non-nullable paths of ``schema``, nested fields included + (map interiors excepted).""" out: set[ColumnPath] = set() for field in schema: _collect(field, (field.name,), out) return frozenset(out) -# ------------------------------------------------------------------- encode / decode - - -def _encode(paths: Iterable[ColumnPath]) -> tuple[dict[str, bytes], bytes]: - """Return the chunk entries and the header value for ``paths``.""" - payload = json.dumps( - sorted(list(p) for p in paths), separators=(",", ":"), ensure_ascii=False - ).encode("utf-8") - digest = hashlib.sha256(payload).hexdigest() - pieces = [ - payload[i : i + _CHUNK_BYTES] for i in range(0, len(payload), _CHUNK_BYTES) - ] - chunks = {_chunk_key(digest, i): piece for i, piece in enumerate(pieces)} - header = json.dumps( - { - "format": _FORMAT, - "version": _VERSION, - "chunks": len(pieces), - "sha256": digest, - }, - separators=(",", ":"), - ).encode("utf-8") - return chunks, header - - -def _chunk_key(digest: str, index: int) -> str: - """Return the metadata key of chunk ``index`` of the payload with SHA-256 ``digest``. - - Args: - digest: The payload's SHA-256, as hex. - index: The chunk's position, from 0. - - Returns: - ``__orcapod_nullability__//``. - """ - return f"{RECORD_KEY}/{digest[:16]}/{index}" - - -def read_nullability_record( - metadata: Mapping[str, bytes], -) -> frozenset[ColumnPath] | None: - """Return the non-nullable paths recorded in a table's key-value metadata. - - Args: - metadata: The table's key-value metadata (pyspiral ``Table.get_metadata()``). - - Returns: - The recorded paths, or ``None`` if the table has no record (no header key). - - Raises: - NullabilityRecordError: If the record cannot be read in full: the header is not - JSON or has the wrong shape, the format or version is unknown, a chunk is - missing, the digest does not match, or the payload is not a list of paths. - """ - raw = metadata.get(RECORD_KEY) - if raw is None: - return None - try: - header = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise NullabilityRecordError(f"the header is not JSON ({exc})") from exc - if not isinstance(header, dict): - raise NullabilityRecordError("the header is not a JSON object") - if header.get("format") != _FORMAT: - raise NullabilityRecordError(f"unknown format {header.get('format')!r}") - if header.get("version") != _VERSION: - raise NullabilityRecordError( - f"unsupported version {header.get('version')!r} (this Orcapod reads " - f"version {_VERSION})" - ) - count, digest = header.get("chunks"), header.get("sha256") - if not isinstance(count, int) or isinstance(count, bool) or count < 1: - raise NullabilityRecordError(f"invalid chunk count {count!r}") - if not isinstance(digest, str) or len(digest) != 64: - raise NullabilityRecordError(f"invalid digest {digest!r}") - pieces = [] - for i in range(count): - piece = metadata.get(_chunk_key(digest, i)) - if piece is None: - raise NullabilityRecordError(f"chunk {i} of {count} is missing") - pieces.append(piece) - payload = b"".join(pieces) - if hashlib.sha256(payload).hexdigest() != digest: - raise NullabilityRecordError("the chunks do not match the header's digest") - try: - paths = json.loads(payload.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise NullabilityRecordError(f"the payload is not JSON ({exc})") from exc - if not isinstance(paths, list) or not all( - isinstance(p, list) and p and all(isinstance(s, str) for s in p) for p in paths - ): - raise NullabilityRecordError( - "the payload is not a list of column paths (lists of strings)" - ) - return frozenset(tuple(p) for p in paths) - - -def write_nullability_record(table: MetadataTable, schema: pa.Schema) -> bool: - """Record the non-nullable paths of ``schema`` in ``table``'s key-value metadata. - - For writers other than Orcapod's connector (and for replacing a wrong record): pass the - Arrow schema the table's data was written with. Chunks are written first, then the - header, then chunks of an earlier record are dropped, so a reader never sees a header - whose chunks are missing. Other metadata keys are left alone. The helper reads no data: - check the table holds no null in the schema's non-nullable columns before recording it. - - Replacing a record changes the schema Orcapod reads, and so the table's - ``pipeline_hash`` and ``content_hash``. - - Args: - table: A pyspiral ``Table`` (anything with ``get_metadata``, ``set_metadata`` and - ``drop_metadata``). - schema: The Arrow schema the table was written with. - - Returns: - ``True`` if a record was written, ``False`` if the table already held this record. - - Raises: - NullabilityRecordError: If ``schema`` has a non-nullable field inside a map. - """ - paths = schema_paths(schema) - current_metadata = table.get_metadata() - try: - current = read_nullability_record(current_metadata) - except NullabilityRecordError: - current = None # a broken record is replaced - if current == paths: - return False - chunks, header = _encode(paths) - table.set_metadata(chunks) - table.set_metadata({RECORD_KEY: header}) - stale = [ - k - for k in current_metadata - if k.startswith(RECORD_KEY + "/") and k not in chunks - ] - if stale: - table.drop_metadata(stale) - return True - - -def remove_nullability_record(table: MetadataTable) -> None: - """Remove ``table``'s nullability record: the header first, then every chunk. - - Used by the connector to undo a record whose rows failed to write. Chunks left - behind by a failure after the header is gone are no record. - - Args: - table: A pyspiral ``Table`` (anything with the ``MetadataTable`` methods). - """ - metadata = table.get_metadata() - if RECORD_KEY in metadata: - table.drop_metadata([RECORD_KEY]) - chunks = [k for k in metadata if k.startswith(RECORD_KEY + "/")] - if chunks: - table.drop_metadata(chunks) - - -# ------------------------------------------------------------------- apply / enforce - - -def _restrict_field( - field: pa.Field[Any], - path: ColumnPath, - paths: frozenset[ColumnPath], - matched: set[ColumnPath], -) -> pa.Field[Any]: - """Return ``field`` with every recorded path at or below ``path`` non-nullable.""" - out = field - if path in paths: - matched.add(path) - out = out.with_nullable(False) - if not any(p[: len(path)] == path and len(p) > len(path) for p in paths): - return out - t = field.type - if pa.types.is_struct(t): - new_type: pa.DataType = pa.struct( - [ - _restrict_field(t.field(i), (*path, t.field(i).name), paths, matched) - for i in range(t.num_fields) - ] - ) - elif pa.types.is_large_list(t): - new_type = pa.large_list( - _restrict_field(t.value_field, (*path, ITEM), paths, matched) - ) - elif pa.types.is_list(t): - new_type = pa.list_( - _restrict_field(t.value_field, (*path, ITEM), paths, matched) - ) - elif pa.types.is_fixed_size_list(t): - new_type = pa.list_( - _restrict_field(t.value_field, (*path, ITEM), paths, matched), t.list_size - ) - else: - return out - return out.with_type(new_type) - - -def apply_nullability_record( - schema: pa.Schema, paths: frozenset[ColumnPath] -) -> pa.Schema: - """Return ``schema`` with every recorded path non-nullable; nothing else changes. - - Raises: - NullabilityRecordError: If a recorded path is not in ``schema``. - """ - matched: set[ColumnPath] = set() - fields = [_restrict_field(field, (field.name,), paths, matched) for field in schema] - missing = sorted(paths - matched) - if missing: - raise NullabilityRecordError( - "recorded column(s) not in the table: " - + ", ".join(repr(render_path(p)) for p in missing) - ) - restricted = pa.schema(fields) - return restricted.with_metadata(schema.metadata) if schema.metadata else restricted +# ------------------------------------------------------------------- enforce def _descend(arrays: list[Any], segment: str) -> list[Any]: @@ -408,22 +131,3 @@ def cast_changed_columns(batch: pa.RecordBatch, target: pa.Schema) -> pa.RecordB for column, field in zip(batch.columns, target) ] return pa.RecordBatch.from_arrays(arrays, schema=target) - - -def enforce_nullability_record( - batch: pa.RecordBatch, paths: frozenset[ColumnPath] -) -> pa.RecordBatch: - """Check ``batch`` against the record and return it with the recorded nullability. - - This is the per-batch step of every Spiral read path (the eager connector scan, and the - streaming source of ITL-186). - - Raises: - NullabilityRecordError: If a recorded path is not in the batch. - NullInNonNullableColumnError: If a recorded path holds a null. - """ - target = apply_nullability_record(batch.schema, paths) - check_no_nulls(batch, paths) - if target.equals(batch.schema, check_metadata=True): - return batch - return cast_changed_columns(batch, target) diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_schema_table.py new file mode 100644 index 000000000..01e5731d1 --- /dev/null +++ b/src/orcapod/databases/spiraldb_schema_table.py @@ -0,0 +1,475 @@ +"""The schema table of a SpiralDB dataset (ITL-1186). + +SpiralDB reports every top-level column and every struct field nullable and keeps no +Arrow metadata, and spiral-sdk reads no key-value metadata of a table. So the schemas of a +dataset's tables are kept in one keyed table beside them, ``__orcapod_schemas__``, written +by ``scripts/migrate_spiral_schemas.py``. It is the assumed behaviour: a table that +disagrees with its row is refused, and nothing else is consulted. + +One row per table, keyed by SpiralDB's immutable id of the table; the name is checked. A +row's ``schema`` is the Arrow schema the table is read with (IPC bytes), and ``nullability`` +says where its flags come from: a nullability record (``record``), or the service, for a +table that had none (``service``). One schema per table: a snapshot whose columns differ +from it, also an older version, is refused. + +The last row written is the completion marker, under the key ``__complete__``: how many +table rows there are and a digest of them. Rows without a marker that fits them are an +interrupted migration, and every read of the dataset is refused until it is finished. A +dataset with no schema table, or a table that has no row in a complete one, is read as +SpiralDB reports it, with a warning. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +from collections.abc import Callable, Iterable, Mapping +from contextlib import AbstractContextManager +from dataclasses import dataclass +from functools import cached_property +from threading import Lock +from typing import Any + +import pyarrow as pa + +from orcapod.databases.spiraldb_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 + +SCHEMA_TABLE = "__orcapod_schemas__" +"""The reserved name of a dataset's schema table.""" +FORMAT = "orcapod.table_schema" +FORMAT_VERSION = 1 +MARKER_KEY = "__complete__" +FROM_RECORD = "record" +FROM_SERVICE = "service" + +KEY_SCHEMA = pa.schema([pa.field("table_id", pa.large_string(), nullable=False)]) +ROW_SCHEMA = pa.schema( + [ + *KEY_SCHEMA, + pa.field("table_name", pa.large_string()), + pa.field("format", pa.large_string()), + pa.field("format_version", pa.int64()), + pa.field("nullability", pa.large_string()), + pa.field("schema", pa.large_binary()), + pa.field("key_columns", pa.large_string()), + pa.field("nullable_columns", pa.large_string()), + pa.field("captured_version", pa.int64()), + pa.field("project", pa.large_string()), + pa.field("dataset", pa.large_string()), + pa.field("plan_digest", pa.large_string()), + pa.field("table_count", pa.int64()), + pa.field("rows_digest", pa.large_string()), + pa.field("written_at", pa.large_string()), + pa.field("written_by", pa.large_string()), + ] +) + + +# ---------------------------------------------------------------- comparing schemas + + +def _compared_type(t: pa.DataType) -> Any: + """Return ``t`` as it is compared: every nested name and their order count; layout + (large or not) and nullability do not.""" + if pa.types.is_struct(t): + fields = [t.field(i) for i in range(t.num_fields)] + return ["struct", *([f.name, _compared_type(f.type)] for f in fields)] + if pa.types.is_fixed_size_list(t): + return ["fixed_size_list", t.list_size, _compared_type(t.value_type)] + if pa.types.is_list(t) or pa.types.is_large_list(t): + return ["list", _compared_type(t.value_type)] + if pa.types.is_map(t): + return ["map", _compared_type(t.key_type), _compared_type(t.item_type)] + return str(arrow_utils.normalize_to_large_types(t, keep_null=True)) + + +def compared_columns(schema: pa.Schema) -> list[Any]: + """Return the columns of ``schema`` as they are compared, in order.""" + return [[f.name, _compared_type(f.type)] for f in schema] + + +def describe_difference(table: pa.Schema, recorded: pa.Schema) -> str: + """Return how a table's columns differ from a recorded schema's, naming both.""" + have = {f.name: _compared_type(f.type) for f in table} + want = {f.name: _compared_type(f.type) for f in recorded} + parts = [] + if missing := sorted(want.keys() - have.keys()): + parts.append(f"recorded but not in the table: {missing}") + if extra := sorted(have.keys() - want.keys()): + parts.append(f"in the table but not recorded: {extra}") + parts.extend( + f"column {name!r} is {table.field(name).type} in the table and " + f"{recorded.field(name).type} in the row" + for name in sorted(have.keys() & want.keys()) + if have[name] != want[name] + ) + if not parts and table.names != recorded.names: + parts.append( + f"the table has columns in order {table.names}, the row {recorded.names}" + ) + return "; ".join(parts) or "no difference" + + +def nullable_paths(schema: pa.Schema) -> list[ColumnPath]: + """Return the nullable paths of ``schema`` (map interiors excepted), sorted.""" + out: list[ColumnPath] = [] + + def walk(field: pa.Field[Any], path: ColumnPath) -> None: + if field.nullable: + out.append(path) + is_struct = pa.types.is_struct(field.type) + for member in field_members(field.type): + walk(member, (*path, member.name if is_struct else ITEM)) + + for field in schema: + walk(field, (field.name,)) + return sorted(out) + + +# ------------------------------------------------------------------------------- a row + + +@dataclass(frozen=True) +class SchemaRow: + """One table's row. + + Attributes: + table_id: SpiralDB's id of the table. + table_name: The table's plain name. + key_columns: The table's key columns, in key order. + schema_bytes: The schema the table is read with, as Arrow IPC bytes. They are + what is stored and digested, never bytes encoded again from ``schema``: + which extension types a process has registered changes those. + nullability: ``FROM_RECORD`` or ``FROM_SERVICE``. + captured_version: The table's version when its schema was recorded. Kept for + later; no read uses it. + """ + + table_id: str + table_name: str + key_columns: tuple[str, ...] + schema_bytes: bytes + nullability: str + captured_version: int + + @cached_property + def schema(self) -> pa.Schema: + """The schema in ``schema_bytes``.""" + return read_schema(self.schema_bytes) + + def content(self) -> dict[str, Any]: + """Return the row's canonical content, as JSON values (what is digested).""" + return { + "table_id": self.table_id, + "table_name": self.table_name, + "format": FORMAT, + "format_version": FORMAT_VERSION, + "nullability": self.nullability, + "captured_version": self.captured_version, + "schema": base64.b64encode(self.schema_bytes).decode(), + "key_columns": list(self.key_columns), + "nullable_columns": [list(p) for p in nullable_paths(self.schema)], + } + + def stored(self) -> dict[str, Any]: + """Return the row's stored values, without when and by whom.""" + content = self.content() + return { + **content, + "schema": self.schema_bytes, + "key_columns": canonical_json(content["key_columns"]), + "nullable_columns": canonical_json(content["nullable_columns"]), + } + + @classmethod + def from_stored(cls, row: Mapping[str, Any]) -> SchemaRow: + """Read a stored row in full. + + Args: + row: The row's values. + + Raises: + TableSchemaError: If it cannot be read: an unknown format or version, + unreadable schema bytes, or readable columns that disagree with them. + """ + _require_format(row) + if row["nullability"] not in (FROM_RECORD, FROM_SERVICE): + raise TableSchemaError( + f"a row has the unknown nullability {row['nullability']!r}" + ) + try: + schema_bytes = bytes(row["schema"]) + schema = read_schema(schema_bytes) + keys = json.loads(row["key_columns"]) + except (pa.ArrowInvalid, OSError, TypeError, ValueError) as exc: + raise TableSchemaError(f"a row cannot be decoded ({exc})") from exc + if ( + not isinstance(keys, list) + or not keys + or not all(isinstance(k, str) for k in keys) + ): + raise TableSchemaError(f"a row's key_columns are {row['key_columns']!r}") + readable = canonical_json([list(p) for p in nullable_paths(schema)]) + captured = row["captured_version"] + if not isinstance(captured, int) or captured < 0: + raise TableSchemaError(f"a row's captured_version is {captured!r}") + if row["nullable_columns"] != readable: + raise TableSchemaError( + f"a row's nullable_columns {row['nullable_columns']!r} disagree with its " + f"schema's {readable!r}" + ) + if not set(keys) <= set(schema.names): + raise TableSchemaError( + f"a row's key_columns {keys} are not all columns of its schema " + f"{schema.names}" + ) + return cls( + row["table_id"], + row["table_name"], + tuple(keys), + schema_bytes, + row["nullability"], + captured, + ) + + +def canonical_json(value: Any) -> str: + """Return ``value`` as JSON in one form: sorted keys, no spaces.""" + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + +@dataclass(frozen=True) +class Scope: + """What a schema table is complete for, as its marker states it. + + Attributes: + project: The project. + dataset: The dataset. + plan_digest: The digest of the migration plan it was written from. + """ + + project: str + dataset: str + plan_digest: str + + +def rows_digest(scope: Scope, rows: Iterable[SchemaRow]) -> str: + """Return the digest the completion marker holds: the SHA-256 (hex) of the scope and + of the rows' canonical content, in table id order. + + Args: + scope: The marker's scope. + rows: Every table's row. + """ + content = { + "project": scope.project, + "dataset": scope.dataset, + "plan_digest": scope.plan_digest, + "rows": [r.content() for r in sorted(rows, key=lambda r: r.table_id)], + } + return hashlib.sha256(canonical_json(content).encode()).hexdigest() + + +def marker_values(scope: Scope, rows: Iterable[SchemaRow]) -> dict[str, Any]: + """Return the stored values of the completion marker of ``rows``, without when and + by whom.""" + listed = list(rows) + return { + **dict.fromkeys(f.name for f in ROW_SCHEMA), + "table_id": MARKER_KEY, + "format": FORMAT, + "format_version": FORMAT_VERSION, + "project": scope.project, + "dataset": scope.dataset, + "plan_digest": scope.plan_digest, + "table_count": len(listed), + "rows_digest": rows_digest(scope, listed), + } + + +def read_schema(data: bytes) -> pa.Schema: + """Return the schema in IPC bytes, its extension types (pyarrow brings a registered + one, named in a field's metadata, to life) back in their storage form.""" + return storage_form_schema(pa.ipc.read_schema(pa.py_buffer(data))) + + +def _require_format(row: Mapping[str, Any]) -> None: + """Refuse a row of another format or version.""" + if row["format"] != FORMAT: + raise TableSchemaError(f"a row has the unknown format {row['format']!r}") + if row["format_version"] != FORMAT_VERSION: + raise TableSchemaError( + f"a row has format version {row['format_version']!r} (this Orcapod reads " + f"version {FORMAT_VERSION})" + ) + + +def read_rows( + stored: Iterable[Mapping[str, Any]], +) -> tuple[dict[str, SchemaRow], Mapping[str, Any] | None]: + """Interpret stored rows. + + Args: + stored: Every row of a schema table. + + Returns: + The table rows by table id, and the marker's values (``None`` without one). + + Raises: + TableSchemaError: If a row cannot be read in full. + """ + rows: dict[str, SchemaRow] = {} + marker: Mapping[str, Any] | None = None + for values in stored: + if values["table_id"] == MARKER_KEY: + _require_format(values) + marker = values + else: + rows[values["table_id"]] = SchemaRow.from_stored(values) + return rows, marker + + +def require_complete( + project: str, + dataset: str, + rows: Mapping[str, SchemaRow], + marker: Mapping[str, Any] | None, +) -> None: + """Refuse rows whose completion marker is missing or does not fit them. + + Args: + project: The project the schema table was read from. + dataset: Its dataset. + rows: The table rows, by table id. + marker: The marker's values, or ``None``. + + Raises: + TableSchemaError: If the migration that wrote them was interrupted or withdrawn, + or the rows were changed or copied from another dataset since. + """ + if marker is None: + raise TableSchemaError( + f"the dataset's {SCHEMA_TABLE} has no completion marker: its migration was " + "interrupted. Run the migration's write step again" + ) + if (marker["project"], marker["dataset"]) != (project, dataset): + raise TableSchemaError( + f"the dataset's {SCHEMA_TABLE} was written for dataset " + f"{marker['project']}/{marker['dataset']}" + ) + scope = Scope(project, dataset, str(marker["plan_digest"])) + if marker["table_count"] != len(rows) or marker["rows_digest"] != rows_digest( + scope, rows.values() + ): + raise TableSchemaError( + f"the dataset's {SCHEMA_TABLE} does not fit its completion marker " + f"({marker['table_count']} tables recorded, {len(rows)} found, or their " + "content differs): its migration was interrupted or withdrawn, or rows were " + "changed. Run the migration again" + ) + + +def require_schema_table(table: Any) -> bool: + """Check that an opened table is a schema table of this format. + + Args: + table: The SDK's handle. + + Returns: + Whether rows were ever written to it. + + Raises: + TableSchemaError: If it has another key or other columns: the reserved name was + taken by another program, or by another version. + """ + if list(table.key_columns) != KEY_SCHEMA.names: + raise TableSchemaError( + f"the dataset's {SCHEMA_TABLE} has key columns {list(table.key_columns)}, " + f"not {KEY_SCHEMA.names}" + ) + found = table.schema() + if found.names == KEY_SCHEMA.names: + return False + if sorted(compared_columns(found)) != sorted(compared_columns(ROW_SCHEMA)): + raise TableSchemaError( + f"the dataset's {SCHEMA_TABLE} is not a schema table this Orcapod reads: " + f"{describe_difference(found, ROW_SCHEMA)}" + ) + return True + + +# ---------------------------------------------------------------------------- the table + + +class SchemaTable: + """The schema table of one dataset, read through one client. + + The rows are kept for the snapshot (id and version) they were read from, so a lookup + opens the table and reads it again only when it changed. No lock is held during a + call to the service. + + Args: + project: The project. + dataset: The dataset. + open_table: Opens the schema table's latest snapshot; ``None`` when the dataset + has none. Any other failure is raised. + service_call: A context that says what a failing service call was doing. + """ + + def __init__( + self, + project: str, + dataset: str, + open_table: Callable[[], Any | None], + service_call: Callable[[str], AbstractContextManager[None]], + ) -> None: + self._project = project + self._dataset = dataset + self._open = open_table + self._service_call = service_call + self._lock = Lock() + self._kept: tuple[tuple[str, int], dict[str, SchemaRow]] | None = None + + def row(self, table_id: str) -> SchemaRow | None: + """Return the row of ``table_id`` as stored now; ``None`` when the dataset has no + schema table, or a complete one without that table. + + Raises: + TableSchemaError: If the table cannot be read in full or is not complete. + """ + rows = self.rows() + return None if rows is None else rows.get(table_id) + + def rows(self) -> Mapping[str, SchemaRow] | None: + """Return every row by table id, as stored now; ``None`` when the dataset has no + schema table. + + Raises: + TableSchemaError: If the table cannot be read in full or is not complete. + """ + table = self._open() + if table is None: + return None + snapshot = (str(table.resource_id), int(table.version_id)) + with self._lock: + kept = self._kept + if kept is None or kept[0] != snapshot: + with self._service_call("read the schema table"): + written = require_schema_table(table) + stored = table.scan().to_table().to_pylist() if written else [] + rows, marker = read_rows(stored) + require_complete(self._project, self._dataset, rows, marker) + kept = (snapshot, rows) + with self._lock: + # An older read that ends late does not replace a newer one. + if ( + self._kept is None + or self._kept[0][0] != snapshot[0] + or self._kept[0][1] < snapshot[1] + ): + self._kept = kept + return kept[1] diff --git a/src/orcapod/databases/spiraldb_sign_in.py b/src/orcapod/databases/spiraldb_sign_in.py new file mode 100644 index 000000000..5df2c626e --- /dev/null +++ b/src/orcapod/databases/spiraldb_sign_in.py @@ -0,0 +1,63 @@ +"""Whether spiral-sdk can sign in without asking a person (ITL-1186). + +spiral-sdk takes credentials from the environment, then from the file ``spiral login`` +saved, and otherwise starts a device sign-in: it prints a code and waits for a person. A +source, a job or a notebook must not do that, so ``require_sign_in`` refuses first. + +It decides from the environment and the file's presence alone: no client is made, no +request is sent and no credential is read. Whether a saved login still works (it expires +30 days after it was last renewed, and can be ended earlier) is not known here. +""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Mapping +from pathlib import Path + +from orcapod.errors import SpiralDBSignInError + + +def saved_login_path(environ: Mapping[str, str]) -> Path: + """Return where ``spiral login`` saves credentials. + + Args: + environ: The environment. + """ + if given := environ.get("SPIRAL_AUTH_FILE"): + return Path(given) + home = Path(environ.get("HOME") or Path.home()) + if sys.platform == "darwin": + folder = home / "Library" / "Application Support" + else: + folder = Path(environ.get("XDG_CONFIG_HOME") or home / ".config") + name = "auth.dev.json" if environ.get("SPIRAL__DEV") else "auth.json" + return folder / "pyspiral" / name + + +def require_sign_in() -> None: + """Refuse when spiral-sdk would have to ask a person to sign in. + + Raises: + SpiralDBSignInError: Saying what to run. No credential's value is read into it. + """ + environ = os.environ + if environ.get("SPIRAL_TOKEN") or environ.get("SPIRAL_WORKLOAD_ID"): + return + if environ.get("SPIRAL_CLIENT_ID") and ( + environ.get("SPIRAL_PRIVATE_KEY") or environ.get("SPIRAL_CLIENT_SECRET") + ): + return + path = saved_login_path(environ) + try: + saved = path.stat().st_size > 0 + except OSError: + saved = False + if not saved: + raise SpiralDBSignInError( + f"no SpiralDB sign-in was found (no saved login in {path}, and none of " + "SPIRAL_TOKEN, SPIRAL_WORKLOAD_ID, or SPIRAL_CLIENT_ID with " + "SPIRAL_PRIVATE_KEY is set). Run 'uv run spiral login' in a terminal, then " + "try again." + ) diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index e0a6942ee..a12be0ae7 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -576,15 +576,16 @@ def _in_table(message: str, table: str | None) -> str: return message if table is None else f"table {table}: {message}" -class NullabilityRecordError(ValueError): - """A table's nullability record cannot be read, or a schema cannot be recorded. +class TableSchemaError(ValueError): + """A SpiralDB table's row in the schema table cannot be read, or disagrees with it. - The record is the list of non-nullable column paths Orcapod keeps in a SpiralDB - table's key-value metadata (ITL-936). An unknown format or version, a missing chunk, a - digest mismatch or a path the table does not have is an error, never ignored. + A dataset's schema table holds, for each table Orcapod wrote, the schema it is read + with (ITL-1186). An unknown format or version, a row of another table id, or columns + the table does not have (or has beyond the row's) are errors, never ignored. Also + raised for a schema that cannot be recorded. Attributes: - reason: What is wrong with the record. + reason: What is wrong. table: The table, as ``"//
"``, added by the caller that knows it; ``None`` otherwise. """ @@ -592,17 +593,44 @@ class NullabilityRecordError(ValueError): def __init__(self, reason: str, *, table: str | None = None) -> None: self.reason = reason self.table = table - super().__init__(_in_table(f"nullability record: {reason}", table)) + super().__init__(_in_table(f"table schema: {reason}", table)) + + +class SpiralDBWriteNotSupportedError(NotImplementedError): + """Orcapod does not write SpiralDB through spiral-sdk yet (ITL-1186): it reads it. + + Raised by every write of ``SpiralDBConnector`` (creating or deleting a table, storing + rows), so also by a job whose database is a ``ConnectorArrowDatabase`` on one. Nothing + is written. Writing is a follow-up of ITL-1186. + """ + + +class SpiralDBSignInError(RuntimeError): + """SpiralDB cannot be reached without a person signing in; the message says how. + + Raised before spiral-sdk would start a device sign-in inside a source or a job. + """ + + +class UnrecordedTableSchemaWarning(UserWarning): + """A SpiralDB table that holds rows has no row in its dataset's schema table. + + Its columns are read as SpiralDB reports them: every column and struct field + nullable, with no Arrow metadata. A table written by an Orcapod release on pyspiral + reads this way until its dataset is migrated + (``scripts/migrate_spiral_schemas.py``), so its schema and its hashes differ from + what they were. Issued once per table and process. + """ class NullabilityRecordMismatchError(ValueError): - """A write declares different non-nullable columns than the table's record. + """A write declares different non-nullable columns than the table's recorded schema. - The record is never widened, narrowed or rewritten by a write. + The recorded flags are never widened, narrowed or rewritten by a write. Attributes: - only_in_record: Paths the record lists that the write declares nullable. - only_in_write: Paths the write declares non-nullable that the record does not list. + only_in_record: Paths the recorded schema lists that the write declares nullable. + only_in_write: Paths the write declares non-nullable that it does not list. table: The table, added by the caller; ``None`` otherwise. """ @@ -625,8 +653,8 @@ def __init__( parts.append(f"non-nullable in the write but not recorded: {only_in_write}") super().__init__( _in_table( - "the write's nullability differs from the table's nullability " - "record (" + "; ".join(parts) + ")", + "the write's nullability differs from the table's recorded " + "schema (" + "; ".join(parts) + ")", table, ) ) diff --git a/tests/test_core/alignment/test_spiraldb.py b/tests/test_core/alignment/test_spiraldb.py index eeb468628..1f2faee55 100644 --- a/tests/test_core/alignment/test_spiraldb.py +++ b/tests/test_core/alignment/test_spiraldb.py @@ -20,7 +20,7 @@ import pytest from orcapod.sources import SpiralDBTableSource -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk from .checker import ( Layout, @@ -66,9 +66,9 @@ def key_tokens(table: pa.Table) -> list[str]: @pytest.fixture() def source(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Any]: """A source over the fake table, scanned two rows per batch, and its oracle.""" - monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 2) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(PROJECT) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(PROJECT) project.create_table("default.event", key_schema=KEYS).write(written_table()) yield SpiralDBTableSource( PROJECT, diff --git a/tests/test_core/data_tags/test_database_capability.py b/tests/test_core/data_tags/test_database_capability.py index e33adaf88..5cc6769e8 100644 --- a/tests/test_core/data_tags/test_database_capability.py +++ b/tests/test_core/data_tags/test_database_capability.py @@ -21,7 +21,7 @@ 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, stored_data_tags +from orcapod.core.data_tags import mark_data_tags from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, @@ -31,15 +31,14 @@ ) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.sqlite_connector import SQLiteConnector -from orcapod.errors import InputValidationError, UnstorableColumnError -from orcapod.protocols.db_connector_protocol import ColumnInfo +from orcapod.errors import InputValidationError from orcapod.pipeline import PipelineJob from orcapod.protocols.database_protocols import ( FieldMetadataKeepingDatabaseProtocol, keeps_field_metadata, ) from orcapod.types import CacheMode -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk CALLS: list[float] = [] @@ -92,7 +91,7 @@ def _adapter(cls: type[ThirdPartyDatabase]) -> Any: @pytest.fixture() def spiral(tmp_path: Path) -> Iterator[None]: - with fake_pyspiral.install(tmp_path / "spiral"): + with fake_spiral_sdk.install(tmp_path / "spiral"): yield @@ -220,11 +219,6 @@ def test_plain_tags_ask_nothing_of_an_undeclared_database() -> None: assert job.nodes["double"].keys() == (("unit",), ("y",)) -# --------------------------------------------------------------------------- -# SpiralDB (pyspiral fake): the marker survives every write path it has -# --------------------------------------------------------------------------- - - def _rows(ids: list[int], extra: bool = False) -> pa.Table: columns: dict[str, pa.Array[Any]] = { "rid": pa.array([str(i).encode() for i in ids], pa.large_binary()), @@ -234,234 +228,3 @@ def _rows(ids: list[int], extra: bool = False) -> pa.Table: if extra: columns["z"] = pa.array(ids, pa.int64()) return mark_data_tags(pa.Table.from_pydict(columns), ["unit"]) - - -def test_spiraldb_keeps_the_marker_on_every_write_path(spiral: None) -> None: - db = ConnectorArrowDatabase(SpiralDBConnector("p")) - path = ("node", "table") - - def data_tags(database: ConnectorArrowDatabase = db) -> tuple[str, ...]: - table = database.get_all_records(path) - assert table is not None - return stored_data_tags(table.schema) - - db.add_records(path, _rows([1, 2]), record_id_column="rid", flush=True) - assert data_tags() == ("unit",) # first write - db.add_records(path, _rows([3]), record_id_column="rid", flush=True) - assert data_tags() == ("unit",) # append - db.add_records( - path, _rows([3, 4]), record_id_column="rid", skip_duplicates=True, flush=True - ) - assert data_tags() == ("unit",) # some ids stored already: a merge - # Read through a new connector: the marker is stored, not held in memory. - assert data_tags(ConnectorArrowDatabase(SpiralDBConnector("p"))) == ("unit",) - # The connector database does not evolve a stored schema: it refuses, so no merge - # can drop the marker. - with pytest.raises(ValueError, match="Schema evolution is not supported"): - db.add_records(path, _rows([5], extra=True), record_id_column="rid", flush=True) - assert data_tags() == ("unit",) - - -def test_a_data_tag_job_on_spiraldb_is_refused_as_a_plain_one_is( - spiral: None, -) -> None: - """SpiralDB refuses a function node's reserved columns (ITL-1162), plain or not. - - The marker is not what stops it: the job with data-tags is refused for the same - column as the plain one, before anything is written. - """ - plain = op.sources.DictSource( - [{"unit": 1, "time": 10, "amp": 0.5}], - tag_columns=["unit", "time"], - tag_only_columns=True, - source_id="spikes", - ) - messages = [] - for source in (_source(), plain): - job = PipelineJob(database=ConnectorArrowDatabase(SpiralDBConnector("p"))) - with pytest.raises(UnstorableColumnError) as info: - with job: - double.pod(source, label="double") - messages.append(str(info.value)) - assert all("'__input_data_hash'" in message for message in messages) - - -def test_spiraldb_failed_marker_write_stores_no_row( - spiral: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """The marker is written before the rows: if it fails, no row is stored unmarked.""" - db = ConnectorArrowDatabase(SpiralDBConnector("p")) - path = ("node", "table") - db.add_records(path, _rows([1]), record_id_column="rid", flush=True) - real_set_metadata = fake_pyspiral.FakeTable.set_metadata - - def failing_set_metadata(self: Any, metadata: dict[str, bytes]) -> None: - # Only the Arrow metadata entry (the marker) fails. - if "__arrow_metadata__" in metadata: - raise RuntimeError("metadata service unavailable") - real_set_metadata(self, metadata) - - monkeypatch.setattr(fake_pyspiral.FakeTable, "set_metadata", failing_set_metadata) - with pytest.raises(RuntimeError, match="metadata service unavailable"): - db.add_records( - path, - _rows([2, 3]), - record_id_column="rid", - skip_duplicates=True, - flush=True, - ) - monkeypatch.setattr(fake_pyspiral.FakeTable, "set_metadata", real_set_metadata) - stored = ConnectorArrowDatabase(SpiralDBConnector("p")).get_all_records(path) - assert stored is not None and stored.column("unit").to_pylist() == [1] - - # The retry writes the rows and their marker. - db.add_records( - path, _rows([2, 3]), record_id_column="rid", skip_duplicates=True, flush=True - ) - table = ConnectorArrowDatabase(SpiralDBConnector("p")).get_all_records(path) - assert table is not None and set(table.column("unit").to_pylist()) == {1, 2, 3} - assert stored_data_tags(table.schema) == ("unit",) - - -def test_spiraldb_write_of_stored_rows_keeps_the_stored_metadata(spiral: None) -> None: - """A write with other field metadata never replaces a metadata entry already stored: - it is refused, naming the column, even when every row is already stored (ITL-1334).""" - db = ConnectorArrowDatabase(SpiralDBConnector("p")) - path = ("node", "table") - db.add_records(path, _rows([1, 2]), record_id_column="rid", flush=True) - # The same rows, with other field metadata: ``unit`` unmarked, ``y`` annotated. - rows = _rows([1, 2]) - other = rows.cast( - pa.schema( - [ - field.with_metadata({"note": "other"}) - if field.name == "y" - else field.remove_metadata() - for field in rows.schema - ] - ) - ) - with pytest.raises(InputValidationError, match="'unit'"): - db.add_records( - path, other, record_id_column="rid", skip_duplicates=True, flush=True - ) - db.flush() - table = ConnectorArrowDatabase(SpiralDBConnector("p")).get_all_records(path) - assert table is not None and stored_data_tags(table.schema) == ("unit",) - - -def test_spiraldb_marks_no_stored_row_it_skips(spiral: None) -> None: - """Rows stored unmarked stay unmarked when the same ids are written marked: the - write is refused, naming the column (ITL-1334).""" - db = ConnectorArrowDatabase(SpiralDBConnector("p")) - path = ("node", "table") - rows = _rows([1, 2]) - unmarked = rows.cast(pa.schema([field.remove_metadata() for field in rows.schema])) - db.add_records(path, unmarked, record_id_column="rid", flush=True) - with pytest.raises(InputValidationError, match="'unit'"): - db.add_records( - path, rows, record_id_column="rid", skip_duplicates=True, flush=True - ) - db.flush() - table = ConnectorArrowDatabase(SpiralDBConnector("p")).get_all_records(path) - assert table is not None and stored_data_tags(table.schema) == () - - -def test_spiraldb_failed_first_write_leaves_no_marker( - spiral: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """A first write whose rows fail removes the metadata it published before them.""" - connector = SpiralDBConnector("p") - connector.create_table_if_not_exists( - "t", [ColumnInfo("rid", pa.large_binary())], pk_column="rid" - ) - real_write = fake_pyspiral.FakeTable.write - - def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: - raise RuntimeError("write failed") - - monkeypatch.setattr(fake_pyspiral.FakeTable, "write", failing_write) - with pytest.raises(RuntimeError, match="write failed"): - connector.upsert_records("t", _rows([1]), id_column="rid") - monkeypatch.setattr(fake_pyspiral.FakeTable, "write", real_write) - - rows = _rows([1]) - unmarked = rows.cast(pa.schema([field.remove_metadata() for field in rows.schema])) - connector.upsert_records("t", unmarked, id_column="rid") - table = pa.Table.from_batches(list(connector.iter_batches('SELECT * FROM "t"'))) - assert stored_data_tags(table.schema) == () - - -def test_spiraldb_failed_write_keeps_the_metadata_of_stored_rows( - spiral: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """A failed write restores the metadata entry the stored rows had, even key-only.""" - connector = SpiralDBConnector("p") - connector.create_table_if_not_exists( - "k", [ColumnInfo("rid", pa.large_binary())], pk_column="rid" - ) - - def key_only(ids: list[int]) -> pa.Table: - return mark_data_tags( - pa.table( - {"rid": pa.array([str(i).encode() for i in ids], pa.large_binary())} - ), - ["rid"], - ) - - connector.upsert_records("k", key_only([1]), id_column="rid") - real_write = fake_pyspiral.FakeTable.write - - def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: - raise RuntimeError("write failed") - - monkeypatch.setattr(fake_pyspiral.FakeTable, "write", failing_write) - with pytest.raises(RuntimeError, match="write failed"): - connector.upsert_records("k", key_only([2]), id_column="rid") - monkeypatch.setattr(fake_pyspiral.FakeTable, "write", real_write) - - table = pa.Table.from_batches(list(connector.iter_batches('SELECT * FROM "k"'))) - assert table.column("rid").to_pylist() == [b"1"] - assert stored_data_tags(table.schema) == ("rid",) - - -def test_spiraldb_failed_metadata_read_leaves_no_nullability_record( - spiral: None, monkeypatch: pytest.MonkeyPatch -) -> None: - """A metadata read that fails after the record was written leaves no stale record.""" - from orcapod.databases.spiraldb_nullability import RECORD_KEY - - connector = SpiralDBConnector("p") - connector.create_table_if_not_exists( - "t", [ColumnInfo("rid", pa.large_binary())], pk_column="rid" - ) - real_get_metadata = fake_pyspiral.FakeTable.get_metadata - real_set_metadata = fake_pyspiral.FakeTable.set_metadata - record_written: list[bool] = [] - - def tracking_set_metadata(self: Any, metadata: dict[str, bytes]) -> None: - real_set_metadata(self, metadata) - if any(key.startswith(RECORD_KEY) for key in metadata): - record_written.append(True) - - def failing_get_metadata(self: Any) -> dict[str, bytes]: - # Every read after the nullability record is written fails. - if record_written: - raise RuntimeError("metadata read failed") - return real_get_metadata(self) - - monkeypatch.setattr(fake_pyspiral.FakeTable, "set_metadata", tracking_set_metadata) - monkeypatch.setattr(fake_pyspiral.FakeTable, "get_metadata", failing_get_metadata) - try: - connector.upsert_records("t", _rows([1]), id_column="rid") - wrote = True - except RuntimeError: - wrote = False - monkeypatch.undo() - - table = connector._project.table(connector._table_id("t")) # pyright: ignore[reportPrivateUsage] - if not wrote: - assert not any(key.startswith(RECORD_KEY) for key in table.get_metadata()) - else: - rows = pa.Table.from_batches(list(connector.iter_batches('SELECT * FROM "t"'))) - assert rows.num_rows == 1 diff --git a/tests/test_core/operators/test_filter_pipeline.py b/tests/test_core/operators/test_filter_pipeline.py index 2496fcf90..01f35c2a2 100644 --- a/tests/test_core/operators/test_filter_pipeline.py +++ b/tests/test_core/operators/test_filter_pipeline.py @@ -23,7 +23,7 @@ from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource from orcapod.types import CacheMode, Condition -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") @@ -180,9 +180,9 @@ def source(arrow_type: pa.DataType) -> ArrowTableSource: @pytest.fixture() def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """A fake SpiralDB project holding a 6-row ``event`` table.""" - monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 2) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.create_table("default.event", key_schema=_KEYS).write( pa.table( { @@ -294,8 +294,8 @@ def test_a_filter_reads_what_the_source_selects( @pytest.mark.parametrize( "value, alone, with_where", [ - (float("nan"), [1, 3], []), - (-0.0, [4, 5], [4, 5]), + (float("nan"), [1, 3], [1, 3]), + (-0.0, [4, 5], [4]), (2.0, [6], [6]), ], ids=["NaN", "signed zero", "ordinary float"], @@ -303,8 +303,9 @@ def test_a_filter_reads_what_the_source_selects( def test_where_and_filter_on_a_float_column(project, value, alone, with_where): """CodeRabbit on PR 493 (spec 483, Major) and PR 498 (sources.md:447, operators.md:861): ``filter`` matches floats by Orcapod's rule (NaN equals NaN); ``where`` by the table - system's equality (here IEEE: a NaN matches no row), so ``where`` plus ``filter`` can - keep fewer rows than the ``filter`` alone, and only for a NaN.""" + system's equality (SpiralDB's, as measured on the service: NaN equals NaN and 0.0 does + not equal -0.0), so ``where`` plus ``filter`` can keep fewer rows than the ``filter`` + alone, and only for a zero.""" assert _timestamps(_events().filter(reading=value)) == alone assert ( _timestamps(_events().where(reading=value).filter(reading=value)) == with_where diff --git a/tests/test_core/sources/test_large_normalization_sources.py b/tests/test_core/sources/test_large_normalization_sources.py index 1b25f3ed2..858c34816 100644 --- a/tests/test_core/sources/test_large_normalization_sources.py +++ b/tests/test_core/sources/test_large_normalization_sources.py @@ -233,10 +233,10 @@ def test_function_pod_stream_is_large(n_rows: int, tmp_path: Path) -> None: def test_spiraldb_table_source_is_large(tmp_path: Path) -> None: from orcapod.sources import SpiralDBTableSource - from tests.test_databases import fake_pyspiral + from tests.test_databases import fake_spiral_sdk - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project("p") + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject("p") table = project.create_table( "default.r", key_schema=pa.schema([pa.field("t", pa.string())]) ) diff --git a/tests/test_core/sources/test_source_check_for_new_data.py b/tests/test_core/sources/test_source_check_for_new_data.py index e5e7bd849..270b039ce 100644 --- a/tests/test_core/sources/test_source_check_for_new_data.py +++ b/tests/test_core/sources/test_source_check_for_new_data.py @@ -21,7 +21,6 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import InMemoryArrowDatabase -from orcapod.databases.spiraldb_nullability import write_nullability_record from orcapod.databases.sqlite_connector import SQLiteConnector from orcapod.errors import SourceCheckFailedWarning from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator @@ -37,7 +36,7 @@ SQLiteTableSource, ) from orcapod.types import ColumnInfo -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk CALLS: list[int] = [] ORCHESTRATORS = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} @@ -226,12 +225,12 @@ def test_delta_failed_check_warns_and_runs_on_held_rows( @pytest.fixture() def spiral(tmp_path: Path): """A fake project with table ``default.t`` holding k = 0, 1, 2.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) table = project.create_table("default.t", key_schema=_KEYS) table.write(_rows([0, 1, 2])) # SpiralDB reports every column nullable; the record says k and x are not. - write_nullability_record(table, _SCHEMA) + table.record(_SCHEMA) yield project @@ -252,9 +251,9 @@ def test_spiral_new_version_is_pinned_without_reading_rows(spiral: Any) -> None: source = _spiral(max_rows=2) # the table holds more rows than one read may return before = source.last_modified spiral.table("default.t").write(_rows([3])) - scans = len(fake_pyspiral.scan_log) + scans = len(fake_spiral_sdk.scan_log) assert source.check_for_new_data() is True # no SourceTooLargeError: no row read - assert len(fake_pyspiral.scan_log) == scans + assert len(fake_spiral_sdk.scan_log) == scans assert source.last_modified is not None and before is not None assert source.last_modified > before assert source.check_for_new_data() is False @@ -266,7 +265,7 @@ def test_spiral_reads_the_new_version_after_the_check(spiral: Any) -> None: assert source.check_for_new_data() is True _ = source.as_table() assert ( - fake_pyspiral.scan_log[-1].kwargs["asof"] + fake_spiral_sdk.scan_log[-1].kwargs["asof"] == spiral.table("default.t").last_modified_at() ) @@ -279,7 +278,7 @@ def test_spiral_explicit_asof_never_moves(spiral: Any) -> None: assert source.check_for_new_data() is False assert source.last_modified == before _ = source.as_table() - assert fake_pyspiral.scan_log[-1].kwargs["asof"] == version + assert fake_spiral_sdk.scan_log[-1].kwargs["asof"] == version def test_spiral_recreated_table_fails_the_check(spiral: Any) -> None: @@ -287,7 +286,7 @@ def test_spiral_recreated_table_fails_the_check(spiral: Any) -> None: spiral.drop_table("default.t") recreated = spiral.create_table("default.t", key_schema=_KEYS) recreated.write(_rows([0, 1, 2, 3])) - write_nullability_record(recreated, _SCHEMA) + recreated.record(_SCHEMA) with pytest.raises(ValueError, match="dropped and created again"): source.check_for_new_data() @@ -295,9 +294,8 @@ def test_spiral_recreated_table_fails_the_check(spiral: Any) -> None: def test_spiral_changed_columns_fail_the_check(spiral: Any) -> None: source = _spiral() # Recording x as nullable changes the schema the source reads. - write_nullability_record( - spiral.table("default.t"), - pa.schema([pa.field("k", pa.int64(), False), pa.field("x", pa.int64(), True)]), + spiral.table("default.t").record( + pa.schema([pa.field("k", pa.int64(), False), pa.field("x", pa.int64(), True)]) ) with pytest.raises(ValueError, match="Build the source again"): source.check_for_new_data() diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 417cbbcd1..8c8e91e4e 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -1,7 +1,7 @@ -"""Count SDK calls for sources and jobs using the repository's pyspiral fake. +"""Count SDK calls for sources and jobs using the repository's spiral-sdk fake. Construction and each freshness check get metadata from one lookup (ITL-1350). -Each read has its own table lookup, including reads that also use a manifest count, +Each read has its own table lookup, including reads that also count rows, and the source reuses its SDK client (ITL-1431). """ @@ -22,12 +22,12 @@ from orcapod.databases import ( InMemoryArrowDatabase, SpiralDBConnector, - write_nullability_record, ) +from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE from orcapod.operators import SelectColumns from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk _PROJECT = "lookups" # Two key columns (tags) and two data columns, in two arrangements: the key order of the @@ -45,16 +45,9 @@ "x": pa.field("x", pa.int64(), nullable=False), "y": pa.field("y", pa.large_string(), nullable=True), } -COUNTED = { - (fake_pyspiral.FakeSpiral, "__init__"): "client", - (fake_pyspiral.FakeSpiral, "manifest_stats"): "manifest", - (fake_pyspiral.FakeSpiral, "scan"): "scan", - (fake_pyspiral.FakeProject, "table"): "lookup", - (fake_pyspiral.FakeProject, "list_tables"): "list_tables", - (fake_pyspiral.FakeTable, "schema"): "schema", - (fake_pyspiral.FakeTable, "last_modified_at"): "version", - (fake_pyspiral.FakeTable, "get_metadata"): "metadata", -} +# What is counted: "client" built; "lookup" of the user's table by name; "open_schemas" and +# "read_schemas", the opening of the dataset's schema table and the reads of its rows; +# "schema" of the user's table; "scan" of its rows and "count" of its keys. def _schema(layout: list[str]) -> pa.Schema: @@ -79,28 +72,52 @@ def _rows(layout: list[str], ks: list[int]) -> pa.Table: def calls( request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> Iterator[collections.Counter[str]]: - """A fake project with table ``default.t`` in one arrangement; counts the pyspiral + """A fake project with table ``default.t`` in one arrangement; counts the SDK calls made on it.""" keys, layout = ARRANGEMENTS[request.param] counts: collections.Counter[str] = collections.Counter() - for (cls, name), label in COUNTED.items(): + + def is_schemas(name: str) -> bool: + return name == SCHEMA_TABLE + + def lookup_label(args: tuple[Any, ...], kwargs: Any) -> str: # pyright: ignore[reportExplicitAny] # the call's + return "open_schemas" if is_schemas(args[3]) else "lookup" + + def handle_label(user: str) -> Callable[..., str | None]: + def label(args: tuple[Any, ...], kwargs: Any) -> str | None: # pyright: ignore[reportExplicitAny] # the call's + if is_schemas(args[0]._table["name"]): + return "read_schemas" if user == "scan" else None + columns = args[1] if len(args) > 1 else kwargs.get("columns") + return "count" if user == "scan" and columns else user + + return label + + counted: dict[tuple[type, str], Callable[..., str | None]] = { + (fake_spiral_sdk.FakeClient, "__init__"): lambda args, kwargs: "client", + (fake_spiral_sdk.FakeClient, "keyed_table"): lookup_label, + (fake_spiral_sdk.FakeKeyedTable, "schema"): handle_label("schema"), + (fake_spiral_sdk.FakeKeyedTable, "scan"): handle_label("scan"), + } + for (cls, name), label_of in counted.items(): original: Callable[..., Any] = getattr(cls, name) # pyright: ignore[reportExplicitAny] # the fake's method def wrapper( *args: Any, # pyright: ignore[reportExplicitAny] # passed through _original: Callable[..., Any] = original, # pyright: ignore[reportExplicitAny] - _label: str = label, + _label_of: Callable[..., str | None] = label_of, **kwargs: Any, # pyright: ignore[reportExplicitAny] ) -> Any: # pyright: ignore[reportExplicitAny] - counts[_label] += 1 + label = _label_of(args, kwargs) + if label is not None: + counts[label] += 1 return _original(*args, **kwargs) monkeypatch.setattr(cls, name, wrapper) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) table = project.create_table("default.t", key_schema=_keys(keys)) table.write(_rows(layout, [0, 1, 2])) - write_nullability_record(table, _schema(layout)) + table.record(_schema(layout)) _ARRANGED["keys"], _ARRANGED["layout"] = keys, layout counts.clear() yield counts @@ -149,8 +166,8 @@ def test_a_source_looks_its_table_up_once_to_build( "client": 1, "lookup": 1, "schema": 1, - "metadata": 1, - "version": 1, + "open_schemas": 1, + "read_schemas": 1, } # Its reads are those of every source: the key order, layout and role it has. tags, data = source.keys() @@ -167,7 +184,13 @@ def test_a_source_with_a_given_version_reads_no_version( ) -> None: _source(role, asof=1) # Before ITL-1350: 3 lookups (key, id, schema). - assert calls == {"client": 1, "lookup": 1, "schema": 1, "metadata": 1} + assert calls == { + "client": 1, + "lookup": 1, + "schema": 1, + "open_schemas": 1, + "read_schemas": 1, + } @pytest.mark.parametrize("role", sorted(ROLES)) @@ -179,7 +202,7 @@ def test_each_check_looks_the_table_up_once( calls.clear() assert source.check_for_new_data() is False # Before ITL-1350: 3 lookups (id, schema, version). - assert calls == {"lookup": 1, "schema": 1, "metadata": 1, "version": 1} + assert calls == {"lookup": 1, "schema": 1, "open_schemas": 1} sync, async_ = _sync_and_async_rows(source) assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) @@ -190,11 +213,11 @@ def test_a_check_still_finds_a_table_created_again( ) -> None: source = _source(role) keys, layout = _ARRANGED["keys"], _ARRANGED["layout"] - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.drop_table("default.t") again = project.create_table("default.t", key_schema=_keys(keys)) again.write(_rows(layout, [0, 1, 2, 3])) - write_nullability_record(again, _schema(layout)) + again.record(_schema(layout)) calls.clear() with pytest.raises(ValueError, match="dropped and created again"): source.check_for_new_data() @@ -220,10 +243,10 @@ def test_lookup_preserves_unrelated_sdk_errors( ) -> None: error = ValueError("Invalid SDK configuration") - def fail(_project: fake_pyspiral.FakeProject, _identifier: str) -> None: + def fail(*_args: object, **_kwargs: object) -> None: raise error - monkeypatch.setattr(fake_pyspiral.FakeProject, "table", fail) + monkeypatch.setattr(fake_spiral_sdk.FakeClient, "keyed_table", fail) with pytest.raises(ValueError) as exc: _source("plain") assert exc.value is error @@ -238,26 +261,25 @@ def test_restricted_copy_keeps_client_after_parent_closes( source.close() calls.clear() assert sorted(cast("list[int]", restricted.as_table()["k"].to_pylist())) == [0, 2] - assert calls == {"lookup": 1, "metadata": 1, "scan": 1} + assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1, "scan": 1} restricted.close() def test_invalid_where_releases_client_with_exception_retained( calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch ) -> None: - clients: list[weakref.ReferenceType[fake_pyspiral.FakeSpiral]] = [] - original = fake_pyspiral.FakeSpiral.__init__ + clients: list[weakref.ReferenceType[fake_spiral_sdk.FakeClient]] = [] + original = fake_spiral_sdk.FakeClient.__init__ def track( - sdk: fake_pyspiral.FakeSpiral, + sdk: fake_spiral_sdk.FakeClient, *, - config: object = None, - overrides: dict[str, str] | None = None, + api_url: str | None = None, ) -> None: - original(sdk, config=config, overrides=overrides) + original(sdk, api_url=api_url) clients.append(weakref.ref(sdk)) - monkeypatch.setattr(fake_pyspiral.FakeSpiral, "__init__", track) + monkeypatch.setattr(fake_spiral_sdk.FakeClient, "__init__", track) source = _source("plain") assert len(clients) == 1 and clients[0]() is not None with pytest.raises(ValueError, match="missing_column") as held: @@ -285,7 +307,7 @@ async def collect() -> list[int]: keys.append(key) return keys - for _ in range(2): + for round_ in range(2): calls.clear() keys = ( asyncio.run(collect()) @@ -293,15 +315,21 @@ async def collect() -> list[int]: else cast("list[int]", source.as_table()["k"].to_pylist()) ) assert sorted(keys) == expected - assert calls == {"lookup": 1, "metadata": 1, "scan": 1} | ( - {} if restricted else {"manifest": 1} + assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1, "scan": 1} | ( + {} if restricted or round_ else {"count": 1} ) calls.clear() head = source.head(1) assert head.table.num_rows == 1 assert head.total_rows == 3 - assert calls == {"lookup": 1, "metadata": 1, "scan": 1, "manifest": 1} + # The count was made by the reads above (or is made here, after a restricted read). + assert calls == { + "lookup": 1, + "open_schemas": 1, + "schema": 1, + "scan": 1, + } | ({"count": 1} if restricted else {}) @pytest.mark.parametrize( @@ -321,12 +349,12 @@ def test_source_rejects_malformed_names_before_sdk_lookup( f"SpiralDB project {_PROJECT!r}, dataset {dataset!r}: " f"Table {name!r} not found in database." ) - assert calls["lookup"] == calls["metadata"] == calls["scan"] == 0 + assert calls["lookup"] == calls["open_schemas"] == calls["scan"] == 0 def _write_scope_table(root_layout: list[str], value: int) -> str: """Write the same-shaped table with a recognizable value in this fake endpoint.""" - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project = fake_spiral_sdk.ExternalProject(_PROJECT) table = project.create_table("default.t", key_schema=_keys(["subject", "k"])) rows = _rows(root_layout, [0]) rows = rows.set_column( @@ -335,7 +363,7 @@ def _write_scope_table(root_layout: list[str], value: int) -> str: pa.array([value], type=pa.int64()), ) table.write(rows) - write_nullability_record(table, rows.schema) + table.record(rows.schema) return table.table_id @@ -347,13 +375,13 @@ async def _async_x(source: SpiralDBTableSource) -> list[object]: @pytest.mark.parametrize("async_read", [False, True]) def test_copy_keeps_its_original_endpoint(tmp_path: Path, async_read: bool) -> None: layout = ["subject", "k", "x", "y"] - with fake_pyspiral.install(tmp_path / "endpoint-a"): + with fake_spiral_sdk.install(tmp_path / "endpoint-a"): original_id = _write_scope_table(layout, 14) source = _source("plain", asof=1) restricted = source.where(subject="s0") assert restricted.table_id == original_id - with fake_pyspiral.install(tmp_path / "endpoint-b"): + with fake_spiral_sdk.install(tmp_path / "endpoint-b"): assert _write_scope_table(layout, 29) != original_id if async_read: assert asyncio.run(_async_x(restricted)) == [14] @@ -367,12 +395,12 @@ def test_each_read_refuses_a_replacement_before_scanning( calls: collections.Counter[str], asof: int | None, mode: str ) -> None: source = _source("plain", asof=asof) - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.drop_table("default.t") keys, layout = _ARRANGED["keys"], _ARRANGED["layout"] replacement = project.create_table("default.t", key_schema=_keys(keys)) replacement.write(_rows(layout, [0])) - write_nullability_record(replacement, _schema(layout)) + replacement.record(_schema(layout)) reads: dict[str, Callable[[], object]] = { "table": source.as_table, "iter": lambda: list(source.iter_data()), @@ -390,21 +418,21 @@ def test_two_async_job_readers_use_the_restricted_sources_endpoint( tmp_path: Path, ) -> None: layout = ["subject", "k", "x", "y"] - with fake_pyspiral.install(tmp_path / "endpoint-a"): + with fake_spiral_sdk.install(tmp_path / "endpoint-a"): _write_scope_table(layout, 14) restricted = _source("plain", asof=1).where(subject="s0") - with fake_pyspiral.install(tmp_path / "endpoint-b"): + with fake_spiral_sdk.install(tmp_path / "endpoint-b"): _write_scope_table(layout, 29) job = PipelineJob(name="two-readers", database=InMemoryArrowDatabase()) with job: SelectColumns(["subject", "x"])(restricted, label="left") SelectColumns(["k", "x"])(restricted, label="right") - start = len(fake_pyspiral.scan_log) + start = len(fake_spiral_sdk.scan_log) job.run(orchestrator=AsyncPipelineOrchestrator()) assert job.nodes["left"].as_table()["x"].to_pylist() == [14] assert job.nodes["right"].as_table()["x"].to_pylist() == [14] # The async job fans one scan out to both readers of this source. - assert len(fake_pyspiral.scan_log) - start == 1 + assert len(fake_spiral_sdk.scan_log) - start == 1 @pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) @@ -423,16 +451,15 @@ def test_job_reuses_client_but_refreshes_table_each_run( assert job.nodes["read"].as_table().num_rows == 3 assert calls == { "lookup": 2, - "metadata": 2, - "schema": 1, - "version": 1, - "manifest": 1, + "open_schemas": 2, + "schema": 2, + "count": 1, "scan": 1, } calls.clear() job.run(orchestrator=runner) - assert calls == {"lookup": 1, "metadata": 1, "schema": 1, "version": 1} + assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1} def test_freshness_catches_metadata_schema_changes( @@ -440,27 +467,27 @@ def test_freshness_catches_metadata_schema_changes( ) -> None: source = _source("plain") layout = _ARRANGED["layout"] - table = fake_pyspiral.FakeSpiral().project(_PROJECT).table("default.t") + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") changed = pa.schema( [ _FIELDS[name].with_nullable(True) if name == "x" else _FIELDS[name] for name in layout ] ) - write_nullability_record(table, changed) + table.record(changed) calls.clear() with pytest.raises(ValueError, match="the table has column .x."): source.check_for_new_data() - assert calls == {"lookup": 1, "metadata": 1, "schema": 1} + assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1, "schema": 1} def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: source = _source("plain") - table = fake_pyspiral.FakeSpiral().project(_PROJECT).table("default.t") + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") table.write(_rows(_ARRANGED["layout"], [3])) calls.clear() assert source.check_for_new_data() - assert calls == {"lookup": 1, "metadata": 1, "schema": 1, "version": 1} + assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1} assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2, 3] @@ -491,13 +518,13 @@ def test_the_arrangements_give_the_same_rows_and_pipeline_hash( """Two tables holding the same rows in the two arrangements: the same rows and the same pipeline hash (a schema, in no column order); different content hashes, since they are two tables (two table ids) and the key order is part of a row's record id.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) sources = {} for name, (keys, layout) in ARRANGEMENTS.items(): table = project.create_table(f"default.{name}", key_schema=_keys(keys)) table.write(_rows(layout, [0, 1, 2])) - write_nullability_record(table, _schema(layout)) + table.record(_schema(layout)) sources[name] = SpiralDBTableSource( project_id=_PROJECT, table_name=name, tag_only_columns=ROLES[role] ) diff --git a/tests/test_core/sources/test_spiraldb_table_source.py b/tests/test_core/sources/test_spiraldb_table_source.py index 19d4f39bb..ec50f508f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source.py +++ b/tests/test_core/sources/test_spiraldb_table_source.py @@ -1,7 +1,7 @@ """Tests for SpiralDBTableSource's interface as a source. SpiralDB needs network access and credentials, so these tests run against the -disk-backed pyspiral fake (``tests/test_databases/fake_pyspiral.py``): the source goes +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 record identity are in ``test_spiraldb_table_source_streaming.py``; the workshop path is in ``test_spiraldb_table_source_fake.py``. @@ -32,7 +32,7 @@ from orcapod.core.sources import SpiralDBTableSource from orcapod.databases import SpiralDBConnector from orcapod.databases.spiraldb_connector import SpiralDBTable -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk _TABLE_NAME = "spike_data" _PROJECT_ID = "test-project-123456" @@ -55,7 +55,7 @@ def _make_table( } ) keys = pa.schema([rows.schema.field(name) for name in pk_columns]) - project = fake_pyspiral.FakeSpiral().project(project_id) + project = fake_spiral_sdk.ExternalProject(project_id) project.create_table(f"{dataset}.{name}", key_schema=keys).write(rows) @@ -76,7 +76,7 @@ def _make_composite_pk_table() -> None: @pytest.fixture(autouse=True) def fake_spiral(tmp_path: Path): """Route every source in this module to a fresh fake SpiralDB.""" - with fake_pyspiral.install(tmp_path / "spiral"): + with fake_spiral_sdk.install(tmp_path / "spiral"): yield 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 8f46a99c8..f6e99765f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_fake.py +++ b/tests/test_core/sources/test_spiraldb_table_source_fake.py @@ -3,7 +3,7 @@ Covers the workshop path (ITL-926) through the public interface: EDI-shaped tables (every column nullable, composite keys with string, timestamp and uint32 columns) -> Join of two Spiral sources -> function pod -> PipelineJob with a Delta store -> re-run -> save and load. -See ``tests/test_databases/fake_pyspiral.py`` for the storage behaviour modelled. +See ``tests/test_databases/fake_spiral_sdk.py`` for the storage behaviour modelled. """ from __future__ import annotations @@ -19,12 +19,11 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.errors import NullabilityRecordError +from orcapod.errors import TableSchemaError from orcapod.operators import Join, SelectDataColumns -from orcapod.databases import SpiralDBConnector from orcapod.sources import SpiralDBTableSource from orcapod.types import Schema -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk _PROJECT = "edi-sample" _TS = pa.timestamp("us") @@ -46,8 +45,8 @@ def _all_nullable(table: pa.Table) -> pa.Table: def spiral_root(tmp_path: Path): """Provide a fake root with EDI-shaped, all-nullable ``session`` and ``experiment``.""" root = tmp_path / "spiral" - with fake_pyspiral.install(root): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(root): + project = fake_spiral_sdk.ExternalProject(_PROJECT) session = project.create_table("default.session", key_schema=_SESSION_KEYS) session.write( _all_nullable( @@ -222,9 +221,9 @@ def test_hashes_are_stable_across_processes(spiral_root): source = SpiralDBTableSource(_PROJECT, "experiment", tag_only_columns=True) script = ( "import json\n" - "from tests.test_databases import fake_pyspiral\n" + "from tests.test_databases import fake_spiral_sdk\n" "from orcapod.sources import SpiralDBTableSource\n" - f"with fake_pyspiral.install({str(spiral_root)!r}):\n" + f"with fake_spiral_sdk.install({str(spiral_root)!r}):\n" f" s = SpiralDBTableSource({_PROJECT!r}, 'experiment', tag_only_columns=True)\n" "print(json.dumps([s.content_hash().to_string(), s.pipeline_hash().to_string()]))\n" ) @@ -259,15 +258,14 @@ def two_projects(self, tmp_path: Path): Each is written through ``SpiralDBConnector``, which records its non-nullable columns (ITL-936); ``default.unrecorded`` holds the same row without a record. """ - with fake_pyspiral.install(tmp_path / "spiral"): + with fake_spiral_sdk.install(tmp_path / "spiral"): rows = pa.table({"subject_id": ["m1"], "sex": ["F"]}, schema=self._SUBJECT) keys = pa.schema([pa.field("subject_id", pa.string(), False)]) for project in ("edi-sample-a", "edi-sample-b"): - fake = fake_pyspiral.FakeSpiral().project(project) + fake = fake_spiral_sdk.ExternalProject(project) fake.create_table("default.subject", key_schema=keys) - SpiralDBConnector(project).upsert_records( - "subject", rows, id_column="subject_id" - ) + fake.table("default.subject").write(rows) + fake.table("default.subject").record(rows.schema) fake.create_table("default.unrecorded", key_schema=keys).write(rows) yield @@ -367,22 +365,16 @@ def test_explicit_source_id_keeps_its_hashes(self, two_projects): class TestNullabilityErrors: """The source keeps the nullability error types (ITL-936).""" - def test_unreadable_record_raises_its_own_type(self, tmp_path: Path): - """A broken nullability record surfaces as NullabilityRecordError, naming the table.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + def test_a_damaged_schema_table_raises_its_own_type(self, tmp_path: Path): + """A schema table with no marker surfaces as TableSchemaError, naming the table.""" + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) keys = pa.schema([pa.field("subject_id", pa.string(), False)]) - project.create_table("default.subject", key_schema=keys) - SpiralDBConnector(_PROJECT).upsert_records( - "subject", - pa.table({"subject_id": ["m1"]}, schema=keys), - id_column="subject_id", + project.create_table("default.subject", key_schema=keys).write( + pa.table({"subject_id": ["m1"], "sex": ["F"]}) ) - table = project.table("default.subject") - header = json.loads(table.get_metadata()["__orcapod_nullability__"]) - header["version"] = 99 - table.set_metadata({"__orcapod_nullability__": json.dumps(header).encode()}) - with pytest.raises(NullabilityRecordError) as info: + fake_spiral_sdk.migrate(_PROJECT, {}, complete=False) + with pytest.raises(TableSchemaError, match="interrupted") as info: SpiralDBTableSource(_PROJECT, "subject", tag_only_columns=True) assert info.value.table == f"{_PROJECT}/default/subject" @@ -418,9 +410,14 @@ class TestNonNullableColumns: def strict_root(self, tmp_path: Path): """Provide recorded ``session`` and ``unit`` tables and an unrecorded copy of session.""" root = tmp_path / "spiral" - with fake_pyspiral.install(root): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) - connector = SpiralDBConnector(_PROJECT) + with fake_spiral_sdk.install(root): + project = fake_spiral_sdk.ExternalProject(_PROJECT) + + def write(name: str, rows: pa.Table) -> None: + """Write rows and record their schema.""" + project.table(f"default.{name}").write(rows) + project.table(f"default.{name}").record(rows.schema) + session_rows = pa.table( { "subject_id": ["m1", "m2"], @@ -432,12 +429,12 @@ def strict_root(self, tmp_path: Path): schema=self._SESSION, ) project.create_table("default.session", key_schema=self._KEYS) - connector.upsert_records("session", session_rows, id_column="subject_id") + write("session", session_rows) project.create_table( "default.session_unrecorded", key_schema=self._KEYS ).write(session_rows) project.create_table("default.unit", key_schema=self._KEYS) - connector.upsert_records( + write( "unit", pa.table( { @@ -457,7 +454,6 @@ def strict_root(self, tmp_path: Path): ] ), ), - id_column="subject_id", ) yield root diff --git a/tests/test_core/sources/test_spiraldb_table_source_live.py b/tests/test_core/sources/test_spiraldb_table_source_live.py index 57aee84a8..e705f5e6c 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_live.py +++ b/tests/test_core/sources/test_spiraldb_table_source_live.py @@ -1,13 +1,9 @@ """SpiralDBTableSource against a live SpiralDB project (ITL-186). Opt-in. -Skipped unless ``ORCAPOD_SPIRAL_LIVE_PROJECT`` names a project the saved ``spiral login`` +Skipped unless ``ORCAPOD_SPIRAL_LIVE_PROJECT`` names a project that spiral-sdk's sign-in can read, with a ``default.spike_event`` table of more than 1,000 rows (the workshop project is ``edi-tutorial-v1-841226``, 63,349 rows); the tests that need that many skip -when the table records fewer. Every test is read-only except -``test_rows_appended_between_runs_are_the_only_ones_computed`` and -``test_a_source_reads_the_version_it_was_built_at``, which also need -``ORCAPOD_SPIRAL_LIVE_WRITE=1`` and write only to a table each creates and drops in the -project's ``scratch`` dataset. +when the table holds fewer. Every test is read-only. ORCAPOD_SPIRAL_LIVE_PROJECT=edi-tutorial-v1-841226 \\ uv run --extra spiraldb pytest tests/test_core/sources/test_spiraldb_table_source_live.py @@ -17,11 +13,8 @@ import os import time -import uuid from pathlib import Path -from typing import cast -import pyarrow as pa import pytest from orcapod import PipelineJob, function_pod @@ -31,7 +24,6 @@ from orcapod.sources import SpiralDBTableSource PROJECT = os.environ.get("ORCAPOD_SPIRAL_LIVE_PROJECT", "") -WRITE = os.environ.get("ORCAPOD_SPIRAL_LIVE_WRITE") == "1" pytestmark = pytest.mark.skipif( not PROJECT, reason="Set ORCAPOD_SPIRAL_LIVE_PROJECT to run the live Spiral tests" @@ -173,86 +165,3 @@ def test_tags_as_data_gives_each_unit_its_spike_times_in_time_order(): assert sum(len(r["spike_time_us"]) for r in rows) == spikes.as_table().num_rows for row in rows: assert row["spike_time_us"] == sorted(row["spike_time_us"]) - - -@pytest.mark.skipif( - not WRITE, reason="Set ORCAPOD_SPIRAL_LIVE_WRITE=1 to write a scratch table" -) -def test_rows_appended_between_runs_are_the_only_ones_computed(tmp_path: Path): - """After rows are appended, a rerun computes only the new rows.""" - import spiral # pyright: ignore[reportMissingImports] # spiraldb extra, absent in the type-check job - - name = f"itl186_live_{uuid.uuid4().hex[:8]}" - project = spiral.Spiral().project(PROJECT) - table = project.create_table(f"scratch.{name}", key_schema=[("k", pa.int64())]) - calls: list[int | None] = [] - - @function_pod(output_keys="w") - def double(v: int | None) -> int | None: - """Return twice ``v``, recording the call.""" - calls.append(v) - return None if v is None else 2 * v - - def run() -> None: - """Build the job over the scratch table and run it.""" - job = PipelineJob( - name="append", database=DeltaTableDatabase(tmp_path / "store") - ) - with job: - double.pod( - SpiralDBTableSource( - PROJECT, name, dataset="scratch", tag_only_columns=True - ), - label="double", - ) - job.run() - - try: - table.write(pa.table({"k": [2, 3], "v": [20, 30]})) - run() - assert set(calls) == {20, 30} and len(calls) == 2 - calls.clear() - table.write(pa.table({"k": [1], "v": [10]})) - run() - assert calls == [10] - finally: - project.drop_table(f"scratch.{name}") - - -@pytest.mark.skipif( - not WRITE, reason="Set ORCAPOD_SPIRAL_LIVE_WRITE=1 to write a scratch table" -) -def test_a_source_reads_the_version_it_was_built_at(): - """A source, and its row cap, use the table version current when it was built.""" - import spiral # pyright: ignore[reportMissingImports] # spiraldb extra, absent in the type-check job - - name = f"itl186_asof_{uuid.uuid4().hex[:8]}" - project = spiral.Spiral().project(PROJECT) - table = project.create_table(f"scratch.{name}", key_schema=[("k", pa.int64())]) - - def keys(source: SpiralDBTableSource) -> list[int]: - """Return the ``k`` key of every row ``source`` reads.""" - return cast("list[int]", source.as_table().column("k").to_pylist()) - - try: - table.write(pa.table({"k": [1, 2], "v": [10, 20]})) - before = SpiralDBTableSource( - PROJECT, name, dataset="scratch", tag_only_columns=True - ) - table.write(pa.table({"k": [3], "v": [30]})) - - assert keys(before) == [1, 2] - assert [tag.as_dict()["k"] for tag, _ in before.iter_data()] == [1, 2] - assert keys( - SpiralDBTableSource(PROJECT, name, dataset="scratch", tag_only_columns=True) - ) == [1, 2, 3] - - # The cap counts the rows of the version the source reads, not the current one. - capped = SpiralDBTableSource( - PROJECT, name, dataset="scratch", max_rows=3, tag_only_columns=True - ) - table.write(pa.table({"k": [4], "v": [40]})) - assert capped.row_count_estimate == 3 - assert keys(capped) == [1, 2, 3] - finally: - project.drop_table(f"scratch.{name}") diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index e0e3a929d..2b91d9b74 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -17,12 +17,11 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.databases.spiraldb_connector import _serialize_arrow_metadata from orcapod.errors import RowIdentifierError, SourceTooLargeError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.serialization import resolve_source_from_config from orcapod.sources import SpiralDBTableSource -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk _PROJECT = "edi-sample" _KEYS = pa.schema( @@ -46,15 +45,17 @@ def _rows(timestamps: list[int], subject: str = "m1") -> pa.Table: @pytest.fixture() def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Provide a fake project holding a 5-row ``event`` table read 2 rows per batch.""" - monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 2) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.create_table("default.event", key_schema=_KEYS).write( _rows([1, 2, 3, 4, 5]) ) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() + fake_spiral_sdk.count_log.clear() yield project - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() + fake_spiral_sdk.count_log.clear() def _timestamps(source: SpiralDBTableSource) -> list[int]: @@ -84,7 +85,7 @@ def test_construction_and_identity_read_no_rows(self, project): source.to_config() assert source.row_count_estimate == _ROWS - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] def test_iter_data_reads_batches_only_as_rows_are_consumed(self, project): """``iter_data`` takes a batch from the scan only as its rows are consumed.""" @@ -92,14 +93,14 @@ def test_iter_data_reads_batches_only_as_rows_are_consumed(self, project): rows = iter(source.iter_data()) next(rows) - assert [scan.batches_read for scan in fake_pyspiral.scan_log] == [1] + assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [1] assert sum(1 for _ in rows) == _ROWS - 1 - assert [scan.batches_read for scan in fake_pyspiral.scan_log] == [3] + assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [3] def test_batches_handed_on_hold_at_most_batch_rows(self, project, monkeypatch): """Batches handed on hold at most ``batch_rows`` rows, whatever is scanned.""" - monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 4) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 4) source = SpiralDBTableSource( _PROJECT, "event", batch_rows=3, tag_only_columns=True ) @@ -133,11 +134,7 @@ def test_a_metadata_change_after_construction_is_refused(self, project): ] ) ) - # About the connector's non-public metadata encoding: it is how a table's - # field metadata is stored, and the test changes only that. - kv = _serialize_arrow_metadata(marked) # pyright: ignore[reportPrivateUsage] - assert kv is not None - project.table("default.event").set_metadata(kv) + project.table("default.event").record(marked.schema) with pytest.raises( ValueError, match="column 'amplitude'.*build the source again" @@ -239,7 +236,7 @@ def test_limit_reads_the_first_rows_in_key_order(self, project): source = SpiralDBTableSource(_PROJECT, "event", limit=2, tag_only_columns=True) assert _timestamps(source) == [1, 2] - assert fake_pyspiral.scan_log[-1].kwargs["limit"] == 2 + assert fake_spiral_sdk.scan_log[-1].kwargs["limit"] == 2 def test_where_reads_only_matching_rows(self, project): """``where`` reads only the rows whose columns equal the given values.""" @@ -297,7 +294,9 @@ def test_every_read_of_one_source_uses_the_version_it_was_built_at(self, project source.as_table() list(source.iter_data()) - assert [scan.kwargs["asof"] for scan in fake_pyspiral.scan_log] == [version] * 2 + assert [scan.kwargs["asof"] for scan in fake_spiral_sdk.scan_log] == [ + version + ] * 2 def test_a_given_version_is_used(self, project): """A given ``asof`` is passed to the scan and kept in the config.""" @@ -305,7 +304,7 @@ def test_a_given_version_is_used(self, project): source.as_table() - assert fake_pyspiral.scan_log[-1].kwargs["asof"] == 1 + assert fake_spiral_sdk.scan_log[-1].kwargs["asof"] == 1 assert source.to_config()["asof"] == 1 def test_a_given_version_zero_is_used(self, project): @@ -314,7 +313,7 @@ def test_a_given_version_zero_is_used(self, project): source.as_table() - assert fake_pyspiral.scan_log[-1].kwargs["asof"] == 0 + assert fake_spiral_sdk.scan_log[-1].kwargs["asof"] == 0 assert source.to_config()["asof"] == 0 @@ -330,11 +329,11 @@ def test_a_read_over_the_cap_is_refused_before_scanning(self, project): with pytest.raises(SourceTooLargeError) as raised: source.as_table() - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] message = str(raised.value) - assert "up to 5 rows" in message and "max_rows=3" in message - assert "records about 5 rows" in message - assert "deleted rows not yet compacted" in message + assert "more than 3 rows" in message and "max_rows=3" in message + # Counting stopped one past the cap. + assert [c.limit for c in fake_spiral_sdk.count_log] == [4] assert "limit=" in message and "where=" in message with pytest.raises(SourceTooLargeError): list(source.iter_data()) @@ -353,7 +352,7 @@ def test_a_limit_over_the_cap_is_refused(self, project): _PROJECT, "event", max_rows=3, limit=4, tag_only_columns=True ) - with pytest.raises(SourceTooLargeError, match="4 rows"): + with pytest.raises(SourceTooLargeError, match="limit=4"): source.as_table() def test_a_filtered_read_over_the_cap_stops_while_reading(self, project): @@ -523,7 +522,7 @@ def test_config_round_trip_reads_no_rows(self, project): loaded = resolve_source_from_config(config) - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] assert isinstance(loaded, SpiralDBTableSource) assert loaded.to_config() == config assert loaded.content_hash() == source.content_hash() @@ -657,13 +656,14 @@ def big(self, project): project.create_table("default.big", key_schema=_KEYS).write( _rows(list(range(1, 26))) ) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() + fake_spiral_sdk.count_log.clear() return project @staticmethod def _scan_limits() -> list[object]: """Return the ``limit`` of every scan opened, oldest first.""" - return [scan.kwargs.get("limit") for scan in fake_pyspiral.scan_log] + return [scan.kwargs.get("limit") for scan in fake_spiral_sdk.scan_log] def test_display_reads_one_head_of_ten_rows(self, big): """The notebook display is ``head()``: one 10-row scan, headed with the size.""" @@ -705,7 +705,8 @@ def test_a_sorted_head_sorts_only_the_rows_it_read(self, project): table = project.create_table("default.mixed", key_schema=_KEYS) table.write(_rows([10, 20, 30, 40, 50], subject="m1")) table.write(_rows([1, 2, 3, 4, 5, 6], subject="m2")) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() + fake_spiral_sdk.count_log.clear() source = SpiralDBTableSource( _PROJECT, "mixed", @@ -737,12 +738,13 @@ def test_a_table_above_the_cap_previews_without_raising(self, big): ) with pytest.raises(SourceTooLargeError): source.as_table() - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() + fake_spiral_sdk.count_log.clear() html = source._repr_html_() assert self._scan_limits() == [10] - assert "10 rows read, sorted by tags, of about 25" in html + assert "10 rows read, sorted by tags, of more than 20" in html def test_a_small_table_shows_all_its_rows(self, project): """A table of fewer than 10 rows is shown whole, saying so.""" @@ -813,7 +815,7 @@ def test_repr_reads_nothing(self, big): source = SpiralDBTableSource(_PROJECT, "big", tag_only_columns=True) assert repr(source) == "SpiralDBTableSource" - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] def test_switched_off_preview_shows_the_schema_without_a_scan( self, big, monkeypatch @@ -828,7 +830,7 @@ def test_switched_off_preview_shows_the_schema_without_a_scan( head = source.head() html = source._repr_html_() - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] assert head.header() == ( "SpiralDBTableSource[big] — rows not read; the table has about 25 rows" ) diff --git a/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py b/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py index 4e2dcac6c..df2e8e7d9 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py +++ b/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py @@ -21,7 +21,7 @@ from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.serialization import resolve_source_from_config from orcapod.sources import SpiralDBTableSource -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk _PROJECT = "edi-sample" _KEYS = pa.schema( @@ -60,15 +60,15 @@ def _spike_rows(spikes: list[tuple[str, int, int]]) -> pa.Table: @pytest.fixture() def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Provide a fake project holding the 7-row ``spike`` table, read 2 rows per batch.""" - monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 2) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.create_table("default.spike", key_schema=_KEYS).write( _spike_rows(_SPIKES) ) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() yield project - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() def _source(**kwargs: Any) -> SpiralDBTableSource: @@ -108,7 +108,7 @@ def test_the_schema_has_the_copy_and_construction_reads_no_rows(self, project): tag_keys, data_keys = source.keys() _, data_schema = source.output_schema() - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] assert tag_keys == ("subject_id", "timestamp", "unit_id") assert data_keys == ("amplitude", "spike_time_us") assert data_schema["spike_time_us"] is int @@ -185,7 +185,7 @@ def test_the_notebook_preview_shows_the_copy(self, project): """The bounded preview reads one head and shows the copied column.""" html = _source(tags_as_data=_COPY)._repr_html_() - assert [scan.kwargs.get("limit") for scan in fake_pyspiral.scan_log] == [10] + assert [scan.kwargs.get("limit") for scan in fake_spiral_sdk.scan_log] == [10] assert "spike_time_us" in html assert "shape: (7, 5)" in html @@ -210,7 +210,7 @@ def test_refused(self, project, mapping, named): _source(tags_as_data=mapping) assert "'spike'" in str(raised.value) - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] def test_a_tag_that_is_not_a_key_column_is_refused(self, project): """Only a key column, which is never null, can be copied.""" @@ -299,7 +299,7 @@ def test_config_round_trip(self, project): loaded = resolve_source_from_config(json.loads(json.dumps(config))) - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] assert config["tags_as_data"] == {"timestamp": "t", "unit_id": "u"} assert isinstance(loaded, SpiralDBTableSource) assert loaded.to_config() == config diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index f1d08143f..b69edfaf8 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -32,7 +32,7 @@ from orcapod.sources import SpiralDBTableSource from orcapod.core.operators import MapData from orcapod.types import CacheMode, Condition, col -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk _PROJECT = "workshop-sample" _KEYS = pa.schema( @@ -62,15 +62,15 @@ def _rows(subjects: list[str], timestamps: list[int]) -> pa.Table: @pytest.fixture() def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Provide a fake project holding a 5-row ``event`` table read 2 rows per batch.""" - monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 2) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.create_table("default.event", key_schema=_KEYS).write( _rows(["m1", "m1", "m1", "m2", "m2"], [1, 2, 3, 4, 5]) ) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() yield project - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() def _source(**kwargs: Any) -> SpiralDBTableSource: @@ -107,7 +107,9 @@ def test_condition_reaches_the_scan(self, project): """The condition is applied by SpiralDB in the scan, as ``where=`` is.""" _source().where(subject_id="m2").as_table() - assert repr(fake_pyspiral.scan_log[-1].kwargs["where"]) == "subject_id == 'm2'" + assert ( + repr(fake_spiral_sdk.scan_log[-1].kwargs["where"]) == "subject_id == 'm2'" + ) def test_mapping_and_keywords_combine(self, project): """A mapping and keywords are one set of conditions, all of which must hold.""" @@ -261,7 +263,7 @@ def test_two_keywords_reach_the_scan_in_the_order_given( """SpiralDB receives one expression joining both equalities, in call order.""" _source().where(**conditions).as_table() - assert repr(fake_pyspiral.scan_log[-1].kwargs["where"]) == expression + assert repr(fake_spiral_sdk.scan_log[-1].kwargs["where"]) == expression @pytest.mark.parametrize("form", list(_FORMS_OF_ONE_RESTRICTION)) def test_every_form_is_the_same_restriction(self, project, form): @@ -300,7 +302,7 @@ def test_a_value_of_another_type_among_several_is_refused( with pytest.raises(TypeError, match=rf"{column}.*convert"): source.where(**conditions) - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] assert source.to_config()["where"] == {} @pytest.mark.parametrize("form", list(_REPEATED_CONDITIONS)) @@ -462,7 +464,7 @@ def test_a_non_finite_or_signed_zero_float_is_pushed_down_as_given( source = restrict(value) source.as_table() - pushed = dict(fake_pyspiral.scan_log[-1].kwargs["where"].equalities) + pushed = dict(fake_spiral_sdk.scan_log[-1].kwargs["where"].equalities) assert set(pushed) == {"amplitude", "subject_id"} sent = pushed["amplitude"] assert ( @@ -504,7 +506,7 @@ def test_nothing_is_read_when_refusing(self, project): with pytest.raises(TypeError): _source().where(channel="0") - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] _UNITS: list[Any] = ["s", "ms", "us", "ns"] # pyarrow types the unit as a literal @@ -539,7 +541,6 @@ def _typed_rows() -> pa.Table: { "d64": pa.array([one, two, one], pa.date64()), "bin": pa.array([b"a", b"b", b"a"], pa.binary()), - "fbin": pa.array([b"aa", b"bb", b"aa"], pa.binary(2)), "i8": pa.array([-1, 2, -1], pa.int8()), "u8": pa.array([255, 2, 255], pa.uint8()), "i32": pa.array([1, 2, 1], pa.int32()), @@ -549,7 +550,6 @@ def _typed_rows() -> pa.Table: "t32": pa.array([dt.time(1), dt.time(2), dt.time(1)], pa.time32("s")), "t64": pa.array([dt.time(1), dt.time(2), dt.time(1)], pa.time64("us")), "dec": pa.array([Decimal("1.50")] * 3, pa.decimal128(5, 2)), - "dur": pa.array([dt.timedelta(1)] * 3, pa.duration("us")), } ) return pa.table(columns) @@ -559,11 +559,8 @@ def _typed_rows() -> pa.Table: def typed(tmp_path: Path): """Provide a ``typed`` table in a fake that keeps time zones.""" root = tmp_path / "typed" - fake_pyspiral.write_behaviour( - root, fake_pyspiral.StorageBehaviour(drop_timezone=False) - ) - with fake_pyspiral.install(root): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(root): + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.create_table( "default.typed", key_schema=pa.schema([pa.field("k", pa.int64())]) ).write(_typed_rows()) @@ -640,7 +637,6 @@ def test_two_zoned_units_and_a_key_together(self, typed): [ ("d64", dt.date(2026, 1, 1), [0, 2]), ("bin", b"a", [0, 2]), - ("fbin", b"aa", [0, 2]), ("i8", -1, [0, 2]), ("u8", 255, [0, 2]), ("i32", 2, [1]), @@ -656,14 +652,12 @@ def test_each_other_type_can_be_matched(self, typed, column, value, expected): @pytest.mark.parametrize( "column, value, match", [ - ("fbin", b"a", "cannot hold"), ("i8", 128, "cannot hold"), ("u8", -1, "cannot hold"), ("u32", 2**32, "cannot hold"), ("t32", 1, "does not support"), ("t64", 1, "does not support"), ("dec", 1.5, "does not support"), - ("dur", 1, "does not support"), ], ) def test_a_value_the_column_cannot_take_is_refused( @@ -726,11 +720,8 @@ def roles(request, tmp_path: Path): rows = _role_rows() table = pa.table({name: rows[name] for name in columns}) root = tmp_path / "roles" - fake_pyspiral.write_behaviour( - root, fake_pyspiral.StorageBehaviour(drop_timezone=False) - ) - with fake_pyspiral.install(root): - fake_pyspiral.FakeSpiral().project(_PROJECT).create_table( + with fake_spiral_sdk.install(root): + fake_spiral_sdk.ExternalProject(_PROJECT).create_table( "default.roles", key_schema=pa.schema([table.schema.field(k) for k in keys]) ).write(table) yield @@ -908,7 +899,7 @@ def test_the_pinned_version_is_carried_over(self, project): source.where(subject_id="m2").as_table() - assert fake_pyspiral.scan_log[-1].kwargs["asof"] == version + assert fake_spiral_sdk.scan_log[-1].kwargs["asof"] == version assert source.where(subject_id="m2").to_config()["asof"] is None def test_a_given_asof_is_carried_over(self, project): @@ -929,12 +920,14 @@ def test_checking_one_does_not_move_the_other(self, project): restricted.as_table() source.as_table() - new, kept = (scan.kwargs["asof"] for scan in fake_pyspiral.scan_log[-2:]) + new, kept = (scan.kwargs["asof"] for scan in fake_spiral_sdk.scan_log[-2:]) assert (new, kept) == (old + 1, old) def test_no_mutable_state_is_shared(self, project): """The two objects share no mutable container.""" - source = _source(tags_as_data={"timestamp": "time"}, overrides={"a": "b"}) + source = _source( + tags_as_data={"timestamp": "time"}, overrides={"server.url": "b"} + ) source.content_hash() restricted = source.where(subject_id="m2") @@ -991,8 +984,8 @@ def test_head_reads_only_matching_rows(self, project): view = _source().where(subject_id="m1").head(2) assert view.as_table().column("timestamp").to_pylist() == [1, 2] - assert len(fake_pyspiral.scan_log) == 1 - assert fake_pyspiral.scan_log[0].kwargs["limit"] == 2 + assert len(fake_spiral_sdk.scan_log) == 1 + assert fake_spiral_sdk.scan_log[0].kwargs["limit"] == 2 assert view.description is not None assert "where subject_id='m1'" in view.description @@ -1569,7 +1562,7 @@ def test_a_restricted_source_is_refused(self, project, tmp_path, form, via): for text in named: assert text in str(caught.value) - assert fake_pyspiral.scan_log == [] + assert fake_spiral_sdk.scan_log == [] def test_an_unrestricted_cache_still_works(self, project, tmp_path): """A cache over the whole table reads every row.""" @@ -1719,7 +1712,7 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( job = self._job(store, events) self._cache(job, "rename", mode, store) job.nodes["events"].bound_source = events.where(subject_id="m1") - scans = len(fake_pyspiral.scan_log) + scans = len(fake_spiral_sdk.scan_log) with pytest.raises(ValueError, match="cannot cache a restricted read"): if run == "job.run": @@ -1729,7 +1722,7 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( else: job.nodes["rename"].run() - assert len(fake_pyspiral.scan_log) == scans + assert len(fake_spiral_sdk.scan_log) == scans assert not folder.exists() or not any(folder.rglob("*.parquet")) @pytest.mark.parametrize("mode", _CACHING, ids=lambda m: m.name) @@ -1874,12 +1867,12 @@ def test_execute_over_restricted_streams_is_refused( restricted = _RESTRICTIONS[restriction]( _source(source_id="events", tag_only_columns=True) ) - scans = len(fake_pyspiral.scan_log) + scans = len(fake_spiral_sdk.scan_log) with pytest.raises(ValueError, match="cannot cache a restricted read"): node.execute(restricted.select_data_columns(["amplitude", "channel"])) - assert len(fake_pyspiral.scan_log) == scans + assert len(fake_spiral_sdk.scan_log) == scans assert self._stored_files(folder) == [] @pytest.mark.parametrize("mode", _CACHING, ids=lambda m: m.name) @@ -1956,12 +1949,12 @@ def test_execute_over_unrestricted_streams_still_caches( node.attach_databases( pipeline_database=store.at("events"), cache_mode=CacheMode.REPLAY ) - scans = len(fake_pyspiral.scan_log) + scans = len(fake_spiral_sdk.scan_log) replayed = list(node.execute(other).iter_data()) assert self._keyed(replayed) == expected - assert len(fake_pyspiral.scan_log) == scans + assert len(fake_spiral_sdk.scan_log) == scans def _proxy_for(source: SpiralDBTableSource) -> Any: @@ -2064,12 +2057,12 @@ def test_a_cache_over_a_proxy_bound_later_refuses_to_read(self, project, tmp_pat proxy = _proxy_for(_events()) cached = proxy.cached(cache_database=DeltaTableDatabase(tmp_path / "c")) proxy.bind(_events().where(subject_id="m1")) - scans = len(fake_pyspiral.scan_log) + scans = len(fake_spiral_sdk.scan_log) with pytest.raises(ValueError, match="cannot hold a restricted read"): cached.as_table() - assert len(fake_pyspiral.scan_log) == scans + assert len(fake_spiral_sdk.scan_log) == scans assert not (tmp_path / "c").exists() or not any( (tmp_path / "c").rglob("*.parquet") ) @@ -2328,7 +2321,7 @@ def other_table(self, project): project.create_table("default.other", key_schema=_KEYS).write( _rows(["m1", "m2", "m1", "m2", "m2"], [1, 2, 3, 4, 5]) ) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() def _job(self, tmp_path: Path, others: SpiralDBTableSource) -> PipelineJob: """Slot ``events`` (unrestricted) and slot ``others`` bound to ``others``; @@ -2376,7 +2369,7 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( job.nodes["events"].bound_source = _events().semi_join( self._others().where(subject_id="m2") ) - scans = len(fake_pyspiral.scan_log) + scans = len(fake_spiral_sdk.scan_log) with pytest.raises(ValueError, match="different rows in one pipeline"): if run == "job.run": @@ -2385,7 +2378,7 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( asyncio.run(asyncio.wait_for(job.run_async(), timeout=120)) else: job.nodes["both"].run() - assert len(fake_pyspiral.scan_log) == scans + assert len(fake_spiral_sdk.scan_log) == scans @pytest.mark.parametrize("order", ["events first", "others first"]) def test_two_tables_restricted_once_each_are_accepted( diff --git a/tests/test_core/sources/test_tag_only_columns.py b/tests/test_core/sources/test_tag_only_columns.py index 5b58991f0..aa489cd06 100644 --- a/tests/test_core/sources/test_tag_only_columns.py +++ b/tests/test_core/sources/test_tag_only_columns.py @@ -47,7 +47,7 @@ DSN, _make_mock_connector, ) -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk # Builds one source over the rows ``id`` a/b, ``x`` 1/2 in ``tmp``; the keyword is either # absent or ``tag_only_columns=...``. @@ -132,8 +132,8 @@ def _postgresql(_tmp: Path, **option: Unpack[Option]) -> SourceProtocol: @pytest.fixture() def spiral_root(tmp_path: Path) -> Iterator[None]: """Provide a fake Spiral root holding table ``default.r`` keyed on ``id``.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project("p") + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject("p") table = project.create_table( "default.r", key_schema=pa.schema([pa.field("id", pa.string())]) ) diff --git a/tests/test_core/streams/test_explain.py b/tests/test_core/streams/test_explain.py index 17d572431..66c7e56f0 100644 --- a/tests/test_core/streams/test_explain.py +++ b/tests/test_core/streams/test_explain.py @@ -49,7 +49,7 @@ Spec, make_source, ) -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk pytestmark = [ pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), @@ -96,8 +96,8 @@ def spiral(tmp_path: Path): keys = pa.schema( [pa.field("subject_id", pa.string()), pa.field("timestamp", pa.uint64())] ) - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) project.create_table("default.event", key_schema=keys).write( pa.table( { @@ -107,9 +107,9 @@ def spiral(tmp_path: Path): } ) ) - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() yield project - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() def _event(**kwargs: Any) -> SpiralDBTableSource: @@ -120,9 +120,9 @@ class TestSectionFiveCases: def test_a_restricted_source_under_a_filter(self, spiral): source = _event().where(subject_id="m1") stream = source.filter(col("amplitude") >= 1.0, label="loud") - fake_pyspiral.scan_log.clear() + fake_spiral_sdk.scan_log.clear() text = stream.explain().text() - assert fake_pyspiral.scan_log == [] # nothing read + assert fake_spiral_sdk.scan_log == [] # nothing read assert text == ( "DynamicPodStream[loud] reads:\n" f" source {source.source_id!r} (SpiralDBTableSource)\n" diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 778a9d98c..a5b8c84a6 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -1271,11 +1271,11 @@ def test_identical_invocations_keep_the_smallest_explicit_label( def _restricted_job_run(root: Path, names: Sequence[str]) -> None: """Print the node labels, summary lines and warning for one job in a child process.""" - from tests.test_databases import fake_pyspiral + from tests.test_databases import fake_spiral_sdk keys = pa.schema([pa.field("subject", pa.string())]) - with fake_pyspiral.install(root): - project = fake_pyspiral.FakeSpiral().project("synthetic") + with fake_spiral_sdk.install(root): + project = fake_spiral_sdk.ExternalProject("synthetic") for value, name in enumerate(sorted(names)): # Distinct readings avoid competing for the same cache entry in async. rows = pa.table({"subject": ["a", "b"], "reading": [value, value + 1]}) diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py deleted file mode 100644 index 9bc7a0fb1..000000000 --- a/tests/test_databases/fake_pyspiral.py +++ /dev/null @@ -1,877 +0,0 @@ -"""A disk-backed fake of the pyspiral surface that ``SpiralDBConnector`` uses. - -The unit tests for ``SpiralDBConnector`` and ``SpiralDBTableSource`` replace pyspiral (or the -whole connector) with ``MagicMock`` objects, so they never push a real Arrow table through the -connector's read path. This fake does: it stores real Arrow tables and returns them the way -SpiralDB does, so a source built on it goes through the same code as one built on a live -project. - -Only the calls the connector makes are implemented: - -* ``Spiral(overrides=...)``, ``Spiral.project(id)``, - ``Spiral.scan(expr, where=..., limit=..., asof=...)``, ``Spiral.core.manifest_stats`` - (each call is recorded in ``scan_log``; batches are read on demand) -* ``Project.list_tables()`` (``TableResource`` with ``.dataset`` / ``.table``), - ``Project.table(id)``, ``Project.create_table(id, key_schema=..., exist_ok=...)``, - ``Project.drop_table(id)`` -* ``Table.key_schema``, ``Table.table_id``, ``Table.last_modified_at()``, ``Table[name] == v``, - ``Table.core.get_snapshot()``, ``Table.schema().to_arrow()``, ``Table.select()``, ``Table.write(t)``, - ``Table.get_metadata()``, ``Table.set_metadata(kv)``, ``Table.drop_metadata(keys)`` -* ``Scan.to_record_batches()``, ``Scan.to_table()`` - -Tables live under a directory (``FAKE_SPIRAL_ROOT`` or the ``root`` given to ``install``), one -Arrow IPC file per table, so a second Python process sees the tables the first one wrote. - -Storage behaviour. Each way SpiralDB changes data on the way in or out is a switch in -``StorageBehaviour``; ``observed`` says whether it was seen on a live project (ITL-40, the -connector's docstrings, pyspiral's own documentation) or is an assumption to confirm live: - -* ``string_as_utf8`` (observed, ITL-40): strings come back as ``string`` even when written as - ``large_string``. Applied at every nesting level (assumed for nested). -* ``binary_as``: ``"binary"`` (observed on pyspiral 0.11-0.14, ITL-40) or ``"large_binary"`` - (what pyspiral 0.14.9's ``Scan.to_record_batches(disable_view_types=True)`` documents). -* ``drop_timezone`` (observed): ``timestamp[us, tz=UTC]`` comes back as ``timestamp[us]``. -* ``drop_arrow_metadata`` (observed, ITL-471): schema and field metadata are dropped; the - table's key-value store (``set_metadata``) round-trips. -* ``decode_dictionaries`` (assumed): dictionary columns come back as their value type. -* ``server_nullability`` (observed, pyspiral 0.16.33, ITL-936): SpiralDB reports every - top-level column nullable, key columns included, and every struct field nullable, whatever - was written; only list and fixed-size-list items keep a non-null flag. A null in a - top-level column declared non-null is refused on write (Arrow validates the outgoing batch - on the client). A null in a struct field declared non-null is accepted and stored as the - type's zero value (a null written to an ``int32`` field read back as ``0``). Switch it off - only to model a database that keeps nullability. -* ``reject_struct_nulls`` (documented by pyspiral ``Table.write``): a null struct value is - refused unless written with ``push_down_nulls=True``, which turns it into a struct of null - fields (observed live, ITL-936; top-level struct columns only in the fake). -* Rows come back sorted by key and writes upsert by key (SpiralDB is a key-sorted store). -""" - -from __future__ import annotations - -import json -import os -import types -import uuid -from collections.abc import Iterator -from contextlib import contextmanager -from dataclasses import asdict, dataclass -from pathlib import Path -from typing import Any, cast -from unittest.mock import patch - -import pyarrow as pa -import pyarrow.compute as pc - -_ROOT_ENV = "FAKE_SPIRAL_ROOT" -_BEHAVIOUR_FILE = "_behaviour.json" -# pyspiral 0.16.33 ``Table.set_metadata`` limits. -_MAX_PAIR_BYTES = 8192 -_MAX_KEY_CHARS = 255 -_MAX_ENTRIES = 1024 - - -@dataclass -class ScanRecord: - """One ``Spiral.scan(...)`` call: the table, its keyword arguments, batches handed out.""" - - identifier: str - kwargs: dict[str, Any] - batches_read: int = 0 - - -# Every scan opened in this process, oldest first. Tests clear it and read it. -scan_log: list[ScanRecord] = [] -# Rows per batch a scan hands out (SpiralDB's batches follow its stored fragments). -scan_batch_rows = 2 - - -@dataclass(frozen=True) -class StorageBehaviour: - """How the fake transforms data, mirroring SpiralDB's storage behaviour.""" - - string_as_utf8: bool = True - binary_as: str = "binary" - drop_timezone: bool = True - drop_arrow_metadata: bool = True - decode_dictionaries: bool = True - server_nullability: bool = True - reject_struct_nulls: bool = True - - -def _stored_type(t: pa.DataType, b: StorageBehaviour) -> pa.DataType: - """Return the Arrow type SpiralDB hands back for a column written as ``t``. - - Args: - t: The type that was written. - b: The storage behaviour to apply. - - Returns: - The stored type, with the same nesting and field names. Struct fields become - nullable under ``server_nullability``; list items keep their nullability. - """ - if isinstance(t, pa.ExtensionType): - # Vortex stores the storage type; the extension name lives in field metadata, - # which is dropped. - return _stored_type(t.storage_type, b) - if pa.types.is_dictionary(t) and b.decode_dictionaries: - return _stored_type(t.value_type, b) - if (pa.types.is_string(t) or pa.types.is_large_string(t)) and b.string_as_utf8: - return pa.string() - if pa.types.is_binary(t) or pa.types.is_large_binary(t): - return pa.binary() if b.binary_as == "binary" else pa.large_binary() - if pa.types.is_timestamp(t) and t.tz is not None and b.drop_timezone: - return pa.timestamp(t.unit) - if pa.types.is_struct(t): - return pa.struct( - [ - _stored_field(t.field(i), b, nullable=b.server_nullability or None) - for i in range(t.num_fields) - ] - ) - if pa.types.is_map(t): - # pyarrow accepts key/item fields here; its stubs list only types. - return pa.map_( # pyright: ignore[reportCallIssue] - _stored_field(t.key_field, b), - _stored_field(t.item_field, b), - keys_sorted=t.keys_sorted, - ) - if pa.types.is_large_list(t): - return pa.large_list(_stored_field(t.value_field, b)) - if pa.types.is_list(t): - return pa.list_(_stored_field(t.value_field, b)) - if pa.types.is_fixed_size_list(t): - return pa.list_(_stored_field(t.value_field, b), t.list_size) - return t - - -def _stored_field( - f: pa.Field[Any], b: StorageBehaviour, nullable: bool | None = None -) -> pa.Field[Any]: - """Return the field SpiralDB hands back for a field written as ``f``. - - Args: - f: The field that was written. - b: The storage behaviour to apply. - nullable: ``True`` to report the field nullable whatever was written; ``None`` - keeps the written flag. - """ - metadata = None if b.drop_arrow_metadata else f.metadata - flag = f.nullable if nullable is None else nullable - return pa.field(f.name, _stored_type(f.type, b), flag, metadata) - - -def _zero_struct_field_nulls( - col: pa.ChunkedArray[Any], written: pa.DataType -) -> pa.ChunkedArray[Any]: - """Store a null in a struct field declared non-null as the type's zero (seen live). - - Only top-level struct columns with primitive fields are modelled; other nulls are kept. - """ - if not pa.types.is_struct(written): - return col - chunks = [] - for chunk in col.chunks: - struct = cast("pa.StructArray", chunk) - children = [] - for i in range(written.num_fields): - child = struct.field(i) - field = written.field(i) - if not field.nullable and child.null_count: - try: - child = pc.fill_null(child, pa.scalar(0).cast(field.type)) - except (pa.ArrowInvalid, pa.ArrowNotImplementedError): - pass - children.append(child) - chunks.append( - pa.StructArray.from_arrays( - children, - fields=[ - pa.field(written.field(i).name, children[i].type, True) - for i in range(written.num_fields) - ], - mask=struct.is_null(), - ) - ) - return pa.chunked_array(chunks) - - -def _push_down_struct_nulls(col: pa.ChunkedArray[Any]) -> pa.ChunkedArray[Any]: - """Turn each null struct of a top-level struct column into a struct of null fields. - - What ``push_down_nulls=True`` was seen to do live (pyspiral 0.16.33, ITL-936): the - struct-level null and any values under it are lost. - """ - if not pa.types.is_struct(col.type) or not col.null_count: - return col - chunks = [] - for chunk in col.chunks: - struct = cast("pa.StructArray", chunk) - valid = struct.is_valid() - children = [ - pc.if_else( - valid, struct.field(i), pa.scalar(None, struct.type.field(i).type) - ) - for i in range(struct.type.num_fields) - ] - chunks.append( - pa.StructArray.from_arrays( - children, - fields=[ - struct.type.field(i).with_nullable(True) - for i in range(struct.type.num_fields) - ], - ) - ) - return pa.chunked_array(chunks) - - -def _has_struct_nulls(arr: pa.ChunkedArray[Any]) -> bool: - """Return whether ``arr`` is a struct column with a null struct value.""" - return pa.types.is_struct(arr.type) and arr.null_count > 0 - - -class _Store: - """Directory-backed table store shared by every fake object.""" - - def __init__(self, root: Path) -> None: - """Open the database under ``root`` and load its storage behaviour.""" - self.root = root - self.root.mkdir(parents=True, exist_ok=True) - bfile = self.root / _BEHAVIOUR_FILE - self.behaviour = ( - StorageBehaviour(**json.loads(bfile.read_text())) - if bfile.exists() - else StorageBehaviour() - ) - - def _path(self, project_id: str, identifier: str, suffix: str) -> Path: - # identifiers contain a dot (``dataset.table``), so never use ``with_suffix`` - """Return the file holding ``identifier``'s part named by ``suffix``.""" - return self.root / project_id / f"{identifier}{suffix}" - - def exists(self, project_id: str, identifier: str) -> bool: - """Return whether table ``identifier`` exists in ``project_id``.""" - return self._path(project_id, identifier, ".keys.json").exists() - - def identifiers(self, project_id: str) -> list[str]: - """Return every table identifier of ``project_id``, sorted.""" - pdir = self.root / project_id - if not pdir.exists(): - return [] - return sorted(p.name[: -len(".keys.json")] for p in pdir.glob("*.keys.json")) - - def create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> None: - """Create table ``identifier`` with ``key_schema`` and empty metadata.""" - (self.root / project_id).mkdir(parents=True, exist_ok=True) - sink = pa.BufferOutputStream() - pa.ipc.new_stream(sink, key_schema).close() - self._path(project_id, identifier, ".keys.arrow").write_bytes( - sink.getvalue().to_pybytes() - ) - self._path(project_id, identifier, ".keys.json").write_text( - json.dumps(key_schema.names) - ) - self._path(project_id, identifier, ".kv.json").write_text("{}") - # SpiralDB gives every table its own id; a recreated table gets a new one. - self._path(project_id, identifier, ".id.txt").write_text( - f"table_{uuid.uuid4().hex[:12]}" - ) - self._path(project_id, identifier, ".version.txt").write_text("0") - - def drop(self, project_id: str, identifier: str) -> None: - """Remove every file of table ``identifier``.""" - for suffix in ( - ".keys.json", - ".keys.arrow", - ".kv.json", - ".data.arrow", - ".id.txt", - ".version.txt", - ): - p = self._path(project_id, identifier, suffix) - if p.exists(): - p.unlink() - - def key_schema(self, project_id: str, identifier: str) -> pa.Schema: - """Return table ``identifier``'s key schema.""" - raw = self._path(project_id, identifier, ".keys.arrow").read_bytes() - return pa.ipc.open_stream(raw).schema - - def read(self, project_id: str, identifier: str) -> pa.Table | None: - """Return table ``identifier``'s rows, or ``None`` before the first write.""" - p = self._path(project_id, identifier, ".data.arrow") - if not p.exists(): - return None - with pa.ipc.open_file(pa.memory_map(str(p))) as r: - return r.read_all() - - def write(self, project_id: str, identifier: str, table: pa.Table) -> None: - """Replace table ``identifier``'s rows with ``table`` and move its version on.""" - p = self._path(project_id, identifier, ".data.arrow") - with pa.ipc.new_file(str(p), table.schema) as w: - w.write_table(table) - self._path(project_id, identifier, ".version.txt").write_text( - str(self.version(project_id, identifier) + 1) - ) - - def table_id(self, project_id: str, identifier: str) -> str: - """Return table ``identifier``'s own id.""" - return self._path(project_id, identifier, ".id.txt").read_text() - - def version(self, project_id: str, identifier: str) -> int: - """Return table ``identifier``'s version: ``0`` before the first write.""" - return int(self._path(project_id, identifier, ".version.txt").read_text()) - - def kv(self, project_id: str, identifier: str) -> dict[str, bytes]: - """Return table ``identifier``'s key-value metadata.""" - raw = json.loads(self._path(project_id, identifier, ".kv.json").read_text()) - return {k: bytes.fromhex(v) for k, v in raw.items()} - - def set_kv(self, project_id: str, identifier: str, kv: dict[str, bytes]) -> None: - """Upsert ``kv`` into table ``identifier``'s key-value metadata.""" - current = self.kv(project_id, identifier) - current.update(kv) - self._path(project_id, identifier, ".kv.json").write_text( - json.dumps({k: v.hex() for k, v in current.items()}) - ) - - def drop_kv(self, project_id: str, identifier: str, keys: list[str]) -> None: - """Remove ``keys`` from table ``identifier``'s key-value metadata.""" - current = self.kv(project_id, identifier) - for key in keys: - current.pop(key, None) - self._path(project_id, identifier, ".kv.json").write_text( - json.dumps({k: v.hex() for k, v in current.items()}) - ) - - -@dataclass(frozen=True) -class TableResource: - """What ``Project.list_tables()`` returns per table.""" - - id: str - project_id: str - dataset: str - table: str - - -class FakeSchema: - """What ``Table.schema()`` returns: a wrapper whose ``to_arrow()`` gives the schema.""" - - def __init__(self, schema: pa.Schema) -> None: - """Wrap ``schema``.""" - self._schema = schema - - def to_arrow(self) -> pa.Schema: - """Return the stored Arrow schema.""" - return self._schema - - -class FakeExpr: - """The result of ``Table.select()``: names the table to scan.""" - - def __init__(self, table: FakeTable) -> None: - """Name ``table`` as the table to scan.""" - self.table = table - - -class FakePredicate: - """A ``where`` expression: every named column equals its value.""" - - def __init__(self, equalities: list[tuple[str, Any]]) -> None: - """Hold the ``(column, value)`` pairs a row must all match.""" - self.equalities = equalities - - def __and__(self, other: FakePredicate) -> FakePredicate: - """Return a predicate requiring this one's equalities and ``other``'s.""" - return FakePredicate(self.equalities + other.equalities) - - def __repr__(self) -> str: - """Return the equalities as ``name == value`` terms joined by ``&``.""" - return " & ".join(f"{name} == {value!r}" for name, value in self.equalities) - - -class FakeColumn: - """What ``table[name]`` returns: compare it with ``==`` to get a predicate.""" - - def __init__(self, name: str) -> None: - """Name the column ``name``.""" - self._name = name - - def __eq__(self, value: object) -> FakePredicate: # pyright: ignore[reportIncompatibleMethodOverride] # as pyspiral's Expr does - """Return the predicate that this column equals ``value``.""" - return FakePredicate([(self._name, value)]) - - __hash__ = None # pyright: ignore[reportAssignmentType] # an expression, not a value - - -class FakeScan: - """What ``Spiral.scan(table.select(), where=..., limit=...)`` returns.""" - - def __init__( - self, - table: FakeTable, - record: ScanRecord, - where: FakePredicate | None, - limit: int | None, - ) -> None: - """Prepare a scan of ``table``; no row is read until rows are asked for. - - Args: - table: The table to scan. - record: The ``scan_log`` entry that counts the batches handed out. - where: The equalities a row must match, or ``None`` for every row. - limit: The most rows to return, or ``None`` for no limit. - """ - self._table = table - self._record = record - self._where = where - self._limit = limit - - def _rows(self) -> pa.Table: - """Return the rows matching ``where``, cut to ``limit``, in key order.""" - rows = self._table._read_all() - for name, value in self._where.equalities if self._where else []: - rows = rows.filter( - pc.equal( - rows.column(name), pa.scalar(value, rows.schema.field(name).type) - ) - ) - return rows if self._limit is None else rows.slice(0, self._limit) - - def to_table(self) -> pa.Table: - """Return the scanned rows, in key order.""" - return self._rows() - - def to_record_batches(self, **kwargs: Any) -> pa.RecordBatchReader: - """Return the rows in key order, ``scan_batch_rows`` per batch, read on demand.""" - rows = self._rows() - - def batches() -> Iterator[pa.RecordBatch]: - # SpiralDB yields more than one batch for larger tables; split to exercise that. - """Yield ``rows`` in batches, counting each in the scan record.""" - for batch in rows.to_batches(max_chunksize=scan_batch_rows): - self._record.batches_read += 1 - yield batch - - return pa.RecordBatchReader.from_batches(rows.schema, batches()) - - -class FakeTable: - """A stored table: key schema, Arrow schema, key-value metadata and upserting writes. - - Args: - store: The directory-backed store. - project_id: The project the table belongs to. - identifier: ``".
"``. - - Raises: - ValueError: If the table does not exist. - """ - - def __init__(self, store: _Store, project_id: str, identifier: str) -> None: - """Open table ``identifier`` of ``project_id`` in ``store``.""" - if not store.exists(project_id, identifier): - raise ValueError(f"Table not found: {project_id}.{identifier}") - self._store = store - self._project_id = project_id - self._identifier = identifier - - @property - def key_schema(self) -> pa.Schema: - """The key columns, in key order.""" - return self._store.key_schema(self._project_id, self._identifier) - - @property - def table_id(self) -> str: - """The table's own id: kept on rename, new when the table is recreated.""" - return self._store.table_id(self._project_id, self._identifier) - - @property - def core(self) -> Any: - """The table's low-level handle; only ``get_snapshot`` is modelled.""" - return types.SimpleNamespace(get_snapshot=lambda asof=None: self) - - def last_modified_at(self) -> int: - """Return the table's version: ``0`` before the first write.""" - return self._store.version(self._project_id, self._identifier) - - def __getitem__(self, name: str) -> FakeColumn: - """Return the column expression ``table[name]``.""" - return FakeColumn(name) - - def schema(self) -> FakeSchema: - """Return the stored schema (only the key columns before the first write).""" - stored = self._store.read(self._project_id, self._identifier) - keys = self.key_schema - if stored is None: - return FakeSchema(keys) - return FakeSchema(stored.schema) - - def select(self, *paths: str, exclude: list[str] | None = None) -> FakeExpr: - """Return an expression selecting the whole table (projections are not modelled).""" - if paths or exclude: - raise NotImplementedError("fake Table.select supports only select()") - return FakeExpr(self) - - def get_metadata(self) -> dict[str, bytes]: - """Return the table's key-value metadata.""" - return self._store.kv(self._project_id, self._identifier) - - def set_metadata(self, metadata: dict[str, bytes]) -> None: - """Upsert ``metadata`` into the table's key-value metadata. - - Enforces the limits pyspiral 0.16.33 documents for ``Table.set_metadata``: str keys - and bytes values, a key + value pair of at most 8 KiB, keys of at most 255 - characters, and at most 1024 entries per table. - - Raises: - TypeError: If a key is not ``str`` or a value not ``bytes``. - ValueError: If a limit is exceeded. - """ - for k, v in metadata.items(): - if not isinstance(k, str) or not isinstance(v, bytes): - raise TypeError("metadata keys must be str and values bytes") - if len(k) > _MAX_KEY_CHARS: - raise ValueError(f"metadata key {k[:40]!r}... exceeds 255 characters") - if len(k.encode()) + len(v) > _MAX_PAIR_BYTES: - raise ValueError(f"metadata entry {k!r} exceeds 8 KiB") - current = self._store.kv(self._project_id, self._identifier) - if len({*current, *metadata}) > _MAX_ENTRIES: - raise ValueError("a table can have at most 1024 metadata entries") - self._store.set_kv(self._project_id, self._identifier, metadata) - - def drop_metadata(self, keys: list[str]) -> None: - """Remove ``keys`` from the table's key-value metadata; absent keys are ignored.""" - self._store.drop_kv(self._project_id, self._identifier, keys) - - def write( - self, table: pa.Table, push_down_nulls: bool = False, **kwargs: Any - ) -> None: - """Store ``table`` the way SpiralDB does: transform types, then upsert by key. - - Args: - table: The rows to write; every key column must be present. - push_down_nulls: Accept null struct values (SpiralDB's own flag). - **kwargs: Accepted for signature compatibility; unused. - - Raises: - ValueError: If a key column is missing, a column name is one SpiralDB - reserves (a ``.`` anywhere, or a ``__`` prefix on a value column), a - struct value is null without ``push_down_nulls``, or the column set - differs from the stored table (live SpiralDB adds a new column: the - fake does not model it). - """ - b = self._store.behaviour - keys = self.key_schema - missing = [k for k in keys.names if k not in table.column_names] - if missing: - raise ValueError(f"write is missing key columns {missing}") - for name in table.column_names: - # SpiralDB's own refusals, with its messages as observed live (ITL-1164). - if "." in name: - raise ValueError(f"Column '{name}' contains a reserved dot-separator") - if name.startswith("__") and name not in keys.names: - raise ValueError( - f"Column name '{name}' has reserved prefix: column group columns " - "must not start with '__'" - ) - if b.reject_struct_nulls and not push_down_nulls: - for name in table.column_names: - if _has_struct_nulls(table.column(name)): - raise ValueError( - f"SpiralDB does not allow struct-level nulls (column {name!r}); " - "write with push_down_nulls=True" - ) - fields = [] - arrays = [] - for f in table.schema: - col = table.column(f.name) - if push_down_nulls: - col = _push_down_struct_nulls(col) - if b.server_nullability: - # Arrow validates the outgoing batch on the client (live, ITL-936). - if not f.nullable and col.null_count: - raise ValueError( - f"Column {f.name!r} is declared as non-nullable but contains " - "null values" - ) - col = _zero_struct_field_nulls(col, f.type) - sf = _stored_field(f, b, nullable=b.server_nullability or None) - if isinstance(f.type, pa.ExtensionType): - col = pa.chunked_array( - [cast("pa.ExtensionArray[Any]", c).storage for c in col.chunks] - ) - if pa.types.is_dictionary(col.type) and b.decode_dictionaries: - col = col.cast(col.type.value_type) - fields.append(sf) - arrays.append(_cast_storage(col, sf.type)) - incoming = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) - # SpiralDB matches a write's columns by name and stores them in its own - # order, whatever the order written: the key columns in key-schema order, - # then the value columns sorted by name, by code point (observed live, - # ITL-1367). Struct children are sorted live too; the fake keeps them as - # written (struct field order: ITL-1368). - values = sorted(n for n in incoming.column_names if n not in keys.names) - incoming = incoming.select([*keys.names, *values]) - existing = self._store.read(self._project_id, self._identifier) - if existing is not None: - if existing.schema.names != incoming.schema.names: - raise ValueError( - "fake SpiralDB: column set differs from existing table" - ) - # Column by column, only where the type changes: pyarrow refuses to cast a - # fixed-size list with non-null items to its own type when a null row - # hides null item slots (ITL-1334). - incoming = pa.Table.from_arrays( - [ - column if column.type == field.type else column.cast(field.type) - for column, field in zip(incoming.columns, existing.schema) - ], - schema=existing.schema, - ) - if not keys.names: - incoming = pa.concat_tables([existing, incoming]) - else: - incoming = _upsert(existing, incoming, keys.names) - if keys.names: - incoming = incoming.sort_by([(k, "ascending") for k in keys.names]) - self._store.write(self._project_id, self._identifier, incoming.combine_chunks()) - - def _read_all(self) -> pa.Table: - """Return every stored row (an empty key-only table before the first write).""" - stored = self._store.read(self._project_id, self._identifier) - if stored is None: - keys = self.key_schema - return keys.empty_table() - return stored - - -def _upsert(existing: pa.Table, incoming: pa.Table, key_names: list[str]) -> pa.Table: - """Replace existing rows whose key appears in ``incoming`` and append the rest.""" - new_keys = set(zip(*(incoming.column(k).to_pylist() for k in key_names))) - keep = pa.array( - [ - k not in new_keys - for k in zip(*(existing.column(k).to_pylist() for k in key_names)) - ], - type=pa.bool_(), - ) - return pa.concat_tables([existing.filter(keep), incoming]) - - -def _cast_storage( - col: pa.ChunkedArray[Any], target: pa.DataType -) -> pa.ChunkedArray[Any]: - """Cast ``col`` to the stored type ``target``, keeping the UTC instant of a timestamp.""" - if col.type == target: - return col - if pa.types.is_timestamp(col.type) and pa.types.is_timestamp(target): - # dropping the tz keeps the UTC instant (what SpiralDB was seen to do) - return pc.cast(col, pa.timestamp(col.type.unit, tz="UTC")).cast(target) - if pa.types.is_map(col.type) and pa.types.is_map(target): - # pyarrow 23 aborts the process (not an exception) casting some map arrays - # ("Map array keys array should have no nulls"), so a map is rebuilt from its - # parts: offsets, keys and items cast on their own, validity kept (ITL-1334). - # (cast: pyarrow's stubs type ``chunked_array``'s ``type`` too narrowly.) - return pa.chunked_array( - [_cast_map_chunk(chunk, target) for chunk in col.chunks], - type=cast(Any, target), - ) - return col.cast(target) - - -def _cast_map_chunk(chunk: Any, target: Any) -> Any: - """Return the map array ``chunk`` with its keys and items cast to ``target``'s.""" - keys = _cast_storage(pa.chunked_array([chunk.keys]), target.key_type) - items = _cast_storage(pa.chunked_array([chunk.items]), target.item_type) - return pa.MapArray.from_arrays( - chunk.offsets, - keys.combine_chunks(), - items.combine_chunks(), - type=target, - mask=chunk.is_null() if chunk.null_count else None, - ) - - -class FakeProject: - """What ``Spiral.project(id)`` returns: list, open, create and drop tables.""" - - def __init__(self, store: _Store, project_id: str) -> None: - """Bind project ``project_id`` in ``store``.""" - self._store = store - self._project_id = project_id - - def list_tables(self) -> list[TableResource]: - """Return every table of the project, in every dataset.""" - return self._list_tables() - - def _list_tables( - self, dataset: str | None = None, table: str | None = None - ) -> list[TableResource]: - """Apply the SDK's project API filters, which omit empty values.""" - out = [] - for ident in self._store.identifiers(self._project_id): - found_dataset, _, found_table = ident.partition(".") - if (dataset and dataset != found_dataset) or ( - table and table != found_table - ): - continue - table_id = self._store.table_id(self._project_id, ident) - out.append( - TableResource(table_id, self._project_id, found_dataset, found_table) - ) - return out - - def table(self, identifier: str) -> FakeTable: - """Parse and resolve a name as pyspiral does, including omitted filters.""" - parts = identifier.split(".") - if len(parts) == 1: - dataset, table = "default", parts[0] - elif len(parts) == 2: - dataset, table = parts - else: - raise ValueError( - f"Invalid table identifier: {self._project_id}.{identifier}" - ) - resources = self._list_tables(dataset, table) - if not resources: - raise ValueError(f"Table not found: {self._project_id}.{dataset}.{table}") - resolved = resources[0] - return FakeTable( - self._store, self._project_id, f"{resolved.dataset}.{resolved.table}" - ) - - def create_table( - self, - identifier: str, - *, - key_schema: Any, - root_uri: Any = None, - exist_ok: bool = False, - ) -> FakeTable: - """Create the table ``".
"`` with ``key_schema`` and open it. - - Key columns are stored the way SpiralDB stores them, nullable under - ``server_nullability`` however they were declared. - - Args: - identifier: ``".
"``. - key_schema: An Arrow schema, or ``(name, type)`` pairs as pyspiral accepts. - root_uri: Accepted for signature compatibility; unused. - exist_ok: Open an existing table instead of raising. - - Returns: - The new table, or with ``exist_ok`` the existing one. - - Raises: - ValueError: If the table exists and ``exist_ok`` is false. - """ - if self._store.exists(self._project_id, identifier): - if not exist_ok: - raise ValueError(f"Table already exists: {identifier}") - return self.table(identifier) - if isinstance(key_schema, pa.Schema): - schema = key_schema - else: - schema = pa.schema([pa.field(n, t, True) for n, t in key_schema]) - b = self._store.behaviour - # SpiralDB reports key columns nullable however they were declared (ITL-936). - schema = pa.schema( - [ - pa.field( - f.name, - _stored_type(f.type, b), - True if b.server_nullability else f.nullable, - ) - for f in schema - ] - ) - self._store.create(self._project_id, identifier, schema) - return self.table(identifier) - - def drop_table(self, identifier: str) -> None: - """Drop the table ``".
"`` if it exists.""" - self._store.drop(self._project_id, identifier) - - -class FakeSpiral: - """Stands in for ``spiral.Spiral``; tables live under ``FAKE_SPIRAL_ROOT``. - - Args: - config: Accepted for signature compatibility; unused. - overrides: Recorded; unused. - - Raises: - RuntimeError: If ``FAKE_SPIRAL_ROOT`` is not set (use ``install``). - """ - - def __init__( - self, *, config: Any = None, overrides: dict[str, str] | None = None - ) -> None: - """Open the database under ``FAKE_SPIRAL_ROOT`` and record ``overrides``.""" - root = os.environ.get(_ROOT_ENV) - if not root: - raise RuntimeError(f"{_ROOT_ENV} is not set; call fake_pyspiral.install()") - self._store = _Store(Path(root)) - self.overrides = overrides - - def project(self, project_id: str) -> FakeProject: - """Return project ``project_id`` (created on first use).""" - return FakeProject(self._store, project_id) - - def scan(self, *projections: Any, **kwargs: Any) -> FakeScan: - """Return a scan of one ``table.select()``, restricted by ``where`` and ``limit``. - - Every call is appended to ``scan_log``. ``asof`` is accepted and recorded; the - fake keeps one version of a table. Other projections and ``key_ranges`` are - not modelled. - """ - if len(projections) != 1 or not isinstance(projections[0], FakeExpr): - raise NotImplementedError( - "fake Spiral.scan supports only scan(table.select())" - ) - unsupported = {k for k, v in kwargs.items() if v is not None} - { - "where", - "limit", - "asof", - } - if unsupported: - raise NotImplementedError(f"fake Spiral.scan: {sorted(unsupported)}") - table = projections[0].table - record = ScanRecord(table._identifier, dict(kwargs)) - scan_log.append(record) - return FakeScan(table, record, kwargs.get("where"), kwargs.get("limit")) - - @property - def core(self) -> Any: - """The client's low-level handle; only ``manifest_stats`` is modelled.""" - - return types.SimpleNamespace(manifest_stats=self.manifest_stats) - - def manifest_stats(self, snapshot: FakeTable) -> Any: - """Return stats whose ``key_space_stats.total_rows`` counts rows.""" - rows = snapshot._read_all().num_rows - return types.SimpleNamespace( - key_space_stats=types.SimpleNamespace(total_rows=rows) - ) - - -fake_spiral_module = types.SimpleNamespace(Spiral=FakeSpiral) - - -def write_behaviour(root: Path, behaviour: StorageBehaviour) -> None: - """Persist ``behaviour`` so every process using ``root`` applies it.""" - root.mkdir(parents=True, exist_ok=True) - (root / _BEHAVIOUR_FILE).write_text(json.dumps(asdict(behaviour))) - - -@contextmanager -def install(root: Path | str): - """Route ``SpiralDBConnector`` to the fake, with tables stored under ``root``.""" - with ( - patch.dict(os.environ, {_ROOT_ENV: str(root)}), - patch("orcapod.databases.spiraldb_connector.sp", fake_spiral_module), - ): - yield diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py new file mode 100644 index 000000000..5b9e13d61 --- /dev/null +++ b/tests/test_databases/fake_spiral_sdk.py @@ -0,0 +1,1034 @@ +"""A disk-backed fake of the spiral-sdk surface that Orcapod uses (ITL-1186). + +It stores real Arrow tables, every version of each, and returns them the way the service +does, so a connector or source on it goes through the code a live project uses. The same +conformance tests run on it and, opt-in, on the service +(``test_spiraldb_conformance.py``). + +Each rule of ``RULES`` was seen on the service with spiral-sdk 0.16.74 and 0.16.75 on +November 24, 2026, on throwaway tables, unless it says otherwise; its name is cited where +the rule is applied. +""" + +from __future__ import annotations + +import json +import math +import os +import types +import urllib.parse +import uuid +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE + +RULES = { + "missing": "a missing table or dataset: SpiralError 'resource not found: " + "..' and nothing more", + "id": "every table has its own id; a recreated one gets a new id", + "version-0": "a table never written has version '0' and its key columns only", + "asof": "asof gives the newest version not after it; before the first write the key " + "columns only, with version_id the asof itself", + "create-409": "create with exist_ok of a table with another key, or without exist_ok " + "of an existing one: SpiralError with 'status 409' only", + "create-key-types": "a key of a timestamp, date, decimal or fixed-size binary type " + "cannot be created (ValueError); a table pyspiral created with one is read", + "names": "an empty name is a ValueError; more than 255 characters 'status 400'", + "key-flag": "key columns read nullable however they were declared", + "types": "strings, binaries and lists read in their small variants; a dictionary and " + "a run-end encoding as their values; decimal32/64 as decimal128; a map loses " + "keys_sorted and has fields 'key' and 'value'; a time zone is kept", + "flags": "top-level columns and struct fields read nullable; a list item keeps the " + "flag of the first write", + "metadata": "schema and field metadata is dropped", + "order": "key columns in key order, then value columns: non-structs by name, then " + "structs by name; the same for the fields of a struct outside a list", + "stage": "a write is validated when staged; nothing shows before finish", + "zero-rows": "staging no rows and finishing publishes nothing", + "upsert": "rows replace those of their key column by column: a column the write " + "lacks keeps its value; a new column is added, null in older rows", + "dup": "a repeated key in one batch is refused; across batches the last wins", + "null-key": "a null key is refused", + "key-only": "a write without a value column is refused", + "no-key": "a write without a key column is refused", + "reserved": "a value column starting with '__' or '$', or any with '.', is refused", + "nul": "a column name is cut at a NUL character", + "type-conflict": "a column of another type than stored is refused", + "unsupported": "duration, interval, fixed-size binary, union, an empty struct and a " + "null struct outside a list are refused", + "non-null": "a null in a column, struct field or list item declared or stored " + "non-null is refused", + "literal": "a literal must have the column's exact type (large_string is none)", + "float-eq": "0.0 does not equal -0.0, and NaN equals NaN", + "rows": "rows come in key order; filter before limit", + "list": "the documented listing filters a dataset and pages; a page can be empty " + "(documented, not seen)", +} + +_ROOT_ENV = "FAKE_SPIRAL_SDK_ROOT" +_API_URL = "https://api.fake.invalid" + + +class SpiralError(Exception): + """Stands in for ``spiral.SpiralError``.""" + + +def _refuse(message: str) -> SpiralError: + """Return the error the service gives for an invalid argument.""" + return SpiralError(f"Scandal:InvalidArgument (message: Runtime Error: {message})") + + +def _status(code: int) -> SpiralError: + """Return the error the service gives when it hides the response's body.""" + return SpiralError(f"remote service returned an unknown error (status {code})") + + +@dataclass +class ScanRecord: + """One scan: its table and version, its arguments, and the batches handed out.""" + + identifier: str + version: int + columns: list[str] | None + filter: Any + limit: int | None + batches_read: int = 0 + closed: bool = False + + @property + def kwargs(self) -> dict[str, Any]: + """The scan's restriction: ``where``, ``limit`` and the version (``asof``).""" + return {"where": self.filter, "limit": self.limit, "asof": self.version} + + +# Every scan of a user's table read in this process, oldest first. Tests clear and read it. +scan_log: list[ScanRecord] = [] +# Every count: a scan of some columns only. +count_log: list[ScanRecord] = [] +# Every read of a schema table's rows. +schema_scan_log: list[ScanRecord] = [] +# Rows per batch a scan hands out (the service's batches follow its stored fragments). +scan_batch_rows = 2 +# Tables per page of the listing. +list_page_size = 3 + + +# --------------------------------------------------------------------------- what is stored + + +def _order(fields: list[pa.Field[Any]]) -> list[pa.Field[Any]]: + """Order fields as the service does (rule ``order``).""" + return sorted(fields, key=lambda f: (pa.types.is_struct(f.type), f.name)) + + +def _stored_type(t: pa.DataType, *, in_list: bool = False) -> pa.DataType: + """Return the type a column written as ``t`` reads back with (``types``, ``flags``).""" + if isinstance(t, pa.BaseExtensionType): + return _stored_type(t.storage_type, in_list=in_list) + if pa.types.is_dictionary(t) or pa.types.is_run_end_encoded(t): + return _stored_type(t.value_type, in_list=in_list) + if pa.types.is_decimal32(t) or pa.types.is_decimal64(t): + return pa.decimal128(t.precision, t.scale) + if pa.types.is_large_string(t) or pa.types.is_string_view(t): + return pa.string() + if pa.types.is_large_binary(t) or pa.types.is_binary_view(t): + return pa.binary() + if pa.types.is_struct(t): + fields = [ + pa.field(f.name, _stored_type(f.type, in_list=in_list)) + for f in (t.field(i) for i in range(t.num_fields)) + ] + return pa.struct(fields if in_list else _order(fields)) + if pa.types.is_map(t): + item = t.item_field + make: Any = pa.map_ # pyarrow takes an item field; its stubs list only types + return make( + _stored_type(t.key_type, in_list=True), + pa.field("value", _stored_type(item.type, in_list=True), item.nullable), + ) + if pa.types.is_fixed_size_list(t): + return pa.list_(_stored_item(t), t.list_size) + if pa.types.is_list(t) or pa.types.is_large_list(t): + return pa.list_(_stored_item(t)) + return t + + +def _stored_item(t: Any) -> pa.Field[Any]: + """Return the stored item field of a list type.""" + item = t.value_field + return pa.field(item.name, _stored_type(item.type, in_list=True), item.nullable) + + +def _refused_type(t: pa.DataType) -> str | None: + """Return why a column of type ``t`` cannot be written (``unsupported``).""" + if isinstance(t, pa.BaseExtensionType): + return _refused_type(t.storage_type) + if ( + pa.types.is_duration(t) + or pa.types.is_interval(t) + or pa.types.is_fixed_size_binary(t) + or pa.types.is_union(t) + ): + return f"Array encoding not implemented for Arrow data type {t}" + if pa.types.is_struct(t): + if t.num_fields == 0: + return "column group is empty" + for i in range(t.num_fields): + if (why := _reserved(t.field(i).name)) is not None: + return why + if pa.types.is_dictionary(t) or pa.types.is_run_end_encoded(t): + return None + for i in range(t.num_fields): + if (why := _refused_type(t.field(i).type)) is not None: + return why + return None + + +def _reserved(name: str) -> str | None: + """Return the refusal of a reserved column name (``reserved``).""" + if name.startswith(("__", "$")) or "." in name: + return f'Column name "{name}" is reserved' + return None + + +def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: + """Return ``array`` as it is stored, of type ``target``. + + Rebuilt from its parts where a cast would not do (structs whose fields are reordered, + maps), so every value and every null is kept. + + Args: + array: The array written. + target: ``_stored_type`` of its type, or the type already stored. + """ + a: Any = array + if isinstance(a, pa.ExtensionArray): + a = a.storage + if pa.types.is_dictionary(a.type): + a = a.dictionary_decode() + if pa.types.is_run_end_encoded(a.type): + a = cast(Any, pc).run_end_decode(a) + if a.type == target: + return a + t: Any = target + if pa.types.is_struct(t): + children = [ + _stored_array(a.field(t.field(i).name), t.field(i).type) + for i in range(t.num_fields) + ] + return pa.StructArray.from_arrays( + children, fields=list(t), mask=a.is_null() if a.null_count else None + ) + if pa.types.is_map(t): + return cast(Any, pa.MapArray).from_arrays( + a.offsets, + _stored_array(a.keys, t.key_type), + _stored_array(a.items, t.item_type), + type=t, + mask=a.is_null() if a.null_count else None, + ) + if pa.types.is_list(t) and ( + pa.types.is_list(a.type) or pa.types.is_large_list(a.type) + ): + offsets = a.offsets.cast(pa.int32()) + return pa.ListArray.from_arrays( + offsets, + _stored_array(a.values, t.value_type), + type=t, + mask=a.is_null() if a.null_count else None, + ) + if pa.types.is_fixed_size_list(t): + values = _stored_array( + a.values.slice(a.offset * t.list_size, len(a) * t.list_size), t.value_type + ) + return cast(Any, pa.FixedSizeListArray).from_arrays( + values, type=t, mask=a.is_null() if a.null_count else None + ) + return a.cast(target) + + +def _check_nulls(array: Any, field: pa.Field[Any], *, in_list: bool) -> None: + """Refuse a null where the written type has none, or a null struct (``non-null``, + ``unsupported``). + + Args: + array: The array. + field: The field it was written under. + in_list: Whether it is inside a list, where a null struct is kept. + """ + if isinstance(array, pa.ExtensionArray): + array = array.storage + if not field.nullable and array.null_count: + raise SpiralError( + f"Column '{field.name}' is declared as non-nullable but contains null values" + ) + t: Any = array.type + if pa.types.is_struct(t): + if array.null_count and not in_list: + raise _refuse(f"Column group {field.name} contains null rows") + for i in range(t.num_fields): + _check_nulls(array.field(i), t.field(i), in_list=in_list) + elif pa.types.is_list(t) or pa.types.is_large_list(t): + _check_nulls(array.flatten(), t.value_field, in_list=True) + elif pa.types.is_fixed_size_list(t): + _check_nulls(array.flatten(), t.value_field, in_list=True) + + +def _bits(value: Any) -> Any: + """Return ``value`` so that ``==`` compares it as the service does (``float-eq``).""" + if isinstance(value, float): + return "nan" if math.isnan(value) else (value, math.copysign(1.0, value)) + return value + + +# ------------------------------------------------------------------------------- the store + + +class _Store: + """Directory-backed tables, shared by every fake object.""" + + def __init__(self, root: Path) -> None: + """Open the store under ``root``.""" + self.root = root + root.mkdir(parents=True, exist_ok=True) + + def tables(self) -> list[dict[str, Any]]: + """Return every table's description.""" + return [ + json.loads(p.read_text()) + for p in sorted(self.root.glob("table_*/table.json")) + ] + + def find(self, project: str, dataset: str, name: str) -> dict[str, Any] | None: + """Return the table of that name, or ``None``.""" + for table in self.tables(): + if (table["project"], table["dataset"], table["name"]) == ( + project, + dataset, + name, + ): + return table + return None + + def by_id(self, table_id: str) -> dict[str, Any]: + """Return the table with ``table_id`` (``id``).""" + path = self.root / table_id / "table.json" + if not path.exists(): + raise _status(404) + return json.loads(path.read_text()) + + def create( + self, project: str, dataset: str, name: str, key_schema: pa.Schema + ) -> dict[str, Any]: + """Create a table (``id``, ``key-flag``).""" + table_id = f"table_{uuid.uuid4().hex[:12]}" + folder = self.root / table_id + folder.mkdir() + keys = pa.schema([pa.field(f.name, _stored_type(f.type)) for f in key_schema]) + (folder / "keys.arrow").write_bytes(keys.serialize().to_pybytes()) + table = { + "id": table_id, + "project": project, + "dataset": dataset, + "name": name, + "keys": keys.names, + } + (folder / "table.json").write_text(json.dumps(table)) + return table + + def drop(self, table_id: str) -> None: + """Remove a table and every version of it.""" + folder = self.root / table_id + for path in folder.iterdir(): + path.unlink() + folder.rmdir() + + def keys(self, table_id: str) -> pa.Schema: + """Return a table's key schema.""" + raw = (self.root / table_id / "keys.arrow").read_bytes() + return pa.ipc.read_schema(pa.py_buffer(raw)) + + def versions(self, table_id: str) -> list[int]: + """Return a table's versions, oldest first.""" + return sorted(int(p.stem[1:]) for p in (self.root / table_id).glob("v*.arrow")) + + def read(self, table_id: str, version: int) -> pa.Table: + """Return a table's rows at ``version`` (``version-0``, ``asof``).""" + existing = [v for v in self.versions(table_id) if v <= version] + if not existing: + return self.keys(table_id).empty_table() + path = self.root / table_id / f"v{existing[-1]}.arrow" + with pa.ipc.open_file(pa.memory_map(str(path))) as reader: + return reader.read_all() + + def write(self, table_id: str, rows: pa.Table) -> int: + """Store ``rows`` as a table's next version.""" + if not (self.root / table_id).exists(): + raise _status(404) + version = max([0, *self.versions(table_id)]) + 1 + with pa.ipc.new_file( + str(self.root / table_id / f"v{version}.arrow"), rows.schema + ) as writer: + writer.write_table(rows) + return version + + +def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: + """Validate ``rows`` and return them as they are stored (``stage``).""" + names = [name.split("\0")[0] for name in rows.column_names] # nul + rows = rows.rename_columns(names) + for key in keys: + if key not in names: + raise _refuse(f"Input batch is missing key field '{key}'") + if rows.column(key).null_count: + raise _refuse(f"Key field '{key}' contains null values") + if set(names) <= set(keys): + raise _refuse("Write contains no data columns") + tuples = list(zip(*(rows.column(k).to_pylist() for k in keys))) + if len(set(tuples)) != len(tuples): + raise _refuse("Duplicate keys found in input batch") + fields, arrays = [], [] + for field in rows.schema: + why = None if field.name in keys else _reserved(field.name) + why = why or _refused_type(field.type) + if why is not None: + raise _refuse(why) + array: Any = pa.concat_arrays( + rows.column(field.name).chunks or [pa.array([], field.type)] + ) + _check_nulls(array, field, in_list=False) + target = _stored_type(field.type) + if field.name in stored.names: + kept = stored.field(field.name).type + if _without_flags(kept) != _without_flags(target): + raise _refuse( + f"cannot unify incompatible data types: {kept} and {target}" + ) + _check_nulls(array, pa.field(field.name, kept), in_list=False) + _check_stored_items(array, kept) + target = kept + fields.append(pa.field(field.name, target)) + arrays.append(_stored_array(array, target)) + return pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + + +def _check_stored_items(array: Any, stored: Any) -> None: + """Refuse a null list item where the stored item is non-null (``non-null``).""" + if isinstance(array, pa.ExtensionArray): + array = array.storage + if pa.types.is_list(stored) or pa.types.is_fixed_size_list(stored): + items = array.flatten() + if not stored.value_field.nullable and items.null_count: + raise SpiralError("Vortex error: Cannot cast AllInvalid to NonNullable") + _check_stored_items(items, stored.value_type) + elif pa.types.is_struct(stored): + for i in range(stored.num_fields): + _check_stored_items(array.field(stored.field(i).name), stored.field(i).type) + + +def _without_flags(t: pa.DataType) -> pa.DataType: + """Return ``t`` with every nested field nullable.""" + if pa.types.is_struct(t): + return pa.struct( + [ + (t.field(i).name, _without_flags(t.field(i).type)) + for i in range(t.num_fields) + ] + ) + if pa.types.is_fixed_size_list(t): + return pa.list_(_without_flags(t.value_type), t.list_size) + if pa.types.is_list(t): + return pa.list_(_without_flags(t.value_type)) + if pa.types.is_map(t): + return pa.map_(_without_flags(t.key_type), _without_flags(t.item_type)) + return t + + +def _upserted(stored: pa.Table, rows: pa.Table, keys: list[str]) -> pa.Table: + """Return ``stored`` with ``rows`` upserted, in key order (``upsert``, ``order``).""" + fields = {f.name: f for f in (*stored.schema, *rows.schema)} + fields.update({f.name: f for f in stored.schema}) + values = _order([f for name, f in fields.items() if name not in keys]) + schema = pa.schema([*(fields[k] for k in keys), *values]) + + def key_of(table: pa.Table) -> list[tuple[Any, ...]]: + return list(zip(*(table.column(k).to_pylist() for k in keys))) + + old = {key: i for i, key in enumerate(key_of(stored))} + new = {key: i for i, key in enumerate(key_of(rows))} + # Python's order of these key values is the service's: text by code point. + ordered = sorted({**old, **new}) + columns = [] + for field in schema: + parts: list[pa.Array[Any]] = [] + for table in (stored, rows): + column = ( + table.column(field.name).combine_chunks() + if field.name in table.column_names + else pa.nulls(table.num_rows, field.type) + ) + parts.append(cast("pa.Array[Any]", column)) + whole: Any = pa.concat_arrays( + [p if p.type == field.type else _stored_array(p, field.type) for p in parts] + ) + indices = [ + stored.num_rows + new[key] + if key in new and field.name in rows.column_names + else old.get(key) + for key in ordered + ] + columns.append(whole.take(pa.array(indices, pa.int64()))) + return pa.Table.from_arrays(columns, schema=schema) + + +# --------------------------------------------------------------------------- expressions + + +@dataclass(frozen=True) +class _Column: + """A column named in an expression.""" + + name: str + + +@dataclass(frozen=True) +class _Literal: + """A value with the exact Arrow type ``FakeKeyedTable.scan`` checks.""" + + value: Any + type: pa.DataType + + +@dataclass(frozen=True) +class FakePredicate: + """Equalities a row must all match.""" + + terms: tuple[tuple[str, _Literal], ...] + + @property + def equalities(self) -> list[tuple[str, Any]]: + """The ``(column, value)`` pairs, in the order given.""" + return [(name, wanted.value) for name, wanted in self.terms] + + def __repr__(self) -> str: + """Return the equalities as ``name == value`` terms joined by ``&``.""" + return " & ".join(f"{name} == {value!r}" for name, value in self.equalities) + + +def column(name: str) -> _Column: + """Stand in for ``spiral.column``.""" + return _Column(name) + + +def literal(value: Any, type: Any = None) -> _Literal: + """Stand in for ``spiral.literal`` (``literal``): an explicit scalar type.""" + if type is None or pa.types.is_large_string(type) or pa.types.is_large_binary(type): + raise TypeError(f"unsupported literal Arrow type {type}") + return _Literal(pa.scalar(value, type).as_py(), type) + + +def eq(left: _Column, right: _Literal) -> FakePredicate: + """Stand in for ``spiral.eq``.""" + return FakePredicate(((left.name, right),)) + + +def and_(left: FakePredicate, right: FakePredicate) -> FakePredicate: + """Stand in for ``spiral.and_``.""" + return FakePredicate(left.terms + right.terms) + + +# -------------------------------------------------------------------------------- the client + + +class FakeReader: + """Stands in for the reader of ``Scan.to_reader()``; a closed one gives no row.""" + + def __init__(self, rows: pa.Table, record: ScanRecord, batch_rows: int) -> None: + """Hold the parts it is made of.""" + self._batches = iter(rows.to_batches(max_chunksize=batch_rows)) + self._record = record + + def __iter__(self) -> Iterator[pa.RecordBatch]: + """Yield the batches until there is none.""" + while True: + try: + yield self.read_next_batch() + except StopIteration: + return + + def __next__(self) -> pa.RecordBatch: + """Return the next batch.""" + return self.read_next_batch() + + def read_next_batch(self) -> pa.RecordBatch: + """Return the next batch, or raise ``StopIteration``.""" + if self._record.closed: + raise SpiralError("the reader is closed") + batch = next(self._batches) + self._record.batches_read += 1 + return batch + + def close(self) -> None: + """Close the reader.""" + self._record.closed = True + + +class FakeScan: + """Stands in for ``spiral.tables.Scan``: rows are read when asked for.""" + + def __init__(self, rows: pa.Table, record: ScanRecord, batch_rows: int) -> None: + """Hold the parts it is made of.""" + self._rows, self._record, self._batch_rows = rows, record, batch_rows + + def to_reader(self) -> FakeReader: + """Return a reader of the rows, ``scan_batch_rows`` at most per batch.""" + log = ( + schema_scan_log + if self._record.identifier.endswith(f".{SCHEMA_TABLE}") + else (count_log if self._record.columns else scan_log) + ) + log.append(self._record) + return FakeReader(self._rows, self._record, self._batch_rows) + + def to_table(self) -> pa.Table: + """Return the rows.""" + batches = list(self.to_reader()) + return pa.Table.from_batches(batches, schema=self._rows.schema) + + +class FakeKeyedTable: + """Stands in for ``spiral.keyed_tables.KeyedTable``: one immutable snapshot.""" + + def __init__(self, store: _Store, table: dict[str, Any], version: int) -> None: + """Hold the parts it is made of.""" + self._store, self._table, self._version = store, table, version + + @property + def resource_id(self) -> str: + """The table's id (``id``).""" + return self._table["id"] + + @property + def version_id(self) -> str: + """The snapshot's version (``version-0``, ``asof``).""" + return str(self._version) + + @property + def key_columns(self) -> tuple[str, ...]: + """The key columns, in key order.""" + return tuple(self._table["keys"]) + + def schema(self) -> pa.Schema: + """Return the snapshot's schema.""" + return self._store.read(self.resource_id, self._version).schema + + def scan( + self, + columns: list[str] | None = None, + *, + filter: FakePredicate | None = None, + limit: int | None = None, + batch_rows: int | None = None, + ) -> FakeScan: + """Plan a scan (``rows``, ``literal``, ``float-eq``).""" + rows = self._store.read(self.resource_id, self._version) + for name, wanted in filter.terms if filter else (): + if rows.schema.field(name).type != wanted.type: + raise SpiralError( + "scan filter is unsupported: Comparison requires equal dtypes, got " + f"{rows.schema.field(name).type} and {wanted.type}" + ) + # Temporal values as their counts: a date64 may be off midnight. + stored: Any = rows.column(name) + given: Any = pa.array([wanted.value], wanted.type) + if pa.types.is_temporal(wanted.type): + width = pa.int32() if pa.types.is_date32(wanted.type) else pa.int64() + stored, given = stored.cast(width), given.cast(width) + values, (value,) = stored.to_pylist(), given.to_pylist() + rows = rows.filter( + pa.array( + [v is not None and _bits(v) == _bits(value) for v in values], + pa.bool_(), + ) + ) + if columns is not None: + rows = rows.select(columns) + if limit is not None: + rows = rows.slice(0, limit) + record = ScanRecord( + f"{self._table['dataset']}.{self._table['name']}", + self._version, + columns, + filter, + limit, + ) + size = ( + scan_batch_rows if batch_rows is None else min(batch_rows, scan_batch_rows) + ) + return FakeScan(rows, record, size) + + def append(self, data: pa.Table) -> FakeKeyedTable: + """Upsert rows and return the new snapshot.""" + writer = self.writer() + writer.append(data) + return writer.finish() + + def writer(self) -> FakeWriter: + """Begin a write.""" + return FakeWriter(self._store, self._table) + + +class FakeWriter: + """Stands in for ``spiral.keyed_tables.KeyedTableWrite``.""" + + def __init__(self, store: _Store, table: dict[str, Any]) -> None: + """Hold the parts it is made of.""" + self._store, self._table = store, table + self._parts: list[pa.Table] = [] + self._keys_to_delete: list[pa.Table] = [] + self._drop: list[str] = [] + self.aborted = False + + def append(self, data: pa.Table) -> None: + """Validate and stage rows (``stage``).""" + latest = self._latest() + self._parts.append(_staged(data, self._table["keys"], latest.schema)) + + def delete_keys(self, data: pa.Table) -> None: + """Stage the deletion of rows.""" + self._keys_to_delete.append(data) + + def alter_schema(self, changes: list[str]) -> None: + """Stage column drops (``drop_column`` gives the name here).""" + self._drop.extend(changes) + + def finish(self) -> FakeKeyedTable: + """Publish what was staged (``zero-rows``).""" + self._store.by_id(self._table["id"]) + keys = self._table["keys"] + rows = self._latest() + before = rows + for part in self._parts: + if part.num_rows: + rows = _upserted(rows, part, keys) + for dropped in self._keys_to_delete: + gone = set(zip(*(dropped.column(k).to_pylist() for k in keys))) + kept = [ + key not in gone + for key in zip(*(rows.column(k).to_pylist() for k in keys)) + ] + rows = rows.filter(pa.array(kept, pa.bool_())) + if self._drop: + rows = rows.drop_columns(self._drop) + if rows is not before: + self._store.write(self._table["id"], rows) + return _open(self._store, self._table, None) + + def abort(self) -> None: + """Close without publishing.""" + self.aborted = True + + def _latest(self) -> pa.Table: + """Return the table's latest rows.""" + self._store.by_id(self._table["id"]) + versions = self._store.versions(self._table["id"]) + return self._store.read(self._table["id"], max([0, *versions])) + + +def drop_column(name: str) -> str: + """Stand in for ``spiral.drop_column``.""" + return name + + +def _open(store: _Store, table: dict[str, Any], asof: int | None) -> FakeKeyedTable: + """Open a table at ``asof`` or its latest version (``asof``, ``version-0``).""" + versions = store.versions(table["id"]) + if asof is None: + version = max([0, *versions]) + else: + existing = [v for v in versions if v <= asof] + version = existing[-1] if existing else asof + return FakeKeyedTable(store, table, version) + + +class FakeProject: + """Stands in for ``spiral.projects.Project``.""" + + def __init__(self, store: _Store, project: str) -> None: + """Hold the parts it is made of.""" + self._store, self._project = store, project + + def create_keyed_table( + self, dataset: str, name: str, key_schema: pa.Schema, *, exist_ok: bool = False + ) -> FakeKeyedTable: + """Create a table (``create-409``, ``create-key-types``, ``names``).""" + if not dataset or not name: + raise ValueError("dataset and table names must be nonempty") + if len(name) > 255: + raise _status(400) + for field in key_schema: + t = field.type + if ( + pa.types.is_timestamp(t) + or pa.types.is_date(t) + or pa.types.is_decimal(t) + or pa.types.is_fixed_size_binary(t) + ): + raise ValueError( + f"Keyed creation does not support type {t} for key column " + f"'{field.name}'" + ) + table = self._store.find(self._project, dataset, name) + if table is not None: + asked = [(f.name, _stored_type(f.type)) for f in key_schema] + found = [(f.name, f.type) for f in self._store.keys(table["id"])] + if not exist_ok or asked != found: + raise _status(409) + return _open(self._store, table, None) + created = self._store.create(self._project, dataset, name, key_schema) + return _open(self._store, created, None) + + +class FakeClient: + """Stands in for ``spiral.Client``; tables live under the installed root.""" + + def __init__(self, *, api_url: str | None = None, token: str | None = None) -> None: + """Hold the parts it is made of.""" + self._store = _store() + self.api_url = api_url + self._native = types.SimpleNamespace( + api_url=api_url or _API_URL, access_token=lambda: "fake-token" + ) + + def project(self, id: str) -> FakeProject: + """Return a project, without a request.""" + return FakeProject(self._store, id) + + def keyed_table( + self, project: str, dataset: str, name: str, *, asof: int | None = None + ) -> FakeKeyedTable: + """Open a table by name (``missing``).""" + table = self._store.find(project, dataset, name) + if table is None: + raise SpiralError(f"resource not found: {project}.{dataset}.{name}") + return _open(self._store, table, asof) + + def keyed_table_by_id( + self, table_id: str, *, asof: int | None = None + ) -> FakeKeyedTable: + """Open a table by its id.""" + return _open(self._store, self._store.by_id(table_id), asof) + + +def _store() -> _Store: + """Return the installed store.""" + root = os.environ.get(_ROOT_ENV) + if not root: + raise RuntimeError(f"{_ROOT_ENV} is not set; call fake_spiral_sdk.install()") + return _Store(Path(root)) + + +def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]: + """Stand in for the documented listing endpoint (``list``): pages, the last but one + of them empty.""" + parts = urllib.parse.urlsplit(url) + query = dict(urllib.parse.parse_qsl(parts.query)) + assert token == "fake-token" + segments = [urllib.parse.unquote(s) for s in parts.path.split("/")] + assert ( + segments[1:4] == ["api", "keyed-tables", "projects"] and segments[5] == "tables" + ) + items = [ + {"table": t["name"], "dataset": t["dataset"], "id": t["id"]} + for t in _store().tables() + if t["project"] == segments[4] + and query.get("dataset", t["dataset"]) == t["dataset"] + ] + pages = [ + items[i : i + list_page_size] for i in range(0, len(items), list_page_size) + ] or [[]] + if len(pages) > 1: + pages.insert(-1, []) + index = int(query.get("pageToken", "0")) + page: dict[str, Any] = {"items": pages[index]} + if index + 1 < len(pages): + page["nextPageToken"] = str(index + 1) + return page + + +fake_module = types.SimpleNamespace( + Client=FakeClient, + SpiralError=SpiralError, + column=column, + literal=literal, + eq=eq, + and_=and_, + drop_column=drop_column, +) + + +# ------------------------------------------------------------------------ another program + + +class ExternalTable: + """A table as another program writes it: no row in the schema table.""" + + def __init__(self, store: _Store, table: dict[str, Any]) -> None: + """Hold the parts it is made of.""" + self._store, self._table = store, table + + @property + def table_id(self) -> str: + """The table's id.""" + return self._table["id"] + + def last_modified_at(self) -> int: + """Return the table's version.""" + return int(_open(self._store, self._table, None).version_id) + + def write(self, rows: pa.Table) -> None: + """Upsert rows.""" + _open(self._store, self._table, None).append(rows) + + def record(self, schema: pa.Schema) -> None: + """Migrate the dataset, with ``schema`` as what this table was written with.""" + migrate( + self._table["project"], + {self._table["name"]: schema}, + self._table["dataset"], + ) + + +class ExternalProject: + """A project as another program uses it: keys of any type (as pyspiral creates + them), and drops.""" + + def __init__(self, project: str) -> None: + """Hold the parts it is made of.""" + self._store, self._project = _store(), project + + def create_table(self, identifier: str, *, key_schema: Any) -> ExternalTable: + """Create ``".
"`` with a key schema or ``(name, type)`` pairs.""" + dataset, _, name = identifier.partition(".") + table = self._store.create(self._project, dataset, name, pa.schema(key_schema)) + return ExternalTable(self._store, table) + + def table(self, identifier: str) -> ExternalTable: + """Open ``".
"``.""" + dataset, _, name = identifier.partition(".") + table = self._store.find(self._project, dataset, name) + if table is None: + raise KeyError(identifier) + return ExternalTable(self._store, table) + + def drop_table(self, identifier: str) -> None: + """Drop ``".
"``; nothing if there is none.""" + dataset, _, name = identifier.partition(".") + table = self._store.find(self._project, dataset, name) + if table is not None: + self._store.drop(table["id"]) + + +@contextmanager +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_connector._http_get_json", fake_http_get_json + ), + ): + yield + + +def migrate( + project: str, + schemas: dict[str, pa.Schema], + dataset: str = "default", + *, + complete: bool = True, +) -> None: + """Write a dataset's schema table as the migration tool does: a row per table, with + ``schemas`` (by table name) where given, then the completion marker. Rows that are + there for other tables are kept. + + Args: + project: The project. + schemas: Table name to the schema it was written with. A column SpiralDB + reorders is recorded in SpiralDB's order. + dataset: The dataset. + complete: Whether to write the marker. + """ + from orcapod.databases import spiraldb_schema_table as st + from orcapod.utils import arrow_utils + + store = _store() + handle = FakeProject(store, project).create_keyed_table( + dataset, SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=True + ) + stored = store.read(handle.resource_id, int(handle.version_id)) + by_id, _ = st.read_rows(stored.to_pylist() if stored.num_columns > 1 else []) + for table in store.tables(): + if (table["project"], table["dataset"]) != (project, dataset): + continue + if table["name"] == SCHEMA_TABLE: + continue + found = _open(store, table, None).schema() + given = schemas.get(table["name"]) + if given is None and table["id"] in by_id: + continue + fields = [ + _recorded_field(f, None if given is None else given.field(f.name)) + for f in found + ] + schema = pa.schema( + [ + f.with_type( + arrow_utils.normalize_to_large_types(f.type, keep_null=True) + ) + for f in fields + ], + metadata=cast(Any, None if given is None else given.metadata), + ) + by_id[table["id"]] = st.SchemaRow( + table["id"], + table["name"], + tuple(table["keys"]), + schema.serialize().to_pybytes(), + st.FROM_SERVICE if given is None else st.FROM_RECORD, + max([0, *store.versions(table["id"])]), + ) + rows = list(by_id.values()) + values = [row.stored() for row in rows] + if complete: + values.append(st.marker_values(st.Scope(project, dataset, "0" * 64), rows)) + written = [{"written_at": "", "written_by": "", **v} for v in values] + handle.append(pa.Table.from_pylist(written, schema=st.ROW_SCHEMA)) + + +def _recorded_field(found: pa.Field[Any], given: Any) -> pa.Field[Any]: + """Return SpiralDB's field with the flags and metadata of the field as written.""" + if given is None: + return found + t: Any = found.type + g: Any = given.type + if isinstance(g, pa.BaseExtensionType): + g = g.storage_type + new = t + if pa.types.is_struct(t) and pa.types.is_struct(g): + new = pa.struct([_recorded_field(f, g.field(f.name)) for f in t]) + elif pa.types.is_fixed_size_list(t): + new = pa.list_(_recorded_field(t.value_field, g.value_field), t.list_size) + elif pa.types.is_list(t): + new = pa.list_(_recorded_field(t.value_field, g.value_field)) + return pa.field(found.name, new, given.nullable, given.metadata) diff --git a/tests/test_databases/spiraldb_schema_v1.b64 b/tests/test_databases/spiraldb_schema_v1.b64 new file mode 100644 index 000000000..3808f3945 --- /dev/null +++ b/tests/test_databases/spiraldb_schema_v1.b64 @@ -0,0 +1,11 @@ +/////0gCAAAQAAAAAAAKAA4ABgAFAAgACgAAAAABBAAQAAAAAAAKAAwAAAAEAAgACgAAAEwAAAAE +AAAAAgAAACQAAAAEAAAAbP7//xAAAAAEAAAAAQAAADIAAAABAAAAYQAAAIj+//8QAAAABAAAAAEA +AAAxAAAAAQAAAHoAAAAEAAAApAEAAOQAAABwAAAAFAAAABAAFAAIAAYABwAMAAAAEAAQAAAAAAAB +FRQAAAAYAAAABAAAAAEAAAAQAAAAAQAAAGwAAACA/v//tP7//wAAAAMQAAAAHAAAAAQAAAAAAAAA +BAAAAGl0ZW0AAAYACAAGAAYAAAAAAAEA5P7//wAAAA0UAAAAGAAAAAQAAAABAAAAEAAAAAEAAABn +AAAA2P7//wz///8AAAACEAAAABwAAAAEAAAAAAAAAAEAAAB5AAAACAAOAAgABwAIAAAAAAAAAQgA +AAAAABIAGAAIAAYABwAMAAAAEAAUABIAAAAAAAECFAAAAJQAAAAIAAAAEAAAAAAAAAABAAAAYQAA +AAMAAABQAAAAJAAAAAQAAADE////EAAAAAQAAAABAAAAMQAAAAEAAABiAAAA4P///xAAAAAEAAAA +AQAAAHgAAAAEAAAAbm90ZQAAAAAIAAwABAAIAAgAAAAQAAAABAAAAAIAAABtVgAABAAAAHVuaXQA +AAAACAAMAAgABwAIAAAAAAAAAUAAAAAQABQACAAAAAcADAAAABAAEAAAAAAAABQQAAAAGAAAAAQA +AAAAAAAAAQAAAGsAAAAEAAQABAAAAA== diff --git a/tests/test_databases/test_append_by_name.py b/tests/test_databases/test_append_by_name.py index c3f05014c..8cb22a0f0 100644 --- a/tests/test_databases/test_append_by_name.py +++ b/tests/test_databases/test_append_by_name.py @@ -31,7 +31,6 @@ DeltaTableDatabase, ExtensionAwareDatabase, InMemoryArrowDatabase, - SpiralDBConnector, SQLiteConnector, ) from orcapod.databases.utils import in_held_column_order @@ -58,8 +57,8 @@ "id c a b": [ID, "c", "a", "b"], "b id a c": ["b", ID, "a", "c"], } -DATABASES = ("in-memory", "Delta", "SQLite", "SpiralDB") -DURABLE = ("Delta", "SQLite", "SpiralDB") +DATABASES = ("in-memory", "Delta", "SQLite") +DURABLE = ("Delta", "SQLite") def _row(n: int) -> dict[str, Any]: @@ -77,13 +76,8 @@ def _rows(order: list[str], ns: list[int]) -> pa.Table: def _given_order(database: str, first: list[str], stored: bool = True) -> list[str]: """The order a database gives a table first written in ``first``. - The first write's order, except in SpiralDB once rows are stored: SpiralDB - stores and reads a table's columns in its own order, the key columns, then the - value columns sorted by name, whatever the order written (observed live, - ITL-1367; its fake does the same). Rows still pending keep the first write's. + The first write's order. """ - if database == "SpiralDB" and stored: - return [ID, *sorted(n for n in first if n != ID)] return first @@ -151,7 +145,7 @@ def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( tmp_path: Path, database: str ) -> None: """The first write's order is kept, whichever order it is; nothing is sorted by - Orcapod (SpiralDB orders a table's columns its own way).""" + Orcapod.""" with open_database(database, tmp_path) as db: for n, order in enumerate([["c", "b", "a", ID], [ID, "a", "b", "c"]]): path = (f"t{n}",) @@ -172,8 +166,6 @@ def test_a_new_table_keeps_the_order_the_database_gave_its_first_write( ("Delta", "same pending batch"): ("add", ValueError), ("SQLite", "after a flush"): ("add", UnstorableColumnError), ("SQLite", "same pending batch"): ("add", UnstorableColumnError), - ("SpiralDB", "after a flush"): ("flush", ValueError), - ("SpiralDB", "same pending batch"): ("add", pa.ArrowInvalid), } @@ -250,22 +242,6 @@ def test_rows_queued_before_a_table_is_created_again_are_read_with_it_by_name( ) -def test_a_spiraldb_table_deleted_and_created_again_in_another_order( - tmp_path: Path, -) -> None: - with open_database("SpiralDB", tmp_path) as db: - _add(db, _rows([ID, "a", "c", "b"], [1]), flush=True) - db._connector.delete_table("t") # the connector's own drop - other_db = ConnectorArrowDatabase(SpiralDBConnector("p")) - _add(other_db, _rows(["b", ID, "c", "a"], [3]), flush=True) - _add(db, _rows([ID, "a", "c", "b"], [4]), flush=True) - _check( - db.get_all_records(PATH, record_id_column=ID), - _given_order("SpiralDB", ["b", ID, "c", "a"]), - [3, 4], - ) - - # ── The shared step ──────────────────────────────────────────────────────────── @@ -735,7 +711,7 @@ def test_a_queued_row_is_read_from_memory(tmp_path: Path) -> None: """A point lookup of a queued row answers from memory, in the order the row is queued, with no lookup of the stored table (as main): the stored table is not even listed. Presentation order is a reader's business (ITL-1370).""" - with open_database("SpiralDB", tmp_path) as db: + with open_database("SQLite", tmp_path) as db: rows = pa.table( { "rid": pa.array([bytes([1])], pa.large_binary()), diff --git a/tests/test_databases/test_appended_field_attributes.py b/tests/test_databases/test_appended_field_attributes.py index 04fe9f7ad..b4640fb66 100644 --- a/tests/test_databases/test_appended_field_attributes.py +++ b/tests/test_databases/test_appended_field_attributes.py @@ -4,7 +4,7 @@ column's own, or a nested field's: a struct child, a list item, a map key or item), another nested field name or another ``keys_sorted`` would read back with the held column's attributes, or the held rows with theirs. Every database that keeps such -attributes (in-memory, Delta, SpiralDB) refuses the append before anything is buffered, +attributes (in-memory, Delta) refuses the append before anything is buffered, naming the column and the path, against the stored table and against a batch still pending; the held rows read back unchanged. Nullability is left out: whether a nullability change is refused belongs to the nullability audit (ITL-842). @@ -28,7 +28,7 @@ PATH = ("t",) I64 = pa.int64() -DATABASES = ("in-memory", "Delta", "SpiralDB") +DATABASES = ("in-memory", "Delta") def _meta(unit: str | None) -> dict[str, str] | None: @@ -95,9 +95,8 @@ def _map_item(unit: str | None) -> Any: def _refuses_the_type(database: str, where: str, unit: str | None) -> bool: - """SpiralDB refuses metadata on a map's key or item field: its connector would - not keep it (``spiraldb_connector._holds_map_field_metadata``).""" - return database == "SpiralDB" and where.startswith("map") and unit is not None + """Whether ``database`` cannot store the column at all: neither does.""" + return False def _rows(ids: list[bytes], field: Any, values: list[Any]) -> pa.Table: diff --git a/tests/test_databases/test_logical_identity_appends.py b/tests/test_databases/test_logical_identity_appends.py index aa5f5cb0b..a37606b8e 100644 --- a/tests/test_databases/test_logical_identity_appends.py +++ b/tests/test_databases/test_logical_identity_appends.py @@ -28,7 +28,6 @@ InMemoryArrowDatabase, ) from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase -from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.utils import ( IdentityNode, first_logical_identity_change, @@ -41,7 +40,6 @@ from orcapod.logical_types.registry import make_arrow_extension_type from orcapod.logical_types.registry import LogicalTypeRegistry from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from tests.test_databases import fake_pyspiral NAME = b"ARROW:extension:name" META = b"ARROW:extension:metadata" @@ -173,10 +171,7 @@ def _store(kind: str, root: Path) -> Iterator[_Store]: elif kind == "Delta": yield _Store(lambda: DeltaTableDatabase(root / "delta")) else: - assert kind == "SpiralDB" - with fake_pyspiral.install(root / "spiral"): - fake_pyspiral.FakeSpiral().project("p") - yield _Store(lambda: ConnectorArrowDatabase(SpiralDBConnector("p"))) + raise AssertionError(kind) def _through(db: Any, via: str) -> Any: @@ -187,11 +182,7 @@ def _through(db: Any, via: str) -> Any: def _supported(kind: str, form: str, depth: str) -> bool: - """Whether ``kind`` stores the column at all (the type matrix): SpiralDB keeps an - annotated top-level column only here; it refuses extension types, and the fake - refuses these nested forms.""" - if kind == "SpiralDB": - return form == "annotated" and depth == "top" + """Whether ``kind`` stores the column at all (the type matrix): both do.""" return True @@ -210,7 +201,7 @@ def _main_accepts(kind: str, state: str, form: str, depth: str) -> bool: ) -KINDS = ("in-memory", "Delta", "SpiralDB") +KINDS = ("in-memory", "Delta") STATES = ("pending", "committed", "reopened") FORMS = ("extension", "annotated") DEPTHS = ("top", "struct", "list", "map value") @@ -2128,52 +2119,6 @@ def test_an_unwritable_encoding_is_refused_before_the_rule(tmp_path: Path) -> No sqlite.add_records(PATH, _annotated_top(b"n", [b"22"]), record_id_column="id") -def test_connector_compares_against_its_cached_stored_schema(tmp_path: Path) -> None: - """Pins the connector's behaviour, as main's (round 4, finding 3): it compares - against the stored schema it caches for the ITL-1334 check, so after another - connection replaces the table (same ids, another identifier), the original - handle still refuses by the replaced identifier and a new handle by the one - stored now.""" - with fake_pyspiral.install(tmp_path / "spiral"): - fake_pyspiral.FakeSpiral().project("p") - held = ConnectorArrowDatabase(SpiralDBConnector("p")) - held.add_records( - PATH, _annotated_top(b"m", [b"1"]), record_id_column="id", flush=True - ) - held.add_records( # reads and caches the stored schema - PATH, - _annotated_top(b"m", [b"1"]), - record_id_column="id", - skip_duplicates=True, - ) - connector = SpiralDBConnector("p") - fake_pyspiral.FakeSpiral().project("p").drop_table( - connector._table_id("t") # pyright: ignore[reportPrivateUsage] # the fake's id of the table - ) - fresh = ConnectorArrowDatabase(connector) - fresh.add_records( - PATH, _annotated_top(b"n", [b"1"]), record_id_column="id", flush=True - ) - with pytest.raises( - InputValidationError, match="the stored column's 'itl1371.a;6d'" - ): - held.add_records( - PATH, - _annotated_top(b"n", [b"1"]), - record_id_column="id", - skip_duplicates=True, - ) - with pytest.raises( - InputValidationError, match="the stored column's 'itl1371.a;6e'" - ): - ConnectorArrowDatabase(SpiralDBConnector("p")).add_records( - PATH, - _annotated_top(b"m", [b"1"]), - record_id_column="id", - skip_duplicates=True, - ) - - def test_delta_flush_refuses_after_another_writer_changed_the_identifier( tmp_path: Path, ) -> None: @@ -2365,25 +2310,3 @@ def test_delta_handle_after_delete_and_recreate_reads_the_new_tables_ids( b"c", b"d", ] - - -def test_connector_lists_its_tables_once_per_append(tmp_path: Path) -> None: - """The identity check and the ordinary check share one gathering of the held - schemas: an append to a table not stored yet lists the backend's tables once, as - on main (CodeRabbit, 6eab211e).""" - with fake_pyspiral.install(tmp_path / "spiral"): - fake_pyspiral.FakeSpiral().project("p") - connector = SpiralDBConnector("p") - calls = {"n": 0} - listing = connector.get_table_names - - def counted() -> list[str]: - calls["n"] += 1 - return listing() - - connector.get_table_names = counted # pyright: ignore[reportAttributeAccessIssue] # counts the listings - db = ConnectorArrowDatabase(connector) - for ids in ([b"1"], [b"22"]): - calls["n"] = 0 - db.add_records(PATH, _annotated_top(b"m", ids), record_id_column="id") - assert calls["n"] == 1 diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py new file mode 100644 index 000000000..655fd8fb9 --- /dev/null +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -0,0 +1,457 @@ +"""The migration tool's write and verify steps, on the fake (ITL-1186). + +The dry run needs pyspiral, so its plan is made here from the same functions; all three +steps were run on throwaway tables of the service. +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +from collections.abc import Callable +from pathlib import Path +from types import ModuleType +from typing import Any, cast + +import pyarrow as pa +import pytest + +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 + +_SCRIPT = Path(__file__).parents[2] / "scripts" / "migrate_spiral_schemas.py" +_DATASETS = ("one", "two") +_TABLES = ("trials", "units") +_WRITTEN = pa.schema( + [ + pa.field("k", pa.large_string(), False), + pa.field("j", pa.int32(), False), + pa.field("v", pa.int64(), False, {"unit": "mV"}), + pa.field("w", pa.large_string()), + ], + metadata={"who": "test"}, +) + + +def _rows(keys: list[str]) -> pa.Table: + return pa.table( + { + "w": [None] * len(keys), + "v": list(range(len(keys))), + "j": pa.array([1] * len(keys), pa.int32()), + "k": keys, + }, + schema=pa.schema( + [ + pa.field("w", pa.string()), + pa.field("v", pa.int64()), + pa.field("j", pa.int32()), + pa.field("k", pa.string()), + ] + ), + ) + + +@pytest.fixture() +def tool(monkeypatch: pytest.MonkeyPatch) -> ModuleType: + """The script as a module, its client the fake's.""" + spec = importlib.util.spec_from_file_location("migrate_spiral_schemas", _SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + monkeypatch.setattr(module, "sdk_client", fake.FakeClient) + return module + + +@pytest.fixture() +def project(tmp_path: Path): + """Two datasets of two tables, with key columns in two orders.""" + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + for dataset in _DATASETS: + for name, keys in zip(_TABLES, (["k", "j"], ["j", "k"])): + made.create_table( + f"{dataset}.{name}", + key_schema=[_WRITTEN.field(key) for key in keys], + ).write(_rows(["a", "b", "c"])) + yield made + + +@pytest.fixture() +def args( + tool: ModuleType, project: Any, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> argparse.Namespace: + """The arguments of a step, with the plan of ``project`` on disk. + + What each table was read as before is stated by a copy of the project that is + migrated by the fake. + """ + described: dict[str, Any] = {} + root = tmp_path / "before" + for dataset in _DATASETS: + tables = [] + for name in _TABLES: + handle = fake.FakeClient().keyed_table("p", dataset, name) + found = handle.schema() + schema = pa.schema( + [_WRITTEN.field(f.name) for f in found], + metadata=cast(Any, _WRITTEN.metadata), + ) + row = st.SchemaRow( + handle.resource_id, + name, + handle.key_columns, + schema.serialize().to_pybytes(), + st.FROM_RECORD, + int(handle.version_id), + ) + tables.append({"row": row.content()}) + described[dataset] = {"schema_table": None, "tables": tables} + # 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) + for table in described[dataset]["tables"]: + name = table["row"]["table_name"] + table["source"] = tool.source_values("p", dataset, name) + table["first_rows"] = tool.first_rows_digest(connector, name) + project.drop_table(f"{dataset}.{st.SCHEMA_TABLE}") + plan = { + "format": tool.PLAN_FORMAT, + "version": tool.PLAN_VERSION, + "project": "p", + "datasets": described, + } + root.mkdir() + path = root / "plan.json" + path.write_text(tool.canonical(plan)) + return argparse.Namespace( + project="p", + dataset=list(_DATASETS), + plan=str(path), + digest=tool.plan_digest(plan), + stop_after=None, + adopt=None, + ) + + +def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: + tool.write(args) + tool.verify(args) + for dataset in _DATASETS: + for name in _TABLES: + schema = SpiralDBConnector("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"} + + +@pytest.mark.parametrize("stop_after", [1, 2, 3, 4]) +def test_an_interrupted_write_is_refused_by_reads_and_resumed( + tool: ModuleType, args: argparse.Namespace, stop_after: int +) -> None: + args.stop_after = stop_after + with pytest.raises(tool.MigrationError, match="stopped as asked"): + tool.write(args) + unfinished = _DATASETS[(stop_after - 1) // len(_TABLES)] + with pytest.raises(TableSchemaError, match="interrupted"): + SpiralDBTableSource("p", "units", dataset=unfinished) + args.stop_after = None + tool.write(args) + tool.verify(args) + tool.write(args) # nothing left to do + tool.verify(args) + + +def test_a_wrong_digest_or_scope_writes_nothing( + tool: ModuleType, args: argparse.Namespace +) -> None: + for change in ( + {"digest": "0" * 64}, + {"project": "q"}, + {"dataset": ["one"]}, + {"dataset": ["one", "two", "three"]}, + ): + with pytest.raises(tool.MigrationError): + tool.write(argparse.Namespace(**{**vars(args), **change})) + for dataset in _DATASETS: + with pytest.raises(fake.SpiralError): + fake.FakeClient().keyed_table("p", dataset, st.SCHEMA_TABLE) + + +def _write_rows(project: Any) -> None: + project.table("two.units").write(_rows(["z"])) + + +def _add_table(project: Any) -> None: + project.create_table("two.new", key_schema=[("k", pa.string())]).write( + pa.table({"k": ["a"], "v": [1]}) + ) + + +def _drop_table(project: Any) -> None: + project.drop_table("two.units") + + +def _recreate_table(project: Any) -> None: + project.drop_table("two.units") + project.create_table( + "two.units", key_schema=[_WRITTEN.field("j"), _WRITTEN.field("k")] + ).write(_rows(["a", "b", "c"])) + + +_DRIFTS: dict[str, Callable[[Any], None]] = { + "rows written": _write_rows, + "table added": _add_table, + "table dropped": _drop_table, + "table created again": _recreate_table, +} + + +@pytest.mark.parametrize("drift", sorted(_DRIFTS)) +def test_a_change_since_the_dry_run_writes_nothing( + tool: ModuleType, args: argparse.Namespace, project: Any, drift: str +) -> None: + """Review findings B10 and 28b9ea8f: the refusal names the table, no KeyError.""" + _DRIFTS[drift](project) + with pytest.raises(tool.MigrationError, match="two"): + tool.write(args) + for dataset in _DATASETS: + with pytest.raises(fake.SpiralError): + fake.FakeClient().keyed_table("p", dataset, st.SCHEMA_TABLE) + + +@pytest.mark.parametrize("drift", sorted(_DRIFTS)) +@pytest.mark.parametrize("when", ["before the marker", "after the marker"]) +def test_a_change_during_the_write_leaves_no_valid_marker( + tool: ModuleType, + args: argparse.Namespace, + project: Any, + monkeypatch: pytest.MonkeyPatch, + drift: str, + when: str, +) -> None: + """Review finding B10. The change comes as the last row of dataset ``two``, or its + marker, is written.""" + original = fake.FakeKeyedTable.append + last = st.MARKER_KEY if when == "after the marker" else None + + def append(self: Any, data: pa.Table) -> Any: + done = original(self, data) + (row,) = data.to_pylist() + is_last = ( + row["table_id"] == st.MARKER_KEY + if last + else row["table_name"] == _TABLES[-1] + ) + if self._table["dataset"] == "two" and is_last: + monkeypatch.setattr(fake.FakeKeyedTable, "append", original) + _DRIFTS[drift](project) + return done + + monkeypatch.setattr(fake.FakeKeyedTable, "append", append) + with pytest.raises(tool.MigrationError) as raised: + tool.write(args) + assert ("withdrawn" in str(raised.value)) == (when == "after the marker") + with pytest.raises(TableSchemaError): + SpiralDBTableSource("p", "trials", dataset="two") + tool_error = (tool.MigrationError, TableSchemaError) + with pytest.raises(tool_error): + tool.verify(args) + + +@pytest.mark.parametrize("error", [RuntimeError("network"), KeyboardInterrupt()]) +def test_any_failure_after_the_marker_withdraws_it_and_is_resumed( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + error: BaseException, +) -> None: + original = tool.require_unchanged + calls = [] + + def fail_after_marker(*given: Any) -> None: + calls.append(given) + # 1 and 2: before anything, per dataset; 3: before the first marker; 4: after. + if len(calls) == 4: + raise error + original(*given) + + monkeypatch.setattr(tool, "require_unchanged", fail_after_marker) + with pytest.raises(tool.MigrationError, match="withdrawn"): + tool.write(args) + with pytest.raises(TableSchemaError, match="does not fit"): + SpiralDBTableSource("p", "trials", dataset="one") + monkeypatch.setattr(tool, "require_unchanged", original) + tool.write(args) + tool.verify(args) + + +def test_verify_finds_what_changed_after_it( + tool: ModuleType, args: argparse.Namespace, project: Any +) -> None: + tool.write(args) + _write_rows(project) + with pytest.raises(tool.MigrationError, match="written since"): + tool.verify(args) + + +@pytest.mark.parametrize( + "part", ["source_id", "content_hash", "pipeline_hash", "tag_schema", "data_schema"] +) +def test_verify_compares_every_identity( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + part: str, +) -> None: + tool.write(args) + original = tool.source_values + + def changed(project: str, dataset: str, name: str) -> dict[str, Any]: + values = original(project, dataset, name) + return {**values, part: "another"} if name == "units" else values + + monkeypatch.setattr(tool, "source_values", changed) + with pytest.raises(tool.MigrationError, match=f"units: {part}") as raised: + tool.verify(args) + assert "trials" not in str(raised.value) + assert "first" not in str(raised.value) + + +def test_verify_compares_the_first_rows( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + tool.write(args) + monkeypatch.setattr(tool, "first_rows_digest", lambda connector, name: "another") + with pytest.raises(tool.MigrationError, match="its first 20 rows"): + tool.verify(args) + + +@pytest.mark.parametrize("when", ["before the creation", "after it", "at the note"]) +def test_a_stop_while_the_schema_table_is_created_is_resumed( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + when: str, +) -> None: + create = fake.FakeProject.create_keyed_table + note = tool.write_note + + def stopping(self: Any, *given: Any, **options: Any) -> Any: + if when == "before the creation": + raise RuntimeError("stopped") + made = create(self, *given, **options) + if when == "after it": + raise RuntimeError("stopped") + return made + + def failing(given: Any, dataset: str, value: str) -> None: + if when == "at the note" and value != tool.CREATING: + raise OSError("disk full") + note(given, dataset, value) + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", stopping) + monkeypatch.setattr(tool, "write_note", failing) + with pytest.raises((RuntimeError, OSError)): + tool.write(args) + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", create) + monkeypatch.setattr(tool, "write_note", note) + if when != "before the creation": + # An empty table of that name may be anyone's: a person names it. + table = fake.FakeClient().keyed_table("p", "one", st.SCHEMA_TABLE) + for adopt in (None, "table_other"): + args.adopt = adopt + with pytest.raises(tool.MigrationError, match=table.resource_id): + tool.write(args) + args.adopt = table.resource_id + tool.write(args) + tool.verify(args) + + +def test_a_table_made_after_a_stop_before_the_creation_is_not_adopted( + tool: ModuleType, args: argparse.Namespace +) -> None: + tool.write_note(args, "one", tool.CREATING) + other = fake.FakeClient().project("p") + made = other.create_keyed_table("one", st.SCHEMA_TABLE, st.KEY_SCHEMA) + with pytest.raises(tool.MigrationError, match="nobody else"): + tool.write(args) + assert fake.FakeClient().keyed_table_by_id(made.resource_id).version_id == "0" + + +def test_a_table_another_program_creates_first_is_never_adopted( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + """The exclusive create is refused (409): no retry takes the other's empty table, + which looks exactly like one of ours.""" + create = fake.FakeProject.create_keyed_table + calls = [] + + def second(self: Any, *given: Any, **options: Any) -> Any: + calls.append(options) + if len(calls) == 1: + create(self, *given, exist_ok=True) # the other program is first + return create(self, *given, **options) + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", second) + with pytest.raises(tool.MigrationError, match="another program created"): + tool.write(args) + for _ in range(2): + with pytest.raises(tool.MigrationError, match="not created by this plan"): + tool.write(args) + table = fake.FakeClient().keyed_table("p", "one", st.SCHEMA_TABLE) + assert table.version_id == "0" # nothing was written to it + assert len(calls) == 1 + + +def test_a_noted_creation_does_not_adopt_a_table_that_holds_rows( + tool: ModuleType, args: argparse.Namespace +) -> None: + fake.migrate("p", {}, "one") + tool.write_note(args, "one", tool.CREATING) + with pytest.raises(tool.MigrationError, match="not created by this plan"): + tool.write(args) + + +def test_a_schema_table_of_another_hand_is_refused( + tool: ModuleType, args: argparse.Namespace, project: Any +) -> None: + """Review finding B12: only a schema table this plan's write created is continued.""" + fake.migrate("p", {}, "two") + with pytest.raises(tool.MigrationError, match="not created by this plan"): + tool.write(args) + with pytest.raises(fake.SpiralError): + fake.FakeClient().keyed_table("p", "one", st.SCHEMA_TABLE) + + +def test_a_schema_table_seen_by_the_dry_run_is_refused( + tool: ModuleType, args: argparse.Namespace +) -> None: + plan = json.loads(Path(args.plan).read_text()) + plan["datasets"]["two"]["schema_table"] = "table_x" + Path(args.plan).write_text(tool.canonical(plan)) + args.digest = tool.plan_digest(plan) + with pytest.raises(tool.MigrationError, match="existed at the dry run"): + tool.write(args) + + +def test_no_sign_in_stops_every_step( + tool: ModuleType, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + for name in ("SPIRAL_TOKEN", "SPIRAL_WORKLOAD_ID", "SPIRAL_CLIENT_ID"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("SPIRAL_AUTH_FILE", str(tmp_path / "none.json")) + with pytest.raises(tool.MigrationError, match="sign-in"): + tool.require_credentials() + + +def test_the_principal_is_named_and_the_token_is_not(tool: ModuleType) -> None: + import base64 + + body = base64.urlsafe_b64encode(b'{"sub": "work_1"}').decode().rstrip("=") + assert tool.principal_of(f"head.{body}.secret") == "work_1" diff --git a/tests/test_databases/test_spiraldb_connector.py b/tests/test_databases/test_spiraldb_connector.py deleted file mode 100644 index 64c9d0b00..000000000 --- a/tests/test_databases/test_spiraldb_connector.py +++ /dev/null @@ -1,807 +0,0 @@ -"""Tests for SpiralDBConnector — DBConnectorProtocol backed by SpiralDB.""" - -from __future__ import annotations - -from unittest.mock import MagicMock, patch - -import pyarrow as pa -import pytest - -from orcapod.databases.spiraldb_connector import SpiralDBConnector, _parse_table_name -from orcapod.protocols.db_connector_protocol import DBConnectorProtocol -from orcapod.types import ColumnInfo - - -# --------------------------------------------------------------------------- -# Fixtures -# --------------------------------------------------------------------------- - - -@pytest.fixture() -def mock_sp(): - with patch("orcapod.databases.spiraldb_connector.sp") as mock: - yield mock - - -@pytest.fixture() -def mock_project(mock_sp): - project = MagicMock(name="MockProject") - mock_sp.Spiral.return_value.project.return_value = project - return project - - -@pytest.fixture() -def connector(mock_sp, mock_project): - return SpiralDBConnector(project_id="test-project-123", dataset="default") - - -# --------------------------------------------------------------------------- -# _parse_table_name helper -# --------------------------------------------------------------------------- - - -class TestParseTableName: - def test_double_quoted_identifier(self): - assert _parse_table_name('SELECT * FROM "my_table"') == "my_table" - - def test_unquoted_fallback(self): - assert _parse_table_name("SELECT * FROM my_table") == "my_table" - - def test_case_insensitive_from(self): - assert _parse_table_name('select * from "signals"') == "signals" - - def test_raises_on_no_table_name(self): - with pytest.raises(ValueError, match="Cannot parse table name"): - _parse_table_name("SELECT 1") - - -# --------------------------------------------------------------------------- -# Protocol conformance -# --------------------------------------------------------------------------- - - -class TestProtocolConformance: - def test_isinstance_check_passes(self, connector): - assert isinstance(connector, DBConnectorProtocol) - - -# --------------------------------------------------------------------------- -# Lifecycle -# --------------------------------------------------------------------------- - - -class TestLifecycle: - def test_close_sets_closed_flag(self, connector): - assert not connector._closed - connector.close() - assert connector._closed - - def test_double_close_is_safe(self, connector): - connector.close() - connector.close() # must not raise - - def test_context_manager_closes_on_exit(self, mock_sp, mock_project): - c = SpiralDBConnector(project_id="p", dataset="default") - with c: - assert not c._closed - assert c._closed - - def test_context_manager_does_not_suppress_exceptions(self, mock_sp, mock_project): - c = SpiralDBConnector(project_id="p", dataset="default") - with pytest.raises(RuntimeError, match="boom"): - with c: - raise RuntimeError("boom") - assert c._closed # still closed even when exception raised - - def test_methods_raise_after_close(self, connector, mock_project): - connector.close() - with pytest.raises(RuntimeError, match="closed"): - connector.get_table_names() - with pytest.raises(RuntimeError, match="closed"): - connector.get_pk_columns("t") - with pytest.raises(RuntimeError, match="closed"): - connector.get_column_info("t") - with pytest.raises(RuntimeError, match="closed"): - list(connector.iter_batches('SELECT * FROM "t"')) - with pytest.raises(RuntimeError, match="closed"): - connector.create_table_if_not_exists("t", [], "id") - with pytest.raises(RuntimeError, match="closed"): - connector.upsert_records( - "t", pa.table({"id": pa.array([], type=pa.string())}), "id" - ) - with pytest.raises(RuntimeError, match="closed"): - connector.to_config() - - -# --------------------------------------------------------------------------- -# Schema introspection -# --------------------------------------------------------------------------- - - -class TestGetTableNames: - def test_returns_sorted_plain_names_for_dataset(self, connector, mock_project): - r1 = MagicMock(dataset="default", table="signals") - r2 = MagicMock(dataset="other", table="signals") # excluded — wrong dataset - r3 = MagicMock(dataset="default", table="events") - mock_project.list_tables.return_value = [r1, r2, r3] - assert connector.get_table_names() == ["events", "signals"] - - def test_empty_project_returns_empty_list(self, connector, mock_project): - mock_project.list_tables.return_value = [] - assert connector.get_table_names() == [] - - def test_all_tables_in_other_dataset_returns_empty(self, connector, mock_project): - r1 = MagicMock(dataset="other", table="foo") - mock_project.list_tables.return_value = [r1] - assert connector.get_table_names() == [] - - -class TestGetPkColumns: - def test_single_pk(self, connector, mock_project): - mock_table = MagicMock() - mock_table.key_schema.names = ["id"] - mock_project.table.return_value = mock_table - assert connector.get_pk_columns("my_table") == ["id"] - mock_project.table.assert_called_once_with("default.my_table") - - def test_composite_pk_preserves_order(self, connector, mock_project): - mock_table = MagicMock() - mock_table.key_schema.names = ["session_id", "timestamp", "probe_id"] - mock_project.table.return_value = mock_table - assert connector.get_pk_columns("spike_data") == [ - "session_id", - "timestamp", - "probe_id", - ] - - def test_empty_key_schema_returns_empty_list(self, connector, mock_project): - mock_table = MagicMock() - mock_table.key_schema.names = [] - mock_project.table.return_value = mock_table - assert connector.get_pk_columns("no_key_table") == [] - - -class TestGetColumnInfo: - def test_arrow_types_returned_with_string_normalization( - self, connector, mock_project - ): - # SpiralDB normalizes large_string → string at storage time. - # get_column_info maps string → large_string (and binary → large_binary) - # to stay consistent with SQLiteConnector and PostgreSQLConnector. - arrow_schema = pa.schema( - [ - pa.field("id", pa.string(), nullable=False), # SpiralDB returns string - pa.field("data", pa.binary(), nullable=True), # SpiralDB returns binary - pa.field("value", pa.float64(), nullable=True), - pa.field("count", pa.int64(), nullable=True), - ] - ) - mock_table = MagicMock() - mock_table.schema.return_value.to_arrow.return_value = arrow_schema - mock_table.get_metadata.return_value = {} # no nullability record - mock_project.table.return_value = mock_table - result = connector.get_column_info("my_table") - assert result == [ - ColumnInfo("id", pa.large_string(), nullable=False), # normalized - ColumnInfo("data", pa.large_binary(), nullable=True), # normalized - ColumnInfo("value", pa.float64(), nullable=True), - ColumnInfo("count", pa.int64(), nullable=True), - ] - mock_project.table.assert_called_once_with("default.my_table") - - def test_nonexistent_table_propagates_pyspiral_exception( - self, connector, mock_project - ): - mock_project.table.side_effect = RuntimeError("table not found") - with pytest.raises(RuntimeError, match="table not found"): - connector.get_column_info("nonexistent") - - -# --------------------------------------------------------------------------- -# iter_batches -# --------------------------------------------------------------------------- - - -class TestIterBatches: - def _wire_scan(self, mock_sp, mock_project, batches: list) -> None: - """Wire mock_sp so that scan().to_record_batches() returns ``batches``.""" - mock_project.table.return_value.select.return_value = MagicMock() - mock_project.table.return_value.get_metadata.return_value = {} - mock_sp.Spiral.return_value.scan.return_value.to_record_batches.return_value = ( - iter(batches) - ) - - def test_full_scan_yields_batches(self, connector, mock_sp, mock_project): - # SpiralDB returns pa.string() at the wire; iter_batches must normalize - # to pa.large_string() so ConnectorArrowDatabase can concat with pending - # records (which always use large_string). - raw_batch = pa.record_batch( - {"id": pa.array(["a", "b"], type=pa.string()), "v": pa.array([1, 2])} - ) - self._wire_scan(mock_sp, mock_project, [raw_batch]) - result = list(connector.iter_batches('SELECT * FROM "my_table"')) - assert len(result) == 1 - # Type is promoted to large_string; data values are preserved. - assert result[0].schema.field("id").type == pa.large_string() - assert result[0].column("id").to_pylist() == ["a", "b"] - assert result[0].column("v").to_pylist() == [1, 2] - mock_project.table.assert_called_once_with("default.my_table") - - def test_string_and_binary_normalized_to_large( - self, connector, mock_sp, mock_project - ): - # SpiralDB (Vortex) stores utf8 → pa.string() and binary → pa.binary(). - # iter_batches must cast those to large_string / large_binary so they - # match the types used by ConnectorArrowDatabase for pending records, - # preventing pa.concat_tables schema mismatches. - raw_batch = pa.record_batch( - { - "label": pa.array(["x"], type=pa.string()), - "payload": pa.array([b"\x00"], type=pa.binary()), - "score": pa.array([1.0], type=pa.float64()), - } - ) - self._wire_scan(mock_sp, mock_project, [raw_batch]) - result = list(connector.iter_batches('SELECT * FROM "t"')) - assert len(result) == 1 - batch = result[0] - assert batch.schema.field("label").type == pa.large_string() - assert batch.schema.field("payload").type == pa.large_binary() - assert batch.schema.field("score").type == pa.float64() # unchanged - assert batch.column("label").to_pylist() == ["x"] - assert batch.column("payload").to_pylist() == [b"\x00"] - - def test_empty_table_yields_no_batches(self, connector, mock_sp, mock_project): - self._wire_scan(mock_sp, mock_project, []) - result = list(connector.iter_batches('SELECT * FROM "empty_table"')) - assert result == [] - - def test_multiple_batches_all_yielded(self, connector, mock_sp, mock_project): - b1 = pa.record_batch({"id": pa.array(["a"])}) - b2 = pa.record_batch({"id": pa.array(["b"])}) - self._wire_scan(mock_sp, mock_project, [b1, b2]) - result = list(connector.iter_batches('SELECT * FROM "t"')) - assert len(result) == 2 - - def test_params_not_none_emits_warning( - self, connector, mock_sp, mock_project, caplog - ): - import logging - - self._wire_scan(mock_sp, mock_project, []) - with caplog.at_level(logging.WARNING): - list(connector.iter_batches('SELECT * FROM "t"', params={"x": 1})) - assert any("params" in msg.lower() for msg in caplog.messages) - - def test_batch_size_logs_warning_and_is_ignored( - self, connector, mock_sp, mock_project, caplog - ): - # SpiralDB does not support caller-controlled batch sizing; the SDK - # controls batch sizes internally. A warning should be logged when a - # non-default value is passed, and to_record_batches() must be called - # with no arguments. - import logging # noqa: PLC0415 - - self._wire_scan(mock_sp, mock_project, []) - with caplog.at_level(logging.WARNING): - list(connector.iter_batches('SELECT * FROM "t"', batch_size=500)) - assert any("batch_size" in msg.lower() for msg in caplog.messages) - mock_sp.Spiral.return_value.scan.return_value.to_record_batches.assert_called_with() - - def test_nonexistent_table_propagates_exception( - self, connector, mock_sp, mock_project - ): - mock_project.table.side_effect = RuntimeError("table not found") - with pytest.raises(RuntimeError, match="table not found"): - list(connector.iter_batches('SELECT * FROM "missing"')) - - def test_tbl_select_called_for_full_scan(self, connector, mock_sp, mock_project): - self._wire_scan(mock_sp, mock_project, []) - list(connector.iter_batches('SELECT * FROM "t"')) - mock_project.table.return_value.select.assert_called_once_with() - - -# --------------------------------------------------------------------------- -# create_table_if_not_exists -# --------------------------------------------------------------------------- - - -class TestCreateTableIfNotExists: - def test_creates_table_with_pk_key_schema(self, connector, mock_project): - columns = [ - ColumnInfo("id", pa.string(), nullable=False), - ColumnInfo("value", pa.float64(), nullable=True), - ] - connector.create_table_if_not_exists("my_table", columns, pk_column="id") - mock_project.create_table.assert_called_once_with( - "default.my_table", - key_schema=[("id", pa.string())], - exist_ok=True, - ) - - def test_exist_ok_always_true(self, connector, mock_project): - columns = [ColumnInfo("id", pa.int64(), nullable=False)] - connector.create_table_if_not_exists("t", columns, pk_column="id") - connector.create_table_if_not_exists("t", columns, pk_column="id") - assert mock_project.create_table.call_count == 2 - for call_args in mock_project.create_table.call_args_list: - assert call_args.kwargs.get("exist_ok") is True - - def test_raises_if_pk_column_not_in_columns(self, connector, mock_project): - columns = [ColumnInfo("id", pa.string(), nullable=False)] - with pytest.raises(ValueError, match="pk_column"): - connector.create_table_if_not_exists("t", columns, pk_column="missing_col") - - def test_raises_if_columns_empty(self, connector, mock_project): - with pytest.raises(ValueError, match="pk_column"): - connector.create_table_if_not_exists("t", columns=[], pk_column="id") - - def test_non_pk_columns_not_included_in_key_schema(self, connector, mock_project): - columns = [ - ColumnInfo("id", pa.string(), nullable=False), - ColumnInfo("value", pa.float64()), - ColumnInfo("label", pa.string()), - ] - connector.create_table_if_not_exists("t", columns, pk_column="id") - call_kwargs = mock_project.create_table.call_args.kwargs - assert call_kwargs["key_schema"] == [("id", pa.string())] - - -# --------------------------------------------------------------------------- -# upsert_records -# --------------------------------------------------------------------------- - - -class TestUpsertRecords: - def _make_mock_table(self, mock_project, pk_cols: list[str]) -> MagicMock: - mock_table = MagicMock() - mock_table.key_schema.names = pk_cols - # A table that already holds rows and has no nullability record (ITL-936), so - # the connector writes no record and these tests see only their own calls. - mock_table.get_metadata.return_value = {} - mock_table.schema.return_value.to_arrow.return_value = pa.schema( - [pa.field(c, pa.string()) for c in pk_cols] - + [pa.field("existing_value", pa.int64())] - ) - mock_project.table.return_value = mock_table - return mock_table - - # --- skip_existing=False (default: always upsert-by-key) ---------------- - - def test_write_called_with_full_records(self, connector, mock_project): - mock_table = self._make_mock_table(mock_project, ["id"]) - records = pa.table({"id": ["a", "b"], "value": [1.0, 2.0]}) - connector.upsert_records("my_table", records, id_column="id") - mock_table.write.assert_called_once_with(records) - - def test_raises_if_id_column_not_in_key_schema(self, connector, mock_project): - self._make_mock_table(mock_project, ["id"]) - records = pa.table({"id": ["a"], "value": [1.0]}) - with pytest.raises(ValueError, match="id_column"): - connector.upsert_records("my_table", records, id_column="wrong_col") - - def test_raises_if_pk_column_missing_from_records(self, connector, mock_project): - self._make_mock_table(mock_project, ["id", "session_id"]) - records = pa.table({"id": ["a"]}) # missing session_id - with pytest.raises(ValueError, match="missing key column"): - connector.upsert_records("my_table", records, id_column="id") - - def test_raises_if_empty_key_schema(self, connector, mock_project): - # id_column can never be `in []`, so this always raises ValueError - self._make_mock_table(mock_project, []) - records = pa.table({"id": ["a"]}) - with pytest.raises(ValueError, match="id_column"): - connector.upsert_records("my_table", records, id_column="id") - - # --- skip_existing=True (scan + filter + write novel rows only) ---------- - - def test_skip_existing_writes_only_novel_rows( - self, connector, mock_sp, mock_project - ): - mock_table = self._make_mock_table(mock_project, ["id"]) - existing = pa.table({"id": ["a"], "value": [1.0]}) - new_records = pa.table({"id": ["a", "b"], "value": [1.0, 2.0]}) - mock_sp.Spiral.return_value.scan.return_value.to_table.return_value = existing - - connector.upsert_records( - "my_table", new_records, id_column="id", skip_existing=True - ) - - written = mock_table.write.call_args[0][0] - assert written.column("id").to_pylist() == ["b"] - - def test_skip_existing_noop_when_all_rows_exist( - self, connector, mock_sp, mock_project - ): - mock_table = self._make_mock_table(mock_project, ["id"]) - existing = pa.table({"id": ["a", "b"], "value": [1.0, 2.0]}) - new_records = pa.table({"id": ["a", "b"], "value": [10.0, 20.0]}) - mock_sp.Spiral.return_value.scan.return_value.to_table.return_value = existing - - connector.upsert_records( - "my_table", new_records, id_column="id", skip_existing=True - ) - - mock_table.write.assert_not_called() - - def test_skip_existing_composite_pk(self, connector, mock_sp, mock_project): - mock_table = self._make_mock_table(mock_project, ["session_id", "ts"]) - existing = pa.table( - { - "session_id": pa.array(["s1"]), - "ts": pa.array([1], type=pa.int64()), - "v": pa.array([10.0]), - } - ) - new_records = pa.table( - { - "session_id": pa.array(["s1", "s1"]), - "ts": pa.array( - [1, 2], type=pa.int64() - ), # (s1,1) exists; (s1,2) is novel - "v": pa.array([99.0, 5.0]), - } - ) - mock_sp.Spiral.return_value.scan.return_value.to_table.return_value = existing - - connector.upsert_records( - "my_table", new_records, id_column="session_id", skip_existing=True - ) - - written = mock_table.write.call_args[0][0] - assert written.column("ts").to_pylist() == [2] - - def test_skip_existing_raises_if_id_column_not_in_key_schema( - self, connector, mock_project - ): - self._make_mock_table(mock_project, ["id"]) - records = pa.table({"id": ["a"]}) - with pytest.raises(ValueError, match="id_column"): - connector.upsert_records( - "t", records, id_column="wrong", skip_existing=True - ) - - def test_skip_existing_raises_if_pk_missing_from_records( - self, connector, mock_project - ): - self._make_mock_table(mock_project, ["id", "ts"]) - records = pa.table({"id": ["a"]}) # missing ts - with pytest.raises(ValueError, match="missing key column"): - connector.upsert_records("t", records, id_column="id", skip_existing=True) - - -# --------------------------------------------------------------------------- -# to_config / from_config -# --------------------------------------------------------------------------- - - -class TestConfigSerialization: - def test_to_config_round_trip(self, mock_sp, mock_project): - c = SpiralDBConnector( - project_id="my-project-123", - dataset="prod", - overrides={"server.url": "http://api.spiraldb.dev"}, - ) - cfg = c.to_config() - assert cfg == { - "connector_type": "spiraldb", - "project_id": "my-project-123", - "dataset": "prod", - "overrides": {"server.url": "http://api.spiraldb.dev"}, - } - - def test_to_config_none_overrides(self, connector): - cfg = connector.to_config() - assert cfg["overrides"] is None - - def test_from_config_constructs_connector(self, mock_sp, mock_project): - cfg = { - "connector_type": "spiraldb", - "project_id": "my-project-123", - "dataset": "prod", - "overrides": None, - } - c = SpiralDBConnector.from_config(cfg) - assert c._project_id == "my-project-123" - assert c._dataset == "prod" - assert c._overrides is None - - def test_from_config_default_dataset_when_absent(self, mock_sp, mock_project): - cfg = {"connector_type": "spiraldb", "project_id": "p"} - c = SpiralDBConnector.from_config(cfg) - assert c._dataset == "default" - - def test_from_config_raises_on_wrong_connector_type(self): - with pytest.raises(ValueError, match="connector_type"): - SpiralDBConnector.from_config( - {"connector_type": "sqlite", "project_id": "p"} - ) - - def test_to_config_raises_after_close(self, connector): - connector.close() - with pytest.raises(RuntimeError, match="closed"): - connector.to_config() - - -# --------------------------------------------------------------------------- -# TestValidateRecords -# --------------------------------------------------------------------------- - - -class TestValidateRecords: - def test_no_op_for_plain_columns(self, connector): - """validate_records is a no-op on SpiralDBConnector for plain columns.""" - table = pa.table( - { - "id": pa.array([b"a"], type=pa.large_binary()), - "value": pa.array([1], type=pa.int64()), - } - ) - connector.validate_records(table) # must not raise - - def test_no_op_for_extension_typed_columns(self, connector): - """SpiralDBConnector.validate_records allows extension-typed columns.""" - ext_field = pa.field( - "payload", - pa.large_string(), - metadata={ - b"ARROW:extension:name": b"orcapod.path", - b"ARROW:extension:metadata": b"", - }, - ) - schema = pa.schema([pa.field("id", pa.large_binary()), ext_field]) - table = pa.table( - { - "id": pa.array([b"a"], type=pa.large_binary()), - "payload": pa.array(["/tmp/x"], type=pa.large_string()), - }, - schema=schema, - ) - connector.validate_records( - table - ) # must not raise — SpiralDB supports extension types - - -# --------------------------------------------------------------------------- -# TestUpsertRecordsMetadata -# --------------------------------------------------------------------------- - - -class TestUpsertRecordsMetadata: - def _make_mock_table(self, mock_project, pk_cols: list[str]) -> MagicMock: - mock_table = MagicMock() - mock_table.key_schema.names = pk_cols - # A table that already holds rows and has no nullability record (ITL-936), so - # the connector writes no record and these tests see only their own calls. - mock_table.get_metadata.return_value = {} - mock_table.schema.return_value.to_arrow.return_value = pa.schema( - [pa.field(c, pa.string()) for c in pk_cols] - + [pa.field("existing_value", pa.int64())] - ) - mock_project.table.return_value = mock_table - return mock_table - - def test_set_metadata_called_after_write_when_schema_metadata_present( - self, connector, mock_project - ): - mock_tbl = self._make_mock_table(mock_project, ["id"]) - schema = pa.schema( - [pa.field("id", pa.string()), pa.field("val", pa.int64())], - metadata={b"origin": b"test"}, - ) - records = pa.table( - {"id": pa.array(["a"]), "val": pa.array([1], type=pa.int64())}, - schema=schema, - ) - connector.upsert_records("t", records, id_column="id") - mock_tbl.write.assert_called_once() - mock_tbl.set_metadata.assert_called_once() - kv = mock_tbl.set_metadata.call_args[0][0] - assert "__arrow_metadata__" in kv - - def test_set_metadata_called_when_field_metadata_present( - self, connector, mock_project - ): - mock_tbl = self._make_mock_table(mock_project, ["id"]) - schema = pa.schema( - [ - pa.field("id", pa.string()), - pa.field("val", pa.int64(), metadata={b"unit": b"m"}), - ] - ) - records = pa.table( - {"id": pa.array(["a"]), "val": pa.array([1], type=pa.int64())}, - schema=schema, - ) - connector.upsert_records("t", records, id_column="id") - mock_tbl.set_metadata.assert_called_once() - - def test_set_metadata_not_called_when_no_metadata(self, connector, mock_project): - mock_tbl = self._make_mock_table(mock_project, ["id"]) - records = pa.table({"id": pa.array(["a"]), "val": pa.array([1])}) - connector.upsert_records("t", records, id_column="id") - mock_tbl.write.assert_called_once() - mock_tbl.set_metadata.assert_not_called() - - def test_set_metadata_called_for_skip_existing_path( - self, connector, mock_sp, mock_project - ): - mock_tbl = self._make_mock_table(mock_project, ["id"]) - existing = pa.table({"id": pa.array(["a"]), "val": pa.array([1])}) - mock_sp.Spiral.return_value.scan.return_value.to_table.return_value = existing - schema = pa.schema( - [pa.field("id", pa.string()), pa.field("val", pa.int64())], - metadata={b"version": b"1"}, - ) - records = pa.table( - {"id": pa.array(["a", "b"]), "val": pa.array([1, 2], type=pa.int64())}, - schema=schema, - ) - connector.upsert_records("t", records, id_column="id", skip_existing=True) - # "b" is novel — write called; metadata derived from original records - mock_tbl.write.assert_called_once() - mock_tbl.set_metadata.assert_called_once() - import json # noqa: PLC0415 - import base64 as b64mod # noqa: PLC0415 - - kv = mock_tbl.set_metadata.call_args[0][0] - blob = json.loads(kv["__arrow_metadata__"].decode()) - assert ( - blob["schema"][b64mod.b64encode(b"version").decode()] - == b64mod.b64encode(b"1").decode() - ) - - def test_set_metadata_not_called_when_skip_existing_all_exist( - self, connector, mock_sp, mock_project - ): - mock_tbl = self._make_mock_table(mock_project, ["id"]) - existing = pa.table({"id": pa.array(["a", "b"]), "val": pa.array([1, 2])}) - mock_sp.Spiral.return_value.scan.return_value.to_table.return_value = existing - records = pa.table({"id": pa.array(["a", "b"]), "val": pa.array([10, 20])}) - connector.upsert_records("t", records, id_column="id", skip_existing=True) - mock_tbl.write.assert_not_called() - mock_tbl.set_metadata.assert_not_called() - - -# --------------------------------------------------------------------------- -# TestIterBatchesMetadata -# --------------------------------------------------------------------------- - - -class TestIterBatchesMetadata: - def _wire_scan( - self, mock_sp, mock_project, batches: list, kv: dict | None = None - ) -> None: - mock_project.table.return_value.select.return_value = MagicMock() - mock_project.table.return_value.get_metadata.return_value = kv or {} - mock_sp.Spiral.return_value.scan.return_value.to_record_batches.return_value = ( - iter(batches) - ) - - def test_schema_metadata_reattached(self, connector, mock_sp, mock_project): - import json # noqa: PLC0415 - import base64 as b64mod # noqa: PLC0415 - - stored_blob = json.dumps( - { - "schema": { - b64mod.b64encode(b"origin").decode(): b64mod.b64encode( - b"test" - ).decode() - } - } - ).encode() - raw_batch = pa.record_batch({"id": pa.array(["a"], type=pa.string())}) - self._wire_scan( - mock_sp, mock_project, [raw_batch], {"__arrow_metadata__": stored_blob} - ) - - result = list(connector.iter_batches('SELECT * FROM "t"')) - assert len(result) == 1 - assert result[0].schema.metadata == {b"origin": b"test"} - - def test_field_metadata_reattached(self, connector, mock_sp, mock_project): - import json # noqa: PLC0415 - import base64 as b64mod # noqa: PLC0415 - - stored_blob = json.dumps( - { - "fields": { - "val": { - "meta": { - b64mod.b64encode(b"unit").decode(): b64mod.b64encode( - b"meters" - ).decode() - } - } - } - } - ).encode() - raw_batch = pa.record_batch( - { - "id": pa.array(["a"], type=pa.string()), - "val": pa.array([1.0], type=pa.float64()), - } - ) - self._wire_scan( - mock_sp, mock_project, [raw_batch], {"__arrow_metadata__": stored_blob} - ) - - result = list(connector.iter_batches('SELECT * FROM "t"')) - assert result[0].schema.field("val").metadata == {b"unit": b"meters"} - - def test_string_normalization_preserved_with_metadata( - self, connector, mock_sp, mock_project - ): - """string → large_string normalization still applies when field metadata present.""" - import json # noqa: PLC0415 - import base64 as b64mod # noqa: PLC0415 - - stored_blob = json.dumps( - { - "fields": { - "label": { - "meta": { - b64mod.b64encode( - b"ARROW:extension:name" - ).decode(): b64mod.b64encode(b"orcapod.path").decode() - } - } - } - } - ).encode() - # SpiralDB returns pa.string() at the wire - raw_batch = pa.record_batch({"label": pa.array(["x"], type=pa.string())}) - self._wire_scan( - mock_sp, mock_project, [raw_batch], {"__arrow_metadata__": stored_blob} - ) - - result = list(connector.iter_batches('SELECT * FROM "t"')) - batch = result[0] - # type must be large_string (normalized) - assert batch.schema.field("label").type == pa.large_string() - # metadata must be restored - assert batch.schema.field("label").metadata == { - b"ARROW:extension:name": b"orcapod.path" - } - - def test_no_stored_metadata_behaves_as_before( - self, connector, mock_sp, mock_project - ): - """Tables with no stored metadata are returned unchanged (backward compat).""" - raw_batch = pa.record_batch( - {"id": pa.array(["a"], type=pa.string()), "v": pa.array([1])} - ) - self._wire_scan(mock_sp, mock_project, [raw_batch], {}) - - result = list(connector.iter_batches('SELECT * FROM "t"')) - assert result[0].schema.field("id").type == pa.large_string() - assert result[0].schema.metadata is None - - def test_get_metadata_called_once_per_scan_not_per_batch( - self, connector, mock_sp, mock_project - ): - b1 = pa.record_batch({"id": pa.array(["a"])}) - b2 = pa.record_batch({"id": pa.array(["b"])}) - self._wire_scan(mock_sp, mock_project, [b1, b2], {}) - list(connector.iter_batches('SELECT * FROM "t"')) - mock_project.table.return_value.get_metadata.assert_called_once() - - -# --------------------------------------------------------------------------- -# TestDeleteTable -# --------------------------------------------------------------------------- - - -class TestDeleteTable: - def test_delete_existing_table_calls_drop_table(self, connector, mock_project): - r1 = MagicMock(dataset="default", table="my_table") - mock_project.list_tables.return_value = [r1] - connector.delete_table("my_table") - mock_project.drop_table.assert_called_once_with("default.my_table") - - def test_delete_nonexistent_table_is_noop(self, connector, mock_project): - r1 = MagicMock(dataset="default", table="other_table") - mock_project.list_tables.return_value = [r1] - connector.delete_table("no_such") - mock_project.drop_table.assert_not_called() diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py deleted file mode 100644 index 6d78530da..000000000 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ /dev/null @@ -1,702 +0,0 @@ -"""SpiralDBConnector read path against the disk-backed pyspiral fake (no live SpiralDB). - -These tests push real Arrow tables through the connector, unlike the ``MagicMock`` tests in -``test_spiraldb_connector.py``. See ``fake_pyspiral`` for the storage behaviour modelled. -""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any - -import pyarrow as pa -import pytest - -from orcapod.databases import ( - ConnectorArrowDatabase, - SpiralDBConnector, - read_nullability_record, - spiraldb_connector, - write_nullability_record, -) -from orcapod.errors import ( - NullabilityRecordError, - NullabilityRecordMismatchError, - NullInNonNullableColumnError, - UnsupportedValueError, -) -from orcapod.utils import arrow_utils -from orcapod.sources import ArrowTableSource, SpiralDBTableSource -from tests.test_databases import fake_pyspiral -from tests.test_databases.type_matrix import map_of_fields - -_NESTED = pa.schema( - [ - pa.field("id", pa.int64(), nullable=False), - pa.field("s", pa.string()), - pa.field("list_str", pa.list_(pa.string())), - pa.field("list_nonnull_item", pa.list_(pa.field("item", pa.string(), False))), - pa.field( - "st", - pa.struct([pa.field("a", pa.string(), False), pa.field("b", pa.binary())]), - ), - pa.field("large_list_bin", pa.large_list(pa.binary())), - pa.field( - "tags", - # key field "key" (non-null) and item field "value" (nullable) - pa.map_(pa.string(), pa.list_(pa.string())), - ), - ] -) - -# What the connector must hand out: the large variant at every depth, with every nested -# field's name and nullability unchanged. -_EXPECTED = { - "id": pa.int64(), - "s": pa.large_string(), - "list_str": pa.large_list(pa.large_string()), - "list_nonnull_item": pa.large_list(pa.field("item", pa.large_string(), False)), - "st": pa.struct( - [pa.field("a", pa.large_string(), False), pa.field("b", pa.large_binary())] - ), - "large_list_bin": pa.large_list(pa.large_binary()), - "tags": pa.map_(pa.large_string(), pa.large_list(pa.large_string())), -} - - -def _nested_table() -> pa.Table: - """Return two rows covering every nested type in ``_NESTED``.""" - return pa.table( - { - "id": [1, 2], - "s": ["x", None], - "list_str": [["a"], []], - "list_nonnull_item": [["p", "q"], ["r"]], - "st": [{"a": "u", "b": b"1"}, {"a": "v", "b": None}], - "large_list_bin": [[b"z"], []], - "tags": [[("k", ["a", "b"])], []], - }, - schema=_NESTED, - ) - - -@pytest.fixture() -def spiral_root(tmp_path: Path): - """Provide a fake SpiralDB root holding table ``default.nested`` in project ``p``.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project("p") - project.create_table("default.nested", key_schema=[("id", pa.int64())]) - connector = SpiralDBConnector("p") - # Written through the connector, which records the non-nullable columns (ITL-936): - # SpiralDB itself reports every column and struct field nullable. - connector.upsert_records("nested", _nested_table(), id_column="id") - # Sources hash their rows, and starfix 0.4.0 cannot hash map columns yet, so the - # source-level tests read a copy without the map column. - project.create_table("default.hashable", key_schema=[("id", pa.int64())]) - connector.upsert_records( - "hashable", _nested_table().drop_columns(["tags"]), id_column="id" - ) - yield tmp_path - - -class TestLargeTypeNormalization: - """ITL-40: both read paths give the same, fully large-normalized types.""" - - def test_iter_batches_normalizes_nested_types(self, spiral_root): - connector = SpiralDBConnector("p") - batches = list(connector.iter_batches('SELECT * FROM "nested"')) - assert batches - for batch in batches: - assert {f.name: f.type for f in batch.schema} == _EXPECTED - - def test_get_column_info_matches_iter_batches(self, spiral_root): - connector = SpiralDBConnector("p") - info = {c.name: c.arrow_type for c in connector.get_column_info("nested")} - assert info == _EXPECTED - - def test_source_exposes_normalized_types(self, spiral_root): - source = SpiralDBTableSource("p", "hashable", tag_only_columns=True) - schema = source.as_table().schema - expected = {k: v for k, v in _EXPECTED.items() if k != "tags"} - assert {name: schema.field(name).type for name in expected} == expected - - def test_normalization_leaves_hashes_unchanged(self, spiral_root): - # Large and non-large layouts hash identically, so the Spiral source's per-row - # content hashes equal those of the same rows given in their original layout. - spiral = SpiralDBTableSource( - "p", "hashable", source_id="nested", tag_only_columns=True - ) - # The nullability record restores the written nullability, so the rows as written - # (non-large layouts) are the reference. - direct = ArrowTableSource( - _nested_table().drop_columns(["tags"]), - tag_columns=["id"], - source_id="nested", - tag_only_columns=True, - ) - - def hashes(source) -> list[str]: - return ( - source.as_table(columns={"content_hash": True}) - .column("_content_hash") - .to_pylist() - ) - - assert hashes(spiral) == hashes(direct) - - -_ITEM = pa.field("item", pa.float32(), False) -_G = pa.struct([pa.field("x", pa.int32(), False), pa.field("y", pa.int32(), True)]) -_RECORDED = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("v", pa.int32(), False), - pa.field("w", pa.int32(), True), - pa.field("g", _G, False), - pa.field("l", pa.list_(_ITEM), False), - ] -) -_TABLE = "p/default/t" - - -def _spiral_order(schema: pa.Schema, keys: list[str]) -> pa.Schema: - """``schema`` in the order SpiralDB stores and reads a table's columns, whatever - the order written: the key columns in key order, then the value columns sorted - by name (observed live, ITL-1367).""" - values = sorted(f.name for f in schema if f.name not in keys) - return pa.schema([schema.field(n) for n in [*keys, *values]]) - - -def _rows(schema: pa.Schema = _RECORDED, **override) -> pa.Table: - """Return three rows of ``schema`` (``override`` replaces whole columns).""" - columns = { - "k": [1, 2, 3], - "v": [10, 20, 30], - "w": [None, 2, None], - "g": [{"x": 1, "y": None}, {"x": 2, "y": 3}, {"x": 3, "y": None}], - "l": [[1.0], [], [2.0, 3.0]], - **override, - } - return pa.Table.from_pydict(columns, schema=schema) - - -def _with(schema: pa.Schema, name: str, nullable: bool) -> pa.Schema: - """Return ``schema`` with column ``name`` set to ``nullable``.""" - i = schema.get_field_index(name) - return schema.set(i, schema.field(name).with_nullable(nullable)) - - -class TestNullabilityRecord: - """ITL-936: the connector records non-nullable columns and enforces them on read.""" - - @pytest.fixture() - def fake(self, tmp_path: Path): - """Provide the fake project ``p`` with an empty table ``default.t`` keyed on k.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project("p") - project.create_table("default.t", key_schema=[("k", pa.int64())]) - yield project - - def _batches_schema(self, connector: SpiralDBConnector) -> pa.Schema: - """Return the one schema every batch of table ``t`` has.""" - batches = list(connector.iter_batches('SELECT * FROM "t"')) - assert batches - schemas = {b.schema for b in batches} - assert len(schemas) == 1 - return schemas.pop() - - def test_spiral_itself_reports_every_column_nullable(self, fake): - """The fake, like SpiralDB, reports every column and struct field nullable.""" - SpiralDBConnector("p").upsert_records("t", _rows(), id_column="k") - stored = fake.table("default.t").schema().to_arrow() - assert all(f.nullable for f in stored) - assert stored.field("g").type.field("x").nullable - - def test_first_write_records_and_both_read_paths_restore_it(self, fake): - """The first write records nullability; get_column_info and iter_batches restore it.""" - connector = SpiralDBConnector("p") - connector.upsert_records("t", _rows(), id_column="k") - # In SpiralDB's order: the key column, then the value columns by name - # (ITL-1367). - expected = pa.schema( - [ - pa.field( - f.name, arrow_utils.normalize_to_large_types(f.type), f.nullable - ) - for f in _spiral_order(_RECORDED, ["k"]) - ] - ) - assert self._batches_schema(connector) == expected - info = connector.get_column_info("t") - assert [(c.name, c.arrow_type, c.nullable) for c in info] == [ - (f.name, f.type, f.nullable) for f in expected - ] - - def test_same_schema_writes_again(self, fake): - """A later write with the recorded nullability is accepted.""" - connector = SpiralDBConnector("p") - connector.upsert_records("t", _rows(), id_column="k") - connector.upsert_records("t", _rows(k=[4, 5, 6]), id_column="k") - assert sum(b.num_rows for b in connector.iter_batches('SELECT * FROM "t"')) == 6 - - @pytest.mark.parametrize( - ("name", "nullable", "attribute"), - [("v", True, "only_in_record"), ("w", False, "only_in_write")], - ) - def test_disagreeing_write_is_refused(self, fake, name, nullable, attribute): - """A wider or narrower write is refused, naming the paths and table; nothing is written.""" - connector = SpiralDBConnector("p") - connector.upsert_records("t", _rows(), id_column="k") - other = _with(_RECORDED, name, nullable) - rows = _rows(other, k=[4, 5, 6], w=[1, 2, 3]) - with pytest.raises(NullabilityRecordMismatchError) as info: - connector.upsert_records("t", rows, id_column="k") - assert getattr(info.value, attribute) == [name] - assert info.value.table == _TABLE - assert _TABLE in str(info.value) - assert sum(b.num_rows for b in connector.iter_batches('SELECT * FROM "t"')) == 3 - - @pytest.mark.parametrize( - ("override", "column"), - [ - ({"g": [{"x": 1, "y": 1}, {"x": None, "y": 2}, {"x": 3, "y": 3}]}, "g.x"), - ({"l": [[1.0], [None], []]}, "l[]"), - ({"v": [1, None, 3]}, "v"), - ], - ) - def test_null_in_non_nullable_column_is_refused_before_writing( - self, fake, override, column - ): - # SpiralDB stores a null in a non-null struct field as 0 (live, ITL-936), so the - # connector checks every non-nullable path itself before anything is written. - """A null in a non-null column, struct field or list item is refused before any write.""" - connector = SpiralDBConnector("p") - with pytest.raises(NullInNonNullableColumnError) as info: - connector.upsert_records("t", _rows(**override), id_column="k") - assert info.value.column == column - assert info.value.table == _TABLE - table = fake.table("default.t") - assert table.schema().to_arrow().names == ["k"] # no rows written - assert read_nullability_record(table.get_metadata()) is None - - def test_failed_first_write_leaves_no_record(self, fake, monkeypatch): - """A first write whose rows fail removes the record it wrote, so a retry works.""" - records: list[object] = [] - - def failing_write(self, table, **kwargs): - # The record is written before the rows. - records.append(read_nullability_record(self.get_metadata())) - raise RuntimeError("network down") - - db = ConnectorArrowDatabase(SpiralDBConnector("p")) - with monkeypatch.context() as m: - m.setattr(fake_pyspiral.FakeTable, "write", failing_write) - db.add_record(_PATH, "r1", _result(1)) - with pytest.raises(RuntimeError, match="network down"): - db.flush() - assert records and records[0] is not None - table = fake.table("default.results__fn") - assert read_nullability_record(table.get_metadata()) is None - assert not [k for k in table.get_metadata() if "nullability" in k] - connector = SpiralDBConnector("p") - # Without the rollback the record would name columns the table lacks, and - # get_column_info (which a result-store flush calls first) would raise. - assert [c.name for c in connector.get_column_info("results__fn")] == [ - "__record_id" - ] - id_column = ConnectorArrowDatabase.RECORD_ID_COLUMN - rows = _result(1).append_column(id_column, pa.array([b"r1"], pa.large_binary())) - connector.upsert_records("results__fn", rows, id_column=id_column) - assert read_nullability_record(table.get_metadata()) is not None - - def test_rollback_keeps_a_record_another_writers_rows_rely_on( - self, fake, monkeypatch - ): - """A failed first write keeps the record if another writer's rows landed meanwhile.""" - real = fake_pyspiral.FakeTable.write - - def other_writer_then_fail(self, table, **kwargs): - real(self, _rows(k=[7, 8, 9])) # a concurrent writer's rows land first - raise RuntimeError("network down") - - with monkeypatch.context() as m: - m.setattr(fake_pyspiral.FakeTable, "write", other_writer_then_fail) - with pytest.raises(RuntimeError, match="network down"): - SpiralDBConnector("p").upsert_records("t", _rows(), id_column="k") - table = fake.table("default.t") - assert read_nullability_record(table.get_metadata()) is not None - assert not SpiralDBConnector("p").get_column_info("t")[1].nullable - - def test_half_written_record_counts_as_none(self, fake, monkeypatch): - """Chunks written but not the header: no record, and the next write records.""" - real = fake_pyspiral.FakeTable.set_metadata - - def header_fails(self, metadata): - if "__orcapod_nullability__" in metadata: - raise RuntimeError("network down") - real(self, metadata) - - with monkeypatch.context() as m: - m.setattr(fake_pyspiral.FakeTable, "set_metadata", header_fails) - with pytest.raises(RuntimeError, match="network down"): - SpiralDBConnector("p").upsert_records("t", _rows(), id_column="k") - table = fake.table("default.t") - assert any( - k.startswith("__orcapod_nullability__/") for k in table.get_metadata() - ) - assert read_nullability_record(table.get_metadata()) is None - assert table.schema().to_arrow().names == ["k"] # no rows written - connector = SpiralDBConnector("p") - connector.upsert_records("t", _rows(), id_column="k") - assert read_nullability_record(table.get_metadata()) is not None - assert not connector.get_column_info("t")[1].nullable - - def test_table_with_rows_and_no_record_gets_none(self, fake): - """A table holding rows without a record is written as before and gets no record.""" - fake.table("default.t").write(_rows()) # an earlier writer, no record - connector = SpiralDBConnector("p") - connector.upsert_records("t", _rows(k=[4, 5, 6]), id_column="k") - assert read_nullability_record(fake.table("default.t").get_metadata()) is None - assert all(c.nullable for c in connector.get_column_info("t")) - schema = self._batches_schema(connector) - assert all(f.nullable for f in schema) - assert schema.field("g").type.field("x").nullable - - def test_unreadable_record_raises_naming_the_table(self, fake): - """A record of an unknown version raises on every read and write path, naming the table.""" - connector = SpiralDBConnector("p") - connector.upsert_records("t", _rows(), id_column="k") - table = fake.table("default.t") - header = json.loads(table.get_metadata()["__orcapod_nullability__"]) - header["version"] = 2 - table.set_metadata({"__orcapod_nullability__": json.dumps(header).encode()}) - for read in ( - lambda: connector.get_column_info("t"), - lambda: list(connector.iter_batches('SELECT * FROM "t"')), - lambda: connector.upsert_records("t", _rows(), id_column="k"), - ): - with pytest.raises(NullabilityRecordError, match="version 2") as info: - read() - assert info.value.table == _TABLE - - def test_recorded_column_missing_from_table_raises(self, fake): - """A record naming a column the table lacks raises, naming the table.""" - table = fake.table("default.t") - table.write(_rows()) - write_nullability_record( - table, _RECORDED.append(pa.field("gone", pa.int8(), False)) - ) - with pytest.raises(NullabilityRecordError, match="gone") as info: - SpiralDBConnector("p").get_column_info("t") - assert info.value.table == _TABLE - - def test_null_in_recorded_column_raises_on_read(self, fake): - # A wrong record (w holds nulls) never hides a null. - """A null in a recorded column raises on read, naming the table and column.""" - table = fake.table("default.t") - table.write(_rows()) - write_nullability_record(table, _with(_RECORDED, "w", False)) - with pytest.raises(NullInNonNullableColumnError) as info: - list(SpiralDBConnector("p").iter_batches('SELECT * FROM "t"')) - assert info.value.column == "w" - assert info.value.table == _TABLE - assert "'w'" in str(info.value) and _TABLE in str(info.value) - - def test_only_recorded_tables_pay_the_per_batch_check(self, fake, monkeypatch): - # Spies on the non-public per-batch step: the test is about when it runs. - """The per-batch check runs once per batch of a recorded table and never otherwise.""" - calls: list[int] = [] - real = spiraldb_connector.enforce_nullability_record - - def counting(batch, paths): - calls.append(batch.num_rows) - return real(batch, paths) - - monkeypatch.setattr(spiraldb_connector, "enforce_nullability_record", counting) - fake.table("default.t").write(_rows()) # no record - batches = list(SpiralDBConnector("p").iter_batches('SELECT * FROM "t"')) - assert len(batches) > 1 - assert calls == [] - - fake.create_table("default.r", key_schema=[("k", pa.int64())]) - SpiralDBConnector("p").upsert_records("r", _rows(), id_column="k") - batches = list(SpiralDBConnector("p").iter_batches('SELECT * FROM "r"')) - assert calls == [b.num_rows for b in batches] - - -# Orcapod's own results are large-typed (CLAUDE.md, Arrow types). -_RESULT = pa.schema( - [ - pa.field("score", pa.float64(), False), - pa.field("note", pa.large_string(), True), - pa.field( - "quality", - pa.struct( - [ - pa.field("snr", pa.float32(), False), - pa.field("tag", pa.large_string()), - ] - ), - False, - ), - pa.field("spikes", pa.large_list(pa.field("item", pa.float32(), False)), False), - ] -) -_FLAT_RESULT = pa.schema([_RESULT.field("score"), _RESULT.field("note")]) -_PATH = ("results", "fn") - - -def _result(i: int, schema: pa.Schema = _RESULT) -> pa.Table: - """Return one result row of ``schema``.""" - row = { - "score": [float(i)], - "note": [None if i % 2 else f"n{i}"], - "quality": [{"snr": float(i), "tag": None}], - "spikes": [[float(i)] * i], - } - return pa.table({n: row[n] for n in schema.names}, schema=schema) - - -class TestResultStoreOnSpiral: - """ConnectorArrowDatabase on SpiralDB keeps result nullability (ITL-936).""" - - @pytest.fixture() - def db(self, tmp_path: Path): - """Provide a ConnectorArrowDatabase on a fake SpiralDB project.""" - with fake_pyspiral.install(tmp_path / "spiral"): - yield ConnectorArrowDatabase(SpiralDBConnector("p")) - - def test_results_read_back_with_the_written_schema(self, db): - """Results flushed twice read back with the schema they were written with.""" - db.add_record(_PATH, "r1", _result(1)) - db.flush() - db.add_record(_PATH, "r2", _result(2)) - db.flush() - records = db.get_all_records(_PATH) - assert records is not None - assert records.num_rows == 2 - # In SpiralDB's order: the value columns by name (ITL-1367). - assert records.schema == _spiral_order(_RESULT, []) - - def test_result_table_written_before_the_record_keeps_todays_behaviour( - self, db, monkeypatch - ): - # A result table written by an Orcapod without the record (simulated by - # skipping it on the first flush) gets none later and reads back as SpiralDB - # reports it: every column nullable. - """A result table written without a record gets none and reads back all nullable.""" - with monkeypatch.context() as m: - m.setattr( - spiraldb_connector, "write_nullability_record", lambda t, s: False - ) - db.add_record(_PATH, "r1", _result(1, _FLAT_RESULT)) - db.flush() - db.add_record(_PATH, "r2", _result(2, _FLAT_RESULT)) - db.flush() - records = db.get_all_records(_PATH) - assert records is not None - assert records.num_rows == 2 - assert all(f.nullable for f in records.schema) - - def test_unrecorded_struct_result_table_cannot_take_a_second_flush( - self, db, monkeypatch - ): - # Today's behaviour on a result table without the record: SpiralDB reports the - # struct field nullable, so the flush-time type comparison fails. - """Pins today's behaviour: without a record, a struct result fails its second flush.""" - with monkeypatch.context() as m: - m.setattr( - spiraldb_connector, "write_nullability_record", lambda t, s: False - ) - db.add_record(_PATH, "r1", _result(1)) - db.flush() - db.add_record(_PATH, "r2", _result(2)) - with pytest.raises(ValueError, match="Schema mismatch"): - db.flush() - - -_INNER = pa.struct([pa.field("a", pa.int32())]) - - -class TestStructLevelNulls: - """SpiralDB cannot store a null struct (ITL-936). - - Live, pyspiral 0.16.33: written with ``push_down_nulls=True``, a null struct reads back - as a struct of null fields (value and hash change). The connector never passes - ``push_down_nulls`` and refuses a null struct at any depth before writing anything. - """ - - @pytest.fixture() - def fake(self, tmp_path: Path): - """Provide the fake project ``p`` with an empty table ``default.t`` keyed on k.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project("p") - project.create_table("default.t", key_schema=[("k", pa.int64())]) - yield project - - @pytest.mark.parametrize( - ("column", "values", "path"), - [ - ("g", pa.array([{"a": 1}, None], _INNER), "g"), - ( - "outer", - pa.array( - [{"inner": {"a": 1}}, {"inner": None}], - pa.struct([pa.field("inner", _INNER)]), - ), - "outer.inner", - ), - ("items", pa.array([[{"a": 1}], [None]], pa.list_(_INNER)), "items[]"), - ], - ) - def test_null_struct_is_refused_before_writing(self, fake, column, values, path): - """A null struct at the top level, nested or in a list is refused; nothing is written.""" - rows = pa.table({"k": pa.array([1, 2], pa.int64()), column: values}) - with pytest.raises(UnsupportedValueError) as info: - SpiralDBConnector("p").upsert_records("t", rows, id_column="k") - message = str(info.value) - assert repr(path) in message - assert _TABLE in message - table = fake.table("default.t") - assert table.schema().to_arrow().names == ["k"] # nothing written - assert read_nullability_record(table.get_metadata()) is None - - def test_struct_with_null_fields_is_written(self, fake): - """Null struct fields and null lists are written and read back unchanged.""" - rows = pa.table( - { - "k": pa.array([1, 2], pa.int64()), - "g": pa.array([{"a": 1}, {"a": None}], _INNER), - "items": pa.array([[{"a": 1}], None], pa.list_(_INNER)), - } - ) - connector = SpiralDBConnector("p") - connector.upsert_records("t", rows, id_column="k") - back = pa.Table.from_batches(connector.iter_batches('SELECT * FROM "t"')) - assert back.column("g").to_pylist() == [{"a": 1}, {"a": None}] - assert back.column("items").to_pylist() == [[{"a": 1}], None] - - def test_push_down_nulls_turns_a_null_struct_into_null_fields(self, fake): - # What any writer passing push_down_nulls=True gets (live, ITL-936). - """The fake models push_down_nulls as seen live.""" - table = fake.table("default.t") - table.write( - pa.table( - { - "k": pa.array([1, 2], pa.int64()), - "g": pa.array([{"a": 1}, None], _INNER), - } - ), - push_down_nulls=True, - ) - stored = fake_pyspiral.FakeSpiral().scan(table.select()).to_table() - assert stored.column("g").to_pylist() == [{"a": 1}, {"a": None}] - - def test_result_store_refuses_a_null_struct(self, tmp_path: Path): - """A result-store flush of a null struct raises UnsupportedValueError.""" - with fake_pyspiral.install(tmp_path / "spiral"): - db = ConnectorArrowDatabase(SpiralDBConnector("p")) - db.add_record( - ("results", "fn"), - "r1", - pa.table({"g": pa.array([None], _INNER)}), - ) - with pytest.raises(UnsupportedValueError, match="'g'"): - db.flush() - - -class TestKeptOrRefused: - """ITL-1334: SpiralDB keeps a column exactly or refuses it, naming it.""" - - @pytest.fixture() - def database(self, tmp_path: Path): - """A connector database over the fake project ``p``.""" - with fake_pyspiral.install(tmp_path / "spiral"): - fake_pyspiral.FakeSpiral().project("p") - yield ConnectorArrowDatabase(SpiralDBConnector("p")) - - @pytest.mark.parametrize("python_type", [Path, set[int]], ids=["Path", "set[int]"]) - def test_a_logical_type_is_refused_naming_the_column(self, database, python_type): - """SpiralDB drops field metadata, so the type would read back as its storage.""" - from orcapod.contexts import get_default_context - from orcapod.errors import UnstorableColumnError - - value = Path("/a") if python_type is Path else {1, 2} - table = get_default_context().type_converter.python_dicts_to_arrow_table( - [{"id": b"r1", "v": value}], - python_schema={"id": bytes, "v": python_type}, - ) - with pytest.raises(UnstorableColumnError, match="'v'.*storage type"): - database.add_records(("t",), table, record_id_column="id", flush=True) - - def test_a_fixed_size_list_with_non_null_items_and_a_null_row_reads_back( - self, database - ): - """A null row's hidden item slots are null; the read keeps the column as is - (pyarrow refuses to cast it to its own type, so only changed columns are cast).""" - item = pa.field("item", pa.int64(), nullable=False) - fsl_type: Any = pa.list_(item, 2) # pyarrow's stubs type ``type`` narrowly - column = pa.FixedSizeListArray.from_arrays( - pa.array([1, 2, None, None, 5, 6]), - type=fsl_type, - mask=pa.array([False, True, False]), - ) - table = pa.Table.from_arrays( - [pa.array([b"a", b"b", b"c"], pa.large_binary()), column], - names=["id", "f"], - ) - database.add_records(("t",), table, record_id_column="id", flush=True) - back = database.get_all_records(("t",), record_id_column="id") - assert back is not None - assert back.schema.field("f").type == pa.list_(item, 2) - assert back.sort_by("id").column("f").to_pylist() == [[1, 2], None, [5, 6]] - - @pytest.mark.parametrize( - "arrow_type", - [ - pa.uuid(), - pa.json_(), - pa.large_list(pa.uuid()), - pa.struct([pa.field("j", pa.json_())]), - ], - ids=["uuid", "json", "list of uuid", "struct of json"], - ) - def test_an_arrow_canonical_extension_type_is_refused(self, database, arrow_type): - """Arrow's own extension types (``BaseExtensionType``, not ``ExtensionType``) - would read back as their storage type too (CodeRabbit on PR 471).""" - from orcapod.errors import UnstorableColumnError - - table = pa.table( - {"id": pa.array([b"a"], pa.large_binary()), "v": pa.nulls(1, arrow_type)} - ) - with pytest.raises(UnstorableColumnError, match="'v'.*storage type"): - database.add_records(("t",), table, record_id_column="id", flush=True) - - @pytest.mark.parametrize( - "item", - [ - pa.field("value", pa.int64(), metadata={"unit": "m"}), - pa.field( - "value", pa.struct([pa.field("a", pa.int64(), metadata={"u": "m"})]) - ), - pa.field( - "value", - pa.large_list(pa.field("item", pa.int64(), metadata={"u": "m"})), - ), - ], - ids=["on the item", "inside an item struct", "inside an item list"], - ) - def test_field_metadata_below_a_map_is_refused(self, database, item): - """The connector's metadata record does not descend into a map, so such - metadata would read back dropped (CodeRabbit on PR 471).""" - from orcapod.errors import UnstorableColumnError - - map_type: Any = map_of_fields( - pa.field("key", pa.large_string(), nullable=False), item - ) - table = pa.table( - {"id": pa.array([b"a"], pa.large_binary()), "m": pa.nulls(1, map_type)} - ) - with pytest.raises(UnstorableColumnError, match="'m'.*below a map"): - database.add_records(("t",), table, record_id_column="id", flush=True) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index a6d88ff2a..f256de2fa 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -1,543 +1,317 @@ -"""Integration tests for SpiralDBConnector against the live dev project. - -These tests are skipped unless the ``SPIRAL_INTEGRATION_TESTS=1`` env var is set and -``SPIRAL_PROJECT_ID`` names the project to test against. -They require a valid auth mechanism, either: - -- Local dev: a saved ``spiral login`` (pyspiral keeps it in - ``~/Library/Application Support/pyspiral/`` on macOS, ``~/.config/pyspiral/`` on Linux) -- CI (GitHub Actions, the ``spiral-integration`` job of ``Run Tests``): a - workload private key in the ``SPIRAL_CLIENT_ID`` (workload id) and - ``SPIRAL_PRIVATE_KEY`` (private JWK naming its ``kid``) env vars, which pyspiral - reads to request a token from ``https://auth.spiraldb.com``. The workload holds - the editor role on the test project. The developer sets both repository - secrets; setup and key rotation are in ``RELEASING.md`` ("SpiralDB integration - job"). - -If the env var is set but credentials are absent, the tests fail rather than -skip — the operator is expected to ensure auth is in place when enabling -integration tests. - -Project and server URL are configurable via env vars: - -- ``SPIRAL_PROJECT_ID`` (required; no default) -- ``SPIRAL_SERVER_URL`` (default: ``https://api.spiraldb.dev``) - -Version compatibility note (PLT-1773) -------------------------------------- -pyspiral is in active development and must be kept current. The pinned version -in ``uv.lock`` should be upgraded regularly (see PLT-1785 for the tracking issue). - -History: around 2026-06-15, ``t3.storage.dev`` (SpiralDB's object-storage -backend) began strictly enforcing that every header in a presigned-URL request -must appear in ``X-Amz-SignedHeaders``. pyspiral 0.11.7's embedded Rust HTTP -client sent additional unsigned headers, causing all Vortex file reads to fail -with ``AccessDenied: There were headers present in the request which were not -signed``. Upgrading to pyspiral 0.14.x (which rewrote the HTTP stack in Python -using ``httpx``) resolved the issue. If these tests start failing with a similar -``AccessDenied`` / unsigned-headers error, upgrade pyspiral first. +"""Conformance of reading: the same tests on the fake and, opt-in, on SpiralDB (ITL-1186). + +The fake's runs are always on. The live runs need ``SPIRAL_INTEGRATION_TESTS=1``, +``SPIRAL_PROJECT_ID`` and a sign-in spiral-sdk finds in the environment (CI: +``SPIRAL_CLIENT_ID`` and ``SPIRAL_PRIVATE_KEY``, see ``RELEASING.md``); with the first two +set, a missing sign-in fails the tests rather than skipping them. ``SPIRAL_SERVER_URL`` +names another address. + +spiral-sdk cannot drop a keyed table, so a live run creates nothing anew: it uses fixed +tables in the dataset ``orcapod_conformance`` (``ORCAPOD_SPIRAL_CONFORMANCE_DATASET`` names +another), made on the first run and written the same rows at each. It writes through +spiral-sdk itself, never through Orcapod, which only reads. """ from __future__ import annotations +import datetime as dt +import math import os -import uuid +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any import pyarrow as pa -import pyarrow.compute as pc import pytest -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector -from orcapod.types import ColumnInfo - -INTEGRATION = os.environ.get("SPIRAL_INTEGRATION_TESTS") == "1" -DEV_PROJECT = os.environ.get("SPIRAL_PROJECT_ID", "") -DEV_OVERRIDES = { - "server.url": os.environ.get("SPIRAL_SERVER_URL", "https://api.spiraldb.dev") -} - -pytestmark = pytest.mark.skipif( - not (INTEGRATION and DEV_PROJECT), - reason=( - "Set SPIRAL_INTEGRATION_TESTS=1 and SPIRAL_PROJECT_ID to run SpiralDB " - "integration tests" - ), +from orcapod.databases import SpiralDBConnector +from orcapod.databases import spiraldb_schema_table as st +from orcapod.databases.spiraldb_connector import SpiralDBTableNotFoundError +from orcapod.sources import SpiralDBTableSource +from tests.test_databases import fake_spiral_sdk as fake + +_LIVE = os.environ.get("SPIRAL_INTEGRATION_TESTS") == "1" +_PROJECT = os.environ.get("SPIRAL_PROJECT_ID", "") +_URL = os.environ.get("SPIRAL_SERVER_URL", "https://api.spiraldb.dev") +_DATASET = os.environ.get("ORCAPOD_SPIRAL_CONFORMANCE_DATASET", "orcapod_conformance") + +_INNER = pa.struct([pa.field("q", pa.int8()), pa.field("b", pa.large_string(), False)]) +_UNITS = pa.schema( + [ + pa.field("zz", pa.int64(), False, {"unit": "mV"}), + pa.field( + "g", + pa.struct( + [ + pa.field("z", pa.int8(), False), + pa.field("a", _INNER, False), + pa.field("m", pa.large_string()), + ] + ), + False, + ), + pa.field("k1", pa.large_string(), False), + pa.field("aa", pa.float64()), + pa.field( + "ls", + pa.large_list(pa.struct([("z", pa.int8()), ("a", pa.int8())])), + ), + pa.field("k2", pa.int32(), False), + pa.field("fx", pa.list_(pa.field("item", pa.float32(), False), 2)), + ], + metadata={"who": "conformance"}, +) +_ROWS = pa.Table.from_pylist( + [ + { + "zz": i, + "g": {"z": i, "a": {"q": None, "b": "x"}, "m": None}, + "k1": key, + "aa": None if i == 1 else i / 2, + "ls": [{"z": 1, "a": 2}], + "k2": i % 2, + "fx": [1.0, 2.0], + } + for i, key in enumerate(["b", "a", "c"]) + ], + schema=_UNITS, +) +_TYPED = pa.table( + { + "k": pa.array([1, 2, 3], pa.int64()), + "h": pa.array([0.5, -0.0, float("nan")], pa.float64()).cast(pa.float16()), + "f": pa.array([0.1, -0.0, float("nan")], pa.float32()), + "d": pa.array([0.1, -0.0, float("nan")]), + "s": pa.array(["x", "é", None], pa.large_string()), + "b": pa.array([b"x", b"", None], pa.large_binary()), + "u": pa.array([2**64 - 1, 0, 1], pa.uint64()), + "sec": pa.array([1, 2, 3], pa.timestamp("s")), + "utc": pa.array([1, 2, 3], pa.timestamp("us", tz="UTC")), + "d32": pa.array([0, 1, None], pa.date32()), + } ) -def _unique_table(prefix: str = "test") -> str: - """Return a unique table name to avoid cross-test interference.""" - return f"{prefix}_{uuid.uuid4().hex[:8]}" +@dataclass(frozen=True) +class _Place: + """Where the tables are.""" + project: str + dataset: str + overrides: dict[str, str] | None -@pytest.fixture() -def connector(): - c = SpiralDBConnector( - project_id=DEV_PROJECT, - dataset="default", - overrides=DEV_OVERRIDES, - ) - yield c - c.close() - - -class TestSpiralDBConnectorIntegration: - def test_full_round_trip(self, connector): - """Create table → write records → scan → verify values.""" - table_name = _unique_table("roundtrip") - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("__record_id", pa.string(), nullable=False), - ColumnInfo("value", pa.float64()), - ], - pk_column="__record_id", - ) - records = pa.table( - { - "__record_id": pa.array(["r1", "r2"], type=pa.string()), - "value": pa.array([10.0, 20.0], type=pa.float64()), - } - ) - connector.upsert_records(table_name, records, id_column="__record_id") + def connector(self) -> SpiralDBConnector: + """Return a new connector.""" + return SpiralDBConnector(self.project, self.dataset, self.overrides) - result = pa.Table.from_batches( - list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - ) - assert result.num_rows == 2 - assert sorted(result.column("__record_id").to_pylist()) == ["r1", "r2"] - finally: - connector.delete_table(table_name) - - def test_skip_existing_true(self, connector): - """Write once, write again with overlapping keys — verify no duplication.""" - table_name = _unique_table("skip") - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("id", pa.string(), nullable=False), - ColumnInfo("val", pa.int64()), - ], - pk_column="id", - ) - first_write = pa.table( - {"id": ["a", "b"], "val": pa.array([1, 2], type=pa.int64())} - ) - connector.upsert_records(table_name, first_write, id_column="id") + def source(self, name: str, **options: Any) -> SpiralDBTableSource: + """Return a source on a table.""" + return SpiralDBTableSource( + self.project, + name, + dataset=self.dataset, + overrides=self.overrides, + tag_only_columns=True, + **options, + ) - second_write = pa.table( - {"id": ["a", "c"], "val": pa.array([99, 3], type=pa.int64())} - ) - connector.upsert_records( - table_name, second_write, id_column="id", skip_existing=True - ) - result = pa.Table.from_batches( - list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - ) - ids = sorted(result.column("id").to_pylist()) - assert ids == ["a", "b", "c"] - - # "a" must not have been overwritten (skip_existing=True preserved original val=1) - a_mask = pc.equal(result.column("id"), pa.scalar("a")) - a_val = result.filter(a_mask).column("val")[0].as_py() - assert a_val == 1 - finally: - connector.delete_table(table_name) - - def test_connector_arrow_database_round_trip(self, connector): - """ConnectorArrowDatabase: add_record → flush → get_record_by_id.""" - # Use a unique path so each CI run creates a fresh table and never - # conflicts with tables left by earlier runs (e.g. with a different - # __record_id Arrow type from a schema-migration commit). - unique_suffix = uuid.uuid4().hex[:8] - path = ("spiraldb", f"integration_{unique_suffix}") - # Table name mirrors ConnectorArrowDatabase._path_to_table_name logic. - table_name = f"spiraldb__integration_{unique_suffix}" - db = ConnectorArrowDatabase(connector) - record = pa.table({"x": pa.array([42], type=pa.int64())}) - try: - db.add_record( - path, - record_id=b"test_r1", - record=record, - flush=True, - ) - result = db.get_record_by_id(path, b"test_r1") - assert result is not None - assert result.column("x")[0].as_py() == 42 - finally: - connector.delete_table(table_name) - - -class TestArrowMetadataRoundTrip: - """Integration tests for Arrow metadata preservation across write→read cycles. - - Requires ``SPIRAL_INTEGRATION_TESTS=1`` and valid SpiralDB credentials. - """ - - def test_schema_metadata_round_trip(self, connector): - """Schema-level metadata survives a full write→read cycle.""" - table_name = _unique_table("schema_meta") - schema = pa.schema( - [ - pa.field("__record_id", pa.string(), nullable=False), - pa.field("value", pa.float64()), - ], - metadata={b"origin": b"test-suite", b"version": b"1"}, +def _seed(client: Any, place: _Place) -> None: + """Write the tables and, once, their schema rows, through the SDK.""" + project = client.project(place.project) + made = {} + for name, keys, rows in ( + ("units", ["k2", "k1"], _ROWS), + ("typed", ["k"], _TYPED), + ): + key_schema = pa.schema([rows.schema.field(k) for k in keys]) + table = project.create_keyed_table( + place.dataset, name, key_schema, exist_ok=True ) - records = pa.table( - {"__record_id": pa.array(["r1"]), "value": pa.array([1.0])}, - schema=schema, + made[name] = (table.append(rows), rows.schema) + schemas = project.create_keyed_table( + place.dataset, st.SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=True + ) + if st.require_schema_table(schemas): + return + rows = [] + for name, (table, written) in made.items(): + presented = pa.schema( + [_in_order(f, written.field(f.name)) for f in table.schema()], + metadata=written.metadata, ) - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("__record_id", pa.string(), nullable=False), - ColumnInfo("value", pa.float64()), - ], - pk_column="__record_id", + rows.append( + st.SchemaRow( + table.resource_id, + name, + tuple(table.key_columns), + presented.serialize().to_pybytes(), + st.FROM_RECORD, + int(table.version_id), ) - connector.upsert_records(table_name, records, id_column="__record_id") - - batches = list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - result = pa.Table.from_batches(batches) - assert result.schema.metadata is not None - assert result.schema.metadata.get(b"origin") == b"test-suite" - assert result.schema.metadata.get(b"version") == b"1" - finally: - connector.delete_table(table_name) - - def test_field_metadata_round_trip(self, connector): - """Per-column field metadata survives a full write→read cycle.""" - table_name = _unique_table("field_meta") - schema = pa.schema( - [ - pa.field("__record_id", pa.string(), nullable=False), - pa.field( - "value", - pa.float64(), - metadata={b"unit": b"meters", b"sensor": b"lidar"}, - ), - ] ) - records = pa.table( - {"__record_id": pa.array(["r1"]), "value": pa.array([42.0])}, - schema=schema, - ) - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("__record_id", pa.string(), nullable=False), - ColumnInfo("value", pa.float64()), - ], - pk_column="__record_id", + scope = st.Scope(place.project, place.dataset, "0" * 64) + for values in (*(r.stored() for r in rows), st.marker_values(scope, rows)): + schemas.append( + pa.Table.from_pylist( + [{"written_at": "", "written_by": "", **values}], schema=st.ROW_SCHEMA ) - connector.upsert_records(table_name, records, id_column="__record_id") - - batches = list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - result = pa.Table.from_batches(batches) - value_meta = result.schema.field("value").metadata - assert value_meta is not None - assert value_meta.get(b"unit") == b"meters" - assert value_meta.get(b"sensor") == b"lidar" - finally: - connector.delete_table(table_name) - - def test_extension_type_metadata_round_trip(self, connector): - """ARROW:extension:name / ARROW:extension:metadata field metadata survives.""" - table_name = _unique_table("ext_meta") - ext_field = pa.field( - "path_col", - pa.large_string(), - metadata={ - b"ARROW:extension:name": b"orcapod.path", - b"ARROW:extension:metadata": b"", - }, - ) - schema = pa.schema( - [ - pa.field("__record_id", pa.string(), nullable=False), - ext_field, - ] - ) - records = pa.table( - { - "__record_id": pa.array(["r1"]), - "path_col": pa.array(["/tmp/test"], type=pa.large_string()), - }, - schema=schema, - ) - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("__record_id", pa.string(), nullable=False), - ColumnInfo("path_col", pa.large_string()), - ], - pk_column="__record_id", - ) - connector.upsert_records(table_name, records, id_column="__record_id") - - batches = list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - result = pa.Table.from_batches(batches) - meta = result.schema.field("path_col").metadata - assert meta is not None - assert meta.get(b"ARROW:extension:name") == b"orcapod.path" - finally: - connector.delete_table(table_name) - - def test_no_metadata_backward_compatible(self, connector): - """Plain tables with no Arrow metadata read back without spurious KV entries.""" - table_name = _unique_table("no_meta") - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("__record_id", pa.string(), nullable=False), - ColumnInfo("value", pa.int64()), - ], - pk_column="__record_id", - ) - records = pa.table( - { - "__record_id": pa.array(["r1"]), - "value": pa.array([99], type=pa.int64()), - } - ) - connector.upsert_records(table_name, records, id_column="__record_id") - - batches = list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - result = pa.Table.from_batches(batches) - assert result.schema.metadata is None - for field in result.schema: - assert field.metadata is None - finally: - connector.delete_table(table_name) - - def test_connector_arrow_database_extension_type_round_trip(self, connector): - """Full ConnectorArrowDatabase path: write extension-typed column, read back intact.""" - unique_suffix = uuid.uuid4().hex[:8] - path = ("spiraldb", f"ext_roundtrip_{unique_suffix}") - table_name = f"spiraldb__ext_roundtrip_{unique_suffix}" - - ext_field = pa.field( - "path_col", - pa.large_string(), - metadata={ - b"ARROW:extension:name": b"orcapod.path", - b"ARROW:extension:metadata": b"", - }, - ) - schema = pa.schema([pa.field("__record_id", pa.large_binary()), ext_field]) - record = pa.table( - { - "__record_id": pa.array([b"test_r1"], type=pa.large_binary()), - "path_col": pa.array(["/data/file.npy"], type=pa.large_string()), - }, - schema=schema, ) - db = ConnectorArrowDatabase(connector) - try: - db.add_record(path, record_id=b"test_r1", record=record, flush=True) - result = db.get_record_by_id(path, b"test_r1") - assert result is not None - meta = result.schema.field("path_col").metadata - assert meta is not None - assert meta.get(b"ARROW:extension:name") == b"orcapod.path" - finally: - connector.delete_table(table_name) - - def test_nested_struct_field_metadata_round_trip(self, connector): - """Struct columns with inner-field metadata survive a full write→read cycle.""" - table_name = _unique_table("struct_meta") - inner_field = pa.field("val", pa.float64(), metadata={b"unit": b"volts"}) - struct_col = pa.field("measurement", pa.struct([inner_field])) - schema = pa.schema( - [ - pa.field("__record_id", pa.string(), nullable=False), - struct_col, - ] - ) - records = pa.table( - { - "__record_id": pa.array(["r1"]), - "measurement": pa.array( - [{"val": 3.14}], - type=pa.struct([pa.field("val", pa.float64())]), - ), - }, - schema=schema, - ) - try: - connector.create_table_if_not_exists( - table_name, - columns=[ - ColumnInfo("__record_id", pa.string(), nullable=False), - ColumnInfo( - "measurement", pa.struct([pa.field("val", pa.float64())]) - ), - ], - pk_column="__record_id", - ) - connector.upsert_records(table_name, records, id_column="__record_id") - - batches = list(connector.iter_batches(f'SELECT * FROM "{table_name}"')) - result = pa.Table.from_batches(batches) - inner = result.schema.field("measurement").type.field("val") - assert inner.metadata is not None - assert inner.metadata.get(b"unit") == b"volts" - finally: - connector.delete_table(table_name) - -class TestReservedNamesRefusedLive: - """ITL-1162 / ITL-1164 against the live service (opt-in, like every test here). +def _in_order(found: Any, written: Any) -> Any: + """Return the written field with its struct fields in SpiralDB's order.""" + if not pa.types.is_struct(written.type): + return written + return written.with_type( + pa.struct([_in_order(f, written.type.field(f.name)) for f in found.type]) + ) - The refusal itself is decided by ``SpiralDBConnector.unstorable_column_reason`` - before any request; the second test checks the rule against SpiralDB's own - refusals, so the fake's model of them stays honest. - """ - def test_function_node_job_refused_before_anything_runs(self, connector): - from orcapod import PipelineJob, function_pod - from orcapod.errors import UnstorableColumnError - from orcapod.sources import DictSource +@pytest.fixture( + scope="module", + params=[ + "fake", + pytest.param( + "live", + marks=pytest.mark.skipif( + not (_LIVE and _PROJECT), + reason="Set SPIRAL_INTEGRATION_TESTS=1 and SPIRAL_PROJECT_ID", + ), + ), + ], +) +def place( + request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory +) -> Iterator[_Place]: + """The seeded tables, on the fake or on SpiralDB.""" + if request.param == "fake": + root: Path = tmp_path_factory.mktemp("spiral") + with fake.install(root): + made = _Place("p", _DATASET, None) + _seed(fake.FakeClient(), made) + yield made + return + made = _Place(_PROJECT, _DATASET, {"server.url": _URL}) + with made.connector() as connector: + _seed(connector._client, made) # pyright: ignore[reportPrivateUsage] # the SDK's client, for the test's own writes + yield made + + +def test_the_listing_holds_the_tables_and_not_the_schema_table(place: _Place) -> None: + names = place.connector().get_table_names() + assert {"units", "typed"} <= set(names) + assert st.SCHEMA_TABLE not in names + assert names == sorted(names) + + +def test_the_presented_schema(place: _Place) -> None: + connector = place.connector() + schema = connector.get_arrow_schema("units") + assert connector.get_pk_columns("units") == ["k2", "k1"] + assert schema.names == ["k2", "k1", "aa", "fx", "ls", "zz", "g"] + group = schema.field("g").type + assert [f.name for f in group] == ["m", "z", "a"] + assert [f.name for f in group.field("a").type] == ["b", "q"] + assert [f.name for f in schema.field("ls").type.value_type] == ["z", "a"] + assert schema.metadata == {b"who": b"conformance"} + assert schema.field("zz").metadata == {b"unit": b"mV"} + assert [f.name for f in schema if not f.nullable] == ["k2", "k1", "zz", "g"] + assert not group.field("z").nullable + assert group.field("m").nullable + assert not group.field("a").type.field("b").nullable + for batch in connector.scan_batches("units"): + assert batch.schema.equals(schema, check_metadata=True) + + +def test_rows_in_key_order_with_their_values(place: _Place) -> None: + table = pa.Table.from_batches(place.connector().scan_batches("units")) + keys = list(zip(table["k2"].to_pylist(), table["k1"].to_pylist())) + assert keys == [(0, "b"), (0, "c"), (1, "a")] + by_key = {(r["k2"], r["k1"]): r for r in _ROWS.to_pylist()} + assert [by_key[k] for k in keys] == table.to_pylist() + + +def test_source_identity_and_rows(place: _Place) -> None: + source = place.source("units") + assert source.source_id == ( + f"spiraldb_table_v1:{place.project}.{place.dataset}.units@" + f"{place.connector().get_spiral_table_id('units')}" + ) + tags, data = source.output_schema() + assert dict(tags) == {"k2": int, "k1": str} + assert data["zz"] is int + rows = [(t.as_dict(), d.as_dict()) for t, d in source.iter_data()] + assert [t["k1"] for t, _ in rows] == ["b", "c", "a"] + again = place.source("units") + assert again.content_hash() == source.content_hash() + assert again.pipeline_hash() == source.pipeline_hash() + + +@pytest.mark.parametrize("limit", [1, 2, 3, 9]) +def test_limit_reads_the_first_keys(place: _Place, limit: int) -> None: + table = pa.Table.from_batches(place.connector().scan_batches("units", limit=limit)) + assert table["k1"].to_pylist() == ["b", "c", "a"][:limit] + + +@pytest.mark.parametrize( + ("where", "expected"), + [ + ({"h": 0.5}, [1]), + ({"h": -0.0}, [2]), + ({"h": math.nan}, [3]), + ({"f": 0.1}, []), + ({"f": -0.0}, [2]), + ({"f": math.nan}, [3]), + ({"f": 1e300}, []), + ({"d": 0.1}, [1]), + ({"d": 0.0}, []), + ({"s": "é"}, [2]), + ({"b": b""}, [2]), + ({"u": 2**64 - 1}, [1]), + ({"u": 0}, [2]), + ({"sec": dt.datetime(1970, 1, 1, 0, 0, 1)}, [1]), + ({"utc": dt.datetime(1970, 1, 1, 0, 0, 0, 2, dt.timezone.utc)}, [2]), + ({"d32": dt.date(1970, 1, 2)}, [2]), + ({"s": "x", "k": 1}, [1]), + ({"k": 1, "s": "é"}, []), + ({"h": 0.5, "s": "x"}, [1]), + ({"s": "x", "h": 0.5}, [1]), + ({"k": 1, "s": "x"}, [1]), + ({"s": "é", "k": 1}, []), + ], +) +def test_where(place: _Place, where: dict[str, Any], expected: list[int]) -> None: + batches = place.connector().scan_batches("typed", where=where) + assert [k for b in batches for k in b.column("k").to_pylist()] == expected - calls: list[int] = [] - @function_pod(output_keys="double") - def double(x: int) -> int: - calls.append(x) - return 2 * x +def test_counts(place: _Place) -> None: + table = place.connector().lookup_table("units") + assert table.count_rows(at_most=2) == 2 + assert table.row_count_estimate() == 3 - job = PipelineJob( - name=_unique_table("itl1162"), database=ConnectorArrowDatabase(connector) - ) - source = DictSource( - data=[{"k": "a", "x": 1}], - tag_columns=["k"], - tag_only_columns=True, - source_id="src", - ) - with pytest.raises(UnstorableColumnError) as exc_info: - with job: - _ = double.pod(source, label="dbl") - assert exc_info.value.column == "__input_data_hash" - assert calls == [] - - @pytest.mark.parametrize("name", ["__value", "a.b"]) - def test_spiraldb_itself_refuses_the_names_the_connector_refuses( - self, connector, name - ): - assert ( - connector.unstorable_column_reason(name, pa.int64(), primary_key=False) - is not None - ) - table = _unique_table("itl1162_names") - try: - connector.create_table_if_not_exists( - table, - [ - ColumnInfo("k", pa.large_string(), nullable=False), - ColumnInfo(name, pa.int64(), nullable=True), - ], - pk_column="k", - ) - rows = pa.table( - { - "k": pa.array(["a"], type=pa.large_string()), - name: pa.array([1], type=pa.int64()), - } - ) - with pytest.raises(Exception, match="reserved"): - connector.upsert_records(table, rows, id_column="k") - finally: - if table in connector.get_table_names(): - connector.delete_table(table) - - -def _ordered_rows(order: list[str], ns: list[int]) -> pa.Table: - """Rows ``ns`` with the columns in ``order``; ``a`` and ``c`` are both ``int64``, - so a positional match would swap them.""" - columns = { - "__record_id": pa.array([f"r{n}".encode() for n in ns], pa.large_binary()), - "a": pa.array(ns, pa.int64()), - "c": pa.array([100 + n for n in ns], pa.int64()), - "b": pa.array([f"b{n}" for n in ns], pa.large_string()), - } - return pa.table({name: columns[name] for name in order}) +def test_versions(place: _Place) -> None: + connector = place.connector() + version = connector.get_table_version("units") + assert version > 0 + pinned = pa.Table.from_batches(connector.scan_batches("units", asof=version)) + latest = pa.Table.from_batches(connector.scan_batches("units")) + assert pinned.equals(latest) -def _by_name(table: pa.Table) -> list[dict[str, object]]: - return sorted( - table.select(["__record_id", "a", "c", "b"]).to_pylist(), key=lambda r: r["a"] - ) +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) + with pytest.raises(SpiralDBTableNotFoundError): + missing.lookup_table("absent") + assert missing.get_table_names() == [] -class TestColumnOrderLive: - """SpiralDB matches a write's columns by name and keeps an order of its own: the - key columns, then the value columns sorted by name, whatever the order written - (ITL-1367; the fake does the same).""" - def test_a_raw_write_in_another_order_is_matched_by_name(self, connector): - table = _unique_table("itl1367_raw") - try: - first = ["__record_id", "a", "c", "b"] - connector.create_table_if_not_exists( - table, - [ - ColumnInfo(n, _ordered_rows(first, [1]).schema.field(n).type) - for n in first - ], - pk_column="__record_id", - ) - connector.upsert_records(table, _ordered_rows(first, [1, 2]), "__record_id") - connector.upsert_records( - table, - _ordered_rows(["b", "c", "__record_id", "a"], [3, 4]), - "__record_id", - ) - read = pa.Table.from_batches( - list(connector.iter_batches(f'SELECT * FROM "{table}"')) - ) - assert read.column_names == ["__record_id", "a", "b", "c"] - assert _by_name(read) == _by_name(_ordered_rows(first, [1, 2, 3, 4])) - finally: - if table in connector.get_table_names(): - connector.delete_table(table) - - @pytest.mark.parametrize("when", ["after a flush", "same pending batch"]) - def test_the_database_matches_an_append_in_another_order_by_name( - self, connector, when - ): - path = (_unique_table("itl1367_db"),) - db = ConnectorArrowDatabase(connector) - try: - first = ["__record_id", "a", "c", "b"] - db.add_records( - path, _ordered_rows(first, [1, 2]), flush=when == "after a flush" - ) - db.add_records( - path, - _ordered_rows(["b", "c", "__record_id", "a"], [3, 4]), - record_id_column="__record_id", - ) - db.add_records( - path, - _ordered_rows(["c", "__record_id", "b", "a"], [5]), - record_id_column="__record_id", - ) - db.flush() - read = db.get_all_records(path, record_id_column="__record_id") - assert read is not None - assert read.column_names == ["__record_id", "a", "b", "c"] - assert _by_name(read) == _by_name(_ordered_rows(first, [1, 2, 3, 4, 5])) - finally: - if path[0] in connector.get_table_names(): - connector.delete_table(path[0]) +def test_an_early_close(place: _Place) -> None: + batches: Any = place.connector().scan_batches("units") + assert next(batches).num_rows > 0 + batches.close() diff --git a/tests/test_databases/test_spiraldb_metadata_helpers.py b/tests/test_databases/test_spiraldb_metadata_helpers.py deleted file mode 100644 index b85704176..000000000 --- a/tests/test_databases/test_spiraldb_metadata_helpers.py +++ /dev/null @@ -1,381 +0,0 @@ -"""Pure-function tests for SpiralDB Arrow metadata helpers.""" - -from __future__ import annotations - -import base64 -import json - -import pyarrow as pa - -from orcapod.databases.spiraldb_connector import ( - _ARROW_METADATA_KEY, - _load_arrow_metadata, - _restore_field, - _serialize_arrow_metadata, - _serialize_field_meta_tree, -) - - -def b64(s: bytes) -> str: - return base64.b64encode(s).decode() - - -# --------------------------------------------------------------------------- -# _serialize_field_meta_tree -# --------------------------------------------------------------------------- - - -class TestSerializeFieldMetaTree: - def test_primitive_with_metadata(self): - field = pa.field("x", pa.int64(), metadata={b"unit": b"meters"}) - result = _serialize_field_meta_tree(field) - assert result == {"meta": {b64(b"unit"): b64(b"meters")}} - - def test_primitive_no_metadata_returns_none(self): - field = pa.field("x", pa.int64()) - assert _serialize_field_meta_tree(field) is None - - def test_struct_with_child_metadata(self): - inner = pa.field("val", pa.float64(), metadata={b"key": b"v"}) - field = pa.field("s", pa.struct([inner])) - result = _serialize_field_meta_tree(field) - assert result == {"children": {"val": {"meta": {b64(b"key"): b64(b"v")}}}} - - def test_struct_with_both_own_and_child_metadata(self): - inner = pa.field("val", pa.float64(), metadata={b"k": b"v"}) - field = pa.field("s", pa.struct([inner]), metadata={b"tag": b"yes"}) - result = _serialize_field_meta_tree(field) - assert result == { - "meta": {b64(b"tag"): b64(b"yes")}, - "children": {"val": {"meta": {b64(b"k"): b64(b"v")}}}, - } - - def test_struct_child_no_metadata_not_included(self): - inner_with = pa.field("a", pa.int64(), metadata={b"k": b"v"}) - inner_without = pa.field("b", pa.int64()) - field = pa.field("s", pa.struct([inner_with, inner_without])) - result = _serialize_field_meta_tree(field) - assert "children" in result - assert "a" in result["children"] - assert "b" not in result["children"] - - def test_list_value_field_with_metadata(self): - vf = pa.field("item", pa.int32(), metadata={b"k": b"v"}) - field = pa.field("lst", pa.list_(vf)) - result = _serialize_field_meta_tree(field) - assert result == {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}} - - def test_large_list_value_field_with_metadata(self): - vf = pa.field("item", pa.int32(), metadata={b"k": b"v"}) - field = pa.field("lst", pa.large_list(vf)) - result = _serialize_field_meta_tree(field) - assert result == {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}} - - def test_fixed_size_list_value_field_with_metadata(self): - vf = pa.field("item", pa.float32(), metadata={b"k": b"v"}) - field = pa.field("lst", pa.list_(vf, 3)) - result = _serialize_field_meta_tree(field) - assert result == {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}} - - def test_nested_struct_in_struct(self): - leaf = pa.field("z", pa.int8(), metadata={b"deep": b"yes"}) - inner_struct = pa.field("inner", pa.struct([leaf])) - outer = pa.field("outer", pa.struct([inner_struct])) - result = _serialize_field_meta_tree(outer) - assert result == { - "children": { - "inner": {"children": {"z": {"meta": {b64(b"deep"): b64(b"yes")}}}} - } - } - - def test_no_metadata_anywhere_returns_none(self): - inner = pa.field("a", pa.int64()) - field = pa.field("s", pa.struct([inner])) - assert _serialize_field_meta_tree(field) is None - - def test_map_children_not_recursed(self): - # pa.map_ key/item fields are not recursed — pa.map_() constructor - # does not support field-level metadata on key/item fields. - field = pa.field("m", pa.map_(pa.string(), pa.int32())) - # No metadata on the outer field, no recursion into map children - assert _serialize_field_meta_tree(field) is None - - # Even if the outer field has metadata, children are not in the result - field_with_meta = pa.field( - "m", pa.map_(pa.string(), pa.int32()), metadata={b"tag": b"yes"} - ) - result = _serialize_field_meta_tree(field_with_meta) - assert result == {"meta": {b64(b"tag"): b64(b"yes")}} - assert "children" not in result - - -# --------------------------------------------------------------------------- -# _serialize_arrow_metadata -# --------------------------------------------------------------------------- - - -class TestSerializeArrowMetadata: - def test_no_metadata_returns_none(self): - table = pa.table({"x": pa.array([1, 2], type=pa.int64())}) - assert _serialize_arrow_metadata(table) is None - - def test_schema_metadata_only(self): - table = pa.table( - {"x": pa.array([1], type=pa.int64())}, - schema=pa.schema( - [pa.field("x", pa.int64())], - metadata={b"origin": b"test"}, - ), - ) - result = _serialize_arrow_metadata(table) - assert result is not None - assert _ARROW_METADATA_KEY in result - blob = json.loads(result[_ARROW_METADATA_KEY].decode()) - assert blob["schema"] == {b64(b"origin"): b64(b"test")} - assert "fields" not in blob - - def test_field_metadata_only(self): - schema = pa.schema([pa.field("x", pa.int64(), metadata={b"unit": b"m"})]) - table = pa.table({"x": pa.array([1], type=pa.int64())}, schema=schema) - result = _serialize_arrow_metadata(table) - assert result is not None - blob = json.loads(result[_ARROW_METADATA_KEY].decode()) - assert "schema" not in blob - assert blob["fields"]["x"] == {"meta": {b64(b"unit"): b64(b"m")}} - - def test_nested_field_metadata(self): - inner = pa.field("val", pa.float64(), metadata={b"k": b"v"}) - schema = pa.schema([pa.field("s", pa.struct([inner]))]) - table = pa.table( - { - "s": pa.array( - [{"val": 1.0}], type=pa.struct([pa.field("val", pa.float64())]) - ) - }, - schema=schema, - ) - result = _serialize_arrow_metadata(table) - assert result is not None - blob = json.loads(result[_ARROW_METADATA_KEY].decode()) - assert blob["fields"]["s"] == { - "children": {"val": {"meta": {b64(b"k"): b64(b"v")}}} - } - - def test_returns_bytes_value(self): - schema = pa.schema([pa.field("x", pa.int64())], metadata={b"k": b"v"}) - table = pa.table({"x": pa.array([1])}, schema=schema) - result = _serialize_arrow_metadata(table) - assert isinstance(result[_ARROW_METADATA_KEY], bytes) - - -# --------------------------------------------------------------------------- -# _load_arrow_metadata -# --------------------------------------------------------------------------- - - -class TestLoadArrowMetadata: - def test_empty_kv_returns_none_schema_and_empty_fields(self): - schema_meta, field_trees = _load_arrow_metadata({}) - assert schema_meta is None - assert field_trees == {} - - def test_key_absent_returns_none_schema_and_empty_fields(self): - schema_meta, field_trees = _load_arrow_metadata({"other": b"val"}) - assert schema_meta is None - assert field_trees == {} - - def test_schema_metadata_decoded(self): - blob = {"schema": {b64(b"origin"): b64(b"test"), b64(b"key2"): b64(b"val2")}} - kv = {_ARROW_METADATA_KEY: json.dumps(blob).encode("utf-8")} - schema_meta, field_trees = _load_arrow_metadata(kv) - assert schema_meta == {b"origin": b"test", b"key2": b"val2"} - assert field_trees == {} - - def test_field_trees_returned_raw(self): - raw_fields = { - "col1": {"meta": {b64(b"unit"): b64(b"meters")}}, - "col2": {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}}, - } - blob = {"fields": raw_fields} - kv = {_ARROW_METADATA_KEY: json.dumps(blob).encode("utf-8")} - schema_meta, field_trees = _load_arrow_metadata(kv) - assert schema_meta is None - assert field_trees == raw_fields - - def test_schema_and_fields_together(self): - blob = { - "schema": {b64(b"origin"): b64(b"test")}, - "fields": {"x": {"meta": {b64(b"unit"): b64(b"m")}}}, - } - kv = {_ARROW_METADATA_KEY: json.dumps(blob).encode("utf-8")} - schema_meta, field_trees = _load_arrow_metadata(kv) - assert schema_meta == {b"origin": b"test"} - assert field_trees == {"x": {"meta": {b64(b"unit"): b64(b"m")}}} - - def test_roundtrip_with_serialize(self): - inner = pa.field("val", pa.float64(), metadata={b"desc": b"the value"}) - schema = pa.schema( - [ - pa.field("x", pa.int64(), metadata={b"unit": b"meters"}), - pa.field("s", pa.struct([inner])), - ], - metadata={b"origin": b"roundtrip_test"}, - ) - table = pa.table( - { - "x": pa.array([1, 2], type=pa.int64()), - "s": pa.array( - [{"val": 1.0}, {"val": 2.0}], - type=pa.struct([pa.field("val", pa.float64())]), - ), - }, - schema=schema, - ) - serialized = _serialize_arrow_metadata(table) - assert serialized is not None - schema_meta, field_trees = _load_arrow_metadata(serialized) - assert schema_meta == {b"origin": b"roundtrip_test"} - assert "x" in field_trees - assert field_trees["x"]["meta"] == {b64(b"unit"): b64(b"meters")} - assert "s" in field_trees - assert "children" in field_trees["s"] - assert "val" in field_trees["s"]["children"] - - def test_corrupt_json_returns_empty(self): - """Key present but value is not valid JSON → returns (None, {}) and logs warning.""" - from orcapod.databases.spiraldb_connector import _ARROW_METADATA_KEY - - kv = {_ARROW_METADATA_KEY: b"not valid json {{{"} - schema_meta, field_trees = _load_arrow_metadata(kv) - assert schema_meta is None - assert field_trees == {} - - def test_invalid_utf8_returns_empty(self): - """Key present but value is not valid UTF-8 → returns (None, {}) and logs warning.""" - from orcapod.databases.spiraldb_connector import _ARROW_METADATA_KEY - - kv = {_ARROW_METADATA_KEY: b"\xff\xfe invalid utf-8 \x80"} - schema_meta, field_trees = _load_arrow_metadata(kv) - assert schema_meta is None - assert field_trees == {} - - -# --------------------------------------------------------------------------- -# _restore_field -# --------------------------------------------------------------------------- - - -class TestRestoreField: - def test_none_stored_returns_unchanged(self): - field = pa.field("x", pa.int64()) - restored, changed = _restore_field(field, None) - assert restored is field - assert changed is False - - def test_empty_dict_stored_returns_unchanged(self): - field = pa.field("x", pa.int64()) - restored, changed = _restore_field(field, {}) - assert restored is field - assert changed is False - - def test_primitive_with_meta_restored(self): - field = pa.field("x", pa.int64()) - stored = {"meta": {b64(b"unit"): b64(b"meters")}} - restored, changed = _restore_field(field, stored) - assert changed is True - assert restored.metadata == {b"unit": b"meters"} - assert restored.name == "x" - assert restored.type == pa.int64() - - def test_primitive_already_has_different_meta_overwritten(self): - field = pa.field("x", pa.int64(), metadata={b"old": b"meta"}) - stored = {"meta": {b64(b"new"): b64(b"meta2")}} - restored, changed = _restore_field(field, stored) - assert changed is True - assert restored.metadata == {b"new": b"meta2"} - - def test_struct_child_meta_restored(self): - inner = pa.field("val", pa.float64()) - field = pa.field("s", pa.struct([inner])) - stored = {"children": {"val": {"meta": {b64(b"desc"): b64(b"the value")}}}} - restored, changed = _restore_field(field, stored) - assert changed is True - assert pa.types.is_struct(restored.type) - restored_inner = restored.type.field("val") - assert restored_inner.metadata == {b"desc": b"the value"} - - def test_struct_no_child_meta_unchanged(self): - inner = pa.field("val", pa.float64()) - field = pa.field("s", pa.struct([inner])) - stored = {} - restored, changed = _restore_field(field, stored) - assert restored is field - assert changed is False - - def test_list_value_field_meta_restored(self): - vf = pa.field("item", pa.int32()) - field = pa.field("lst", pa.list_(vf)) - stored = {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}} - restored, changed = _restore_field(field, stored) - assert changed is True - assert pa.types.is_list(restored.type) - restored_vf = restored.type.value_field - assert restored_vf.metadata == {b"k": b"v"} - - def test_large_list_value_field_meta_restored(self): - vf = pa.field("item", pa.int32()) - field = pa.field("lst", pa.large_list(vf)) - stored = {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}} - restored, changed = _restore_field(field, stored) - assert changed is True - assert pa.types.is_large_list(restored.type) - restored_vf = restored.type.value_field - assert restored_vf.metadata == {b"k": b"v"} - - def test_nested_struct_deep_meta_restored(self): - leaf = pa.field("z", pa.int8()) - inner_struct_field = pa.field("inner", pa.struct([leaf])) - outer_field = pa.field("outer", pa.struct([inner_struct_field])) - stored = { - "children": { - "inner": {"children": {"z": {"meta": {b64(b"deep"): b64(b"yes")}}}} - } - } - restored, changed = _restore_field(outer_field, stored) - assert changed is True - assert pa.types.is_struct(restored.type) - inner_restored = restored.type.field("inner") - assert pa.types.is_struct(inner_restored.type) - leaf_restored = inner_restored.type.field("z") - assert leaf_restored.metadata == {b"deep": b"yes"} - - def test_changed_false_when_nothing_to_restore(self): - field = pa.field("x", pa.int64()) - _, changed = _restore_field(field, None) - assert changed is False - - def test_changed_true_when_meta_restored(self): - field = pa.field("x", pa.int64()) - stored = {"meta": {b64(b"unit"): b64(b"meters")}} - _, changed = _restore_field(field, stored) - assert changed is True - - def test_primitive_already_has_same_meta_unchanged(self): - # When stored metadata equals the field's existing metadata, - # the function should return the original field (identity) and changed=False. - field = pa.field("x", pa.int64(), metadata={b"unit": b"meters"}) - # Simulate what _restore_field receives: the stored tree has the same metadata - stored = {"meta": {b64(b"unit"): b64(b"meters")}} - restored, changed = _restore_field(field, stored) - assert not changed - assert restored is field - - def test_fixed_size_list_value_field_meta_restored(self): - vf = pa.field("item", pa.float32()) - field = pa.field("lst", pa.list_(vf, 4)) # fixed_size_list[4] - stored = {"children": {"item": {"meta": {b64(b"k"): b64(b"v")}}}} - restored, changed = _restore_field(field, stored) - assert changed is True - assert pa.types.is_fixed_size_list(restored.type) - restored_vf = restored.type.value_field - assert restored_vf.metadata == {b"k": b"v"} diff --git a/tests/test_databases/test_spiraldb_nullability.py b/tests/test_databases/test_spiraldb_nullability.py deleted file mode 100644 index 9897a6cc1..000000000 --- a/tests/test_databases/test_spiraldb_nullability.py +++ /dev/null @@ -1,208 +0,0 @@ -"""The Spiral nullability record (ITL-936): writing, reading and its integrity checks. - -SpiralDB reports every top-level column and every struct field nullable, whatever was -written, so Orcapod records the non-nullable column paths in the table's key-value metadata. -These tests drive the two public helpers, ``write_nullability_record`` and -``read_nullability_record``, against a table of the disk-backed pyspiral fake. -""" - -from __future__ import annotations - -import hashlib -import json -from pathlib import Path -from typing import Any - -import pyarrow as pa -import pytest - -from orcapod.databases import read_nullability_record, write_nullability_record -from orcapod.errors import NullabilityRecordError -from tests.test_databases import fake_pyspiral - -_KEY = "__orcapod_nullability__" - -_SCHEMA = pa.schema( - [ - pa.field("k", pa.int64(), False), - pa.field("v", pa.int32(), True), - pa.field( - "g", - pa.struct( - [pa.field("x", pa.int32(), False), pa.field("y", pa.int32(), True)] - ), - False, - ), - pa.field("l", pa.list_(pa.field("item", pa.float32(), False)), False), - pa.field("f", pa.list_(pa.field("item", pa.float32(), True), 2), True), - pa.field( - "n", - pa.large_list(pa.struct([pa.field("a", pa.string(), False)])), - True, - ), - pa.field("m", pa.map_(pa.string(), pa.int64()), True), - ] -) -_PATHS = frozenset({("k",), ("g",), ("g", "x"), ("l",), ("l", "[]"), ("n", "[]", "a")}) - - -@pytest.fixture() -def table(tmp_path: Path): - """Provide an empty fake Spiral table to hold metadata.""" - with fake_pyspiral.install(tmp_path / "spiral"): - yield ( - fake_pyspiral.FakeSpiral() - .project("p") - .create_table("default.t", key_schema=[("k", pa.int64())]) - ) - - -def _header(table: fake_pyspiral.FakeTable) -> dict[str, Any]: - """Return the decoded header of ``table``'s nullability record.""" - return json.loads(table.get_metadata()[_KEY]) - - -def _chunk_keys(table: fake_pyspiral.FakeTable) -> list[str]: - """Return the chunk keys of ``table``'s nullability record, sorted.""" - return sorted(k for k in table.get_metadata() if k.startswith(_KEY + "/")) - - -class TestRoundTrip: - def test_non_nullable_paths_at_every_depth(self, table): - """Top-level, struct-field, list-item and nested paths round-trip; maps are skipped.""" - write_nullability_record(table, _SCHEMA) - assert read_nullability_record(table.get_metadata()) == _PATHS - - def test_no_record_reads_as_none(self, table): - """A table without a header key has no record.""" - assert read_nullability_record(table.get_metadata()) is None - - def test_all_nullable_schema_records_an_empty_set(self, table): - """A schema with no non-null field records an empty set, not no record.""" - write_nullability_record(table, pa.schema([pa.field("k", pa.int64())])) - assert read_nullability_record(table.get_metadata()) == frozenset() - - def test_header_is_versioned(self, table): - """The header carries the format name and version 1.""" - write_nullability_record(table, _SCHEMA) - header = _header(table) - assert header["format"] == "orcapod.nullability" - assert header["version"] == 1 - - def test_unchanged_record_is_not_rewritten(self, table): - """Writing the same record twice writes once and returns False the second time.""" - assert write_nullability_record(table, _SCHEMA) is True - assert write_nullability_record(table, _SCHEMA) is False - - def test_replacing_drops_the_old_chunks(self, table): - """A replacement record is read back and the earlier chunks are gone.""" - write_nullability_record(table, _SCHEMA) - old_chunks = _chunk_keys(table) - narrower = pa.schema([pa.field("k", pa.int64(), False)]) - assert write_nullability_record(table, narrower) is True - assert read_nullability_record(table.get_metadata()) == frozenset({("k",)}) - assert not set(old_chunks) & set(_chunk_keys(table)) - - def test_other_metadata_is_left_alone(self, table): - """Writing the record keeps unrelated metadata keys.""" - table.set_metadata({"__arrow_metadata__": b"{}"}) - write_nullability_record(table, _SCHEMA) - assert table.get_metadata()["__arrow_metadata__"] == b"{}" - - def test_wide_table_is_chunked_under_the_8_kib_limit(self, table): - """A 400-column record is split into chunks, each under SpiralDB's limits.""" - names = [f"column_with_a_long_name_{i:04d}" for i in range(400)] - wide = pa.schema( - [pa.field("k", pa.int64(), False)] - + [pa.field(n, pa.float64(), False) for n in names] - ) - write_nullability_record(table, wide) - metadata = table.get_metadata() - chunk_keys = _chunk_keys(table) - assert len(chunk_keys) > 1 - for key in [_KEY, *chunk_keys]: - assert len(key.encode()) + len(metadata[key]) <= 8192 - assert len(key) <= 255 - assert read_nullability_record(metadata) == frozenset( - {("k",), *((n,) for n in names)} - ) - - def test_non_null_map_item_is_refused(self, table): - """A non-null map item cannot be recorded and nothing is written.""" - schema = pa.schema( - [ - pa.field( - "m", - # pyarrow accepts key/item fields here; its stubs list only types. - pa.map_( - pa.field("key", pa.string(), False), # pyright: ignore[reportArgumentType] - pa.field("value", pa.int64(), False), # pyright: ignore[reportArgumentType] - ), - ) - ] - ) - with pytest.raises(NullabilityRecordError, match="'m'"): - write_nullability_record(table, schema) - assert read_nullability_record(table.get_metadata()) is None - - -class TestIntegrity: - """A record that cannot be read in full is an error, never ignored.""" - - def test_unknown_version(self, table): - """A header with an unknown version raises.""" - write_nullability_record(table, _SCHEMA) - header = _header(table) - header["version"] = 2 - table.set_metadata({_KEY: json.dumps(header).encode()}) - with pytest.raises(NullabilityRecordError, match="version 2"): - read_nullability_record(table.get_metadata()) - - def test_unknown_format(self, table): - """A header with an unknown format raises.""" - write_nullability_record(table, _SCHEMA) - header = _header(table) - header["format"] = "something.else" - table.set_metadata({_KEY: json.dumps(header).encode()}) - with pytest.raises(NullabilityRecordError, match="format"): - read_nullability_record(table.get_metadata()) - - def test_header_not_json(self, table): - """A header that is not JSON raises.""" - table.set_metadata({_KEY: b"not json"}) - with pytest.raises(NullabilityRecordError): - read_nullability_record(table.get_metadata()) - - def test_missing_chunk(self, table): - """A missing chunk raises.""" - write_nullability_record(table, _SCHEMA) - table.drop_metadata(_chunk_keys(table)[:1]) - with pytest.raises(NullabilityRecordError, match="missing"): - read_nullability_record(table.get_metadata()) - - def test_digest_mismatch(self, table): - """A chunk that does not match the header's digest raises.""" - write_nullability_record(table, _SCHEMA) - table.set_metadata({_chunk_keys(table)[0]: b'[["v"]]'}) - with pytest.raises(NullabilityRecordError, match="digest"): - read_nullability_record(table.get_metadata()) - - def test_payload_not_a_list_of_paths(self, table): - """A payload that is not a list of string lists raises.""" - write_nullability_record(table, _SCHEMA) - header = _header(table) - payload = b'{"k": true}' - digest = hashlib.sha256(payload).hexdigest() - header["sha256"] = digest - header["chunks"] = 1 - # Chunk keys are named by the payload digest (the documented format). - chunk = f"{_KEY}/{digest[:16]}/0" - table.set_metadata({chunk: payload, _KEY: json.dumps(header).encode()}) - with pytest.raises(NullabilityRecordError, match="path"): - read_nullability_record(table.get_metadata()) - - def test_chunks_without_header_are_no_record(self, table): - """Chunks left without their header are no record.""" - write_nullability_record(table, _SCHEMA) - table.drop_metadata([_KEY]) - assert read_nullability_record(table.get_metadata()) is None diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py new file mode 100644 index 000000000..82c2d0ad7 --- /dev/null +++ b/tests/test_databases/test_spiraldb_reading.py @@ -0,0 +1,850 @@ +"""Reading SpiralDB through spiral-sdk, on the fake (ITL-1186). + +What the connector and the table source read, what they refuse, and the regressions of the +review findings (B2, B3, B4, B9). +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +import math +import os +import signal +import sys +import threading +import time +import warnings +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import pyarrow as pa +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.errors import ( + NullInNonNullableColumnError, + SpiralDBWriteNotSupportedError, + TableSchemaError, + UnrecordedTableSchemaWarning, +) +from orcapod.nodes import FunctionJobNode +from orcapod.sources import DictSource, SpiralDBTableSource +from orcapod.types import ColumnInfo +from tests.test_databases import fake_spiral_sdk as fake + +_ITEM = pa.field("item", pa.float32(), False) +_WRITTEN = pa.schema( + [ + pa.field("k2", pa.int32(), False), + pa.field("k1", pa.large_string(), False), + pa.field("z", pa.float64(), False, {"unit": "mV"}), + pa.field("a", pa.large_list(_ITEM)), + pa.field( + "g", + pa.struct( + [ + pa.field("y", pa.int8(), False, {"m": "1"}), + pa.field("x", pa.large_string()), + ] + ), + False, + ), + ], + metadata={"who": "test"}, +) + + +def _rows() -> pa.Table: + values = [ + {"k2": 2, "k1": "a", "z": 1.0, "a": [1.0], "g": {"y": 1, "x": None}}, + {"k2": 1, "k1": "b", "z": 2.0, "a": [], "g": {"y": 2, "x": "q"}}, + {"k2": 1, "k1": "a", "z": 3.0, "a": None, "g": {"y": 3, "x": "r"}}, + ] + return pa.Table.from_pylist(values, schema=_WRITTEN) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """``units`` and ``swapped``: the same rows under the two key orders.""" + monkeypatch.setattr(connector_module, "_warned_unrecorded", set()) + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + for name, keys in (("units", ["k2", "k1"]), ("swapped", ["k1", "k2"])): + made.create_table( + f"default.{name}", key_schema=[_WRITTEN.field(k) for k in keys] + ).write(_rows()) + yield made + + +def _keys(source: SpiralDBTableSource) -> list[tuple[Any, Any]]: + return [(tag.as_dict()["k2"], tag.as_dict()["k1"]) for tag, _ in source.iter_data()] + + +def test_a_recorded_table_is_read_with_its_schema(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) + connector = SpiralDBConnector("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"] + assert [f.name for f in schema.field("g").type] == ["x", "y"] + assert schema.metadata == {b"who": b"test"} + assert schema.field("z").metadata == {b"unit": b"mV"} + assert {f.name: f.nullable for f in schema} == { + "k2": False, + "k1": False, + "a": True, + "z": False, + "g": False, + } + inner = schema.field("g").type.field("y") + assert (inner.nullable, inner.metadata) == (False, {b"m": b"1"}) + assert schema.field("a").type == pa.large_list(_ITEM) + batches = list(connector.scan_batches("units")) + assert all(b.schema.equals(schema, check_metadata=True) for b in batches) + assert connector.get_column_info("units") == [ + ColumnInfo(f.name, f.type, f.nullable) for f in schema + ] + + +def test_rows_come_in_key_order_and_values_are_kept(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) + assert _keys(SpiralDBTableSource("p", "units", tag_only_columns=True)) == [ + (1, "a"), + (1, "b"), + (2, "a"), + ] + assert _keys(SpiralDBTableSource("p", "swapped", tag_only_columns=True)) == [ + (1, "a"), + (2, "a"), + (1, "b"), + ] + table = pa.Table.from_batches(SpiralDBConnector("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 + + +@pytest.mark.parametrize("name", ["units", "swapped"]) +@pytest.mark.parametrize("tag_only", [True, False], ids=["plain tags", "data-tags"]) +def test_sync_and_async_read_the_same_rows( + project: Any, name: str, tag_only: bool +) -> None: + fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) + source = SpiralDBTableSource("p", name, tag_only_columns=tag_only) + + async def collect() -> list[Any]: + return [(t.as_dict(), d.as_dict()) async for t, d in source.async_iter_data()] + + sync = [(t.as_dict(), d.as_dict()) for t, d in source.iter_data()] + expected = {"units": ["a", "b", "a"], "swapped": ["a", "a", "b"]}[name] + assert [t["k1"] for t, _ in sync] == expected + # One reader hands the batches on in order, so a source's own async read is in key + # order too (a job's async result has no order). + assert repr(asyncio.run(collect())) == repr(sync) + + +def test_a_null_in_a_recorded_column_is_refused(project: Any) -> None: + nulls = _rows().slice(0, 1) + nulls = nulls.set_column( + nulls.schema.get_field_index("z"), + pa.field("z", pa.float64()), + pa.array([None], pa.float64()), + ) + 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")) + + +# ------------------------------------------------------------ a table that is not recorded + + +def _unrecorded(name: str = "units") -> str: + return f"SpiralDB table p/default/{name} has no row" + + +@pytest.mark.parametrize("complete", [False, True], ids=["no table", "absent row"]) +def test_an_unrecorded_table_warns_once_and_reads_nullable( + project: Any, complete: bool +) -> None: + if complete: + fake.migrate("p", {"swapped": _WRITTEN}) + project.create_table("default.late", key_schema=[("k", pa.string())]).write( + pa.table({"k": ["a"], "v": [1]}) + ) + name = "late" if complete else "units" + 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) + 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) + assert all(f.nullable and not f.metadata for f in schema) + + +def test_the_warning_as_an_error_is_raised_every_time(project: Any) -> None: + """Review finding B9.""" + with warnings.catch_warnings(): + warnings.simplefilter("error", UnrecordedTableSchemaWarning) + for _ in range(2): + with pytest.raises(UnrecordedTableSchemaWarning): + SpiralDBTableSource("p", "units", tag_only_columns=True) + + +def test_a_recorded_table_warns_nothing(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + with warnings.catch_warnings(): + warnings.simplefilter("error") + SpiralDBTableSource("p", "units", tag_only_columns=True).as_table() + assert SpiralDBConnector("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"] + + +# ------------------------------------------------------------------ a row that disagrees + + +def test_a_column_added_later_is_refused_naming_it(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + project.table("default.units").write( + pa.table({"k2": pa.array([9], pa.int32()), "k1": ["z"], "new": [1]}) + ) + with pytest.raises(TableSchemaError, match="not recorded: .'new'"): + SpiralDBTableSource("p", "units", tag_only_columns=True) + + +def test_an_older_version_with_other_columns_is_refused(project: Any) -> None: + project.table("default.units").write( + pa.table({"k2": pa.array([9], pa.int32()), "k1": ["z"], "new": [1]}) + ) + fake.migrate("p", {}) + connector = SpiralDBConnector("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)) + + +def test_an_older_version_with_the_same_columns_is_read(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + project.table("default.units").write( + _rows().slice(0, 1).set_column(1, "k1", pa.array(["new"])) + ) + assert len(_keys(SpiralDBTableSource("p", "units", tag_only_columns=True))) == 4 + assert ( + len(_keys(SpiralDBTableSource("p", "units", asof=1, tag_only_columns=True))) + == 3 + ) + + +def test_a_recreated_table_is_not_read_with_the_old_row(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + project.drop_table("default.units") + project.create_table("default.units", key_schema=[("k", pa.string())]).write( + pa.table({"k": ["a"], "v": [1]}) + ) + with pytest.warns(UnrecordedTableSchemaWarning, match="units has no row"): + schema = SpiralDBConnector("p").get_arrow_schema("units") + assert schema.names == ["k", "v"] + + +@pytest.mark.parametrize("failure", ["status 401", "status 403", "transport failed"]) +def test_a_schema_table_that_cannot_be_reached_is_not_an_absent_one( + project: Any, monkeypatch: pytest.MonkeyPatch, failure: str +) -> None: + original = fake.FakeClient.keyed_table + + def opened(self: Any, project_id: str, dataset: str, name: str, **given: Any): + if name == "__orcapod_schemas__": + raise fake.SpiralError(failure) + return original(self, project_id, dataset, name, **given) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", opened) + with pytest.raises(fake.SpiralError, match=failure) as raised: + SpiralDBTableSource("p", "units", tag_only_columns=True) + assert "__orcapod_schemas__" in raised.value.__notes__[0] + + +def _batch(**columns: Any) -> pa.RecordBatch: + return pa.RecordBatch.from_pydict(columns) + + +def test_a_batch_is_mapped_by_name_and_never_by_position(project: Any) -> None: + """Review finding B2.""" + found = pa.schema([("k", pa.int64()), ("v", pa.int64())]) + reading = connector_module._Reading(found, None, "p/default/t") # pyright: ignore[reportPrivateUsage] # the preparation is the subject + out = reading.prepare(_batch(v=[9], k=[1])) + assert out.to_pydict() == {"k": [1], "v": [9]} + assert reading.prepare(_batch(k=[2], v=[3])).to_pydict() == {"k": [2], "v": [3]} + for wrong in ( + _batch(k=[1]), + _batch(k=[1], v=[1], w=[1]), + _batch(k=[1], x=[1]), + _batch(k=[1], v=["text"]), + ): + with pytest.raises(TableSchemaError, match="a batch's columns"): + reading.prepare(wrong) + + +# -------------------------------------------------------------------------------- filters + + +_TYPED = pa.table( + { + "k": pa.array([1, 2, 3], pa.int64()), + "h": pa.array([0.5, -0.0, float("nan")], pa.float64()).cast(pa.float16()), + "f": pa.array([0.1, -0.0, float("nan")], pa.float32()), + "d": pa.array([0.1, -0.0, float("nan")]), + "n": pa.array([0.0, 1.0, None], pa.float32()), + "s": pa.array(["x", "é", None], pa.large_string()), + "b": pa.array([b"x", b"", None], pa.large_binary()), + "u": pa.array([2**64 - 1, 0, 1], pa.uint64()), + "i": pa.array([-1, 0, 1], pa.int8()), + "t": pa.array([True, False, None]), + "sec": pa.array([1, 2, 3], pa.timestamp("s")), + "ns": pa.array([1, 1000, 3], pa.timestamp("ns")), + "d64": pa.array([0, 86400001, None], pa.date64()), + "d32": pa.array([0, 1, None], pa.date32()), + } +) + + +@pytest.mark.parametrize( + ("column", "value", "expected"), + [ + # Measured on the service with pyspiral and through this connector: the same, + # except the two uint64 cases, which pyspiral refused. + ("h", 0.5, [1]), + ("h", 0.0, []), + ("h", -0.0, [2]), + ("h", math.nan, [3]), + ("h", 0.1, []), + ("h", 1e300, []), + ("f", 0.1, []), + ("f", 0.0, []), + ("f", -0.0, [2]), + ("f", math.nan, [3]), + ("f", 1e300, []), + ("f", math.inf, []), + ("n", 0.0, [1]), + ("n", -0.0, []), + ("n", 1.0, [2]), + ("d", 0.1, [1]), + ("d", math.nan, [3]), + ("d", 0.0, []), + ("d", -0.0, [2]), + ("s", "x", [1]), + ("s", "é", [2]), + ("b", b"x", [1]), + ("b", b"", [2]), + ("u", 2**64 - 1, [1]), + ("u", 0, [2]), + ("i", -1, [1]), + ("t", True, [1]), + ("t", False, [2]), + ("sec", dt.datetime(1970, 1, 1, 0, 0, 1), [1]), + ("ns", dt.datetime(1970, 1, 1, 0, 0, 0, 1), [2]), + ("d64", dt.date(1970, 1, 2), []), + ("d64", dt.date(1970, 1, 1), [1]), + ("d32", dt.date(1970, 1, 2), [2]), + ], +) +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("typed", where={column: value}) + assert [k for b in batches for k in b.column("k").to_pylist()] == expected + + +@pytest.mark.parametrize("limit", [1, 2, 3]) +def test_a_filter_applied_here_comes_before_the_limit(project: Any, limit: int) -> None: + rows = pa.table( + { + "k": list(range(8)), + "h": pa.array([1.0, 2.0] * 4, pa.float64()).cast(pa.float16()), + "s": ["x", "x", "y", "x"] * 2, + } + ) + 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("half", where=where, limit=limit) + found = [k for b in batches for k in b.column("k").to_pylist()] + assert found == [1, 3, 5, 7][:limit] + + +# --------------------------------------------------------------------------------- counts + + +def test_a_preview_counts_no_further_than_its_bound( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review finding B4: also when the preview shows the schema only.""" + fake.migrate("p", {"units": _WRITTEN}) + fake.count_log.clear() + source = SpiralDBTableSource("p", "units", max_rows=1, tag_only_columns=True) + monkeypatch.setattr(SpiralDBTableSource, "_preview_reads_rows", False) + head = source.head(1) + assert [c.limit for c in fake.count_log] == [11] + assert head.total_rows == 3 + monkeypatch.setattr(SpiralDBTableSource, "_preview_reads_rows", True) + fake.count_log.clear() + head = SpiralDBTableSource("p", "units", max_rows=1, tag_only_columns=True).head(2) + assert [c.limit for c in fake.count_log] == [3] + assert (head.total_rows, "more than 2" in head.header()) == (None, True) + + +def test_a_preview_names_the_bound_it_counted_to( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + rows = pa.table({"k": list(range(30)), "v": list(range(30))}) + project.create_table("default.many", key_schema=[("k", pa.int64())]).write(rows) + source = SpiralDBTableSource("p", "many", max_rows=1, tag_only_columns=True) + monkeypatch.setattr(SpiralDBTableSource, "_preview_reads_rows", False) + assert "more than 10 rows" in source.head(1).header() + monkeypatch.setattr(SpiralDBTableSource, "_preview_reads_rows", True) + assert "of more than 3" in source.head(3).header() + # More rows shown than a preview counts: no key is read for the total. + monkeypatch.setattr(source_module, "DEFAULT_MAX_ROWS", 5) + fake.count_log.clear() + assert "of at least 6" in source.head(6).header() + assert fake.count_log == [] + + +def test_one_warning_from_many_threads(project: Any) -> None: + barrier = threading.Barrier(8) + + def build(_: int) -> None: + barrier.wait(10) + SpiralDBConnector("p").get_arrow_schema("units") + + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + with ThreadPoolExecutor(8) as pool: + list(pool.map(build, range(8))) + assert len([w for w in seen if w.category is UnrecordedTableSchemaWarning]) == 1 + + +def test_a_second_reader_does_not_pass_while_the_first_warning_raises( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """The first thread is held inside the warning until the second had its chance.""" + inside, second_done = threading.Event(), threading.Event() + warn = warnings.warn + + def slow(*given: Any, **options: Any) -> None: + if not inside.is_set(): + inside.set() + second_done.wait(0.5) + warn(*given, **options) + + def build() -> str: + try: + SpiralDBConnector("p").get_arrow_schema("units") + except UnrecordedTableSchemaWarning: + return "raised" + return "passed" + + def second() -> str: + assert inside.wait(10) + try: + return build() + finally: + second_done.set() + + monkeypatch.setattr(connector_module.warnings, "warn", slow) + with warnings.catch_warnings(): + warnings.simplefilter("error", UnrecordedTableSchemaWarning) + with ThreadPoolExecutor(2) as pool: + results = [pool.submit(build), pool.submit(second)] + assert [r.result(20) for r in results] == ["raised", "raised"] + + +def test_a_count_is_remembered_per_version(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + fake.count_log.clear() + connector = SpiralDBConnector("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 + assert connector.lookup_table("units").count_rows(at_most=9) == 3 + assert [c.limit for c in fake.count_log] == [2, None] + project.table("default.units").write( + _rows().slice(0, 1).set_column(1, "k1", pa.array(["new"])) + ) + assert connector.get_row_count_estimate("units") == 4 + assert connector.get_row_count_estimate("units", asof=1) == 3 + + +# ------------------------------------------------------------------------------- listing + + +@pytest.mark.parametrize("count", [0, 1, 3, 4, 10]) +def test_the_listing_reads_every_page(tmp_path: Path, count: int) -> None: + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p q") + 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() + assert names == sorted(f"t{i}" for i in range(count)) + + +@pytest.mark.parametrize("given", [["a", "a"], ["a", "b", "a"], ["a", "b", "c", "b"]]) +def test_a_listing_that_does_not_advance_is_refused( + project: Any, given: list[str] +) -> None: + tokens = iter(given) + # A patch that ends inside the fake's own (monkeypatch would end after it). + with patch.object( + connector_module, + "_http_get_json", + lambda url, token: {"items": [], "nextPageToken": next(tokens)}, + ): + with pytest.raises(RuntimeError, match="does not advance"): + SpiralDBConnector("p").get_table_names() + + +def test_the_token_is_never_sent_on_a_redirect() -> None: + import http.server + + seen: list[str | None] = [] + + class Redirecting(http.server.BaseHTTPRequestHandler): + """Redirects every request to itself, under another path.""" + + def do_GET(self) -> None: + """Redirect.""" + seen.append(self.headers.get("Authorization")) + self.send_response(302) + self.send_header("Location", "/elsewhere") + self.end_headers() + + def log_message(self, format: str, *args: Any) -> None: + """Print nothing.""" + + server = http.server.HTTPServer(("127.0.0.1", 0), Redirecting) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with pytest.raises(OSError, match="302"): + connector_module._http_get_json( # pyright: ignore[reportPrivateUsage] # the request is the subject + f"http://127.0.0.1:{server.server_port}/", "secret" + ) + finally: + server.shutdown() + server.server_close() + assert seen == ["Bearer secret"] + + +# -------------------------------------------------------------------------------- writes + + +def test_every_write_is_refused_and_writes_nothing(project: Any) -> None: + connector = SpiralDBConnector("p") + columns = [ColumnInfo("k", pa.large_string(), False)] + for write in ( + lambda: connector.create_table_if_not_exists("new", columns, "k"), + lambda: connector.upsert_records("units", _rows(), "k1"), + lambda: connector.upsert_records("units", _rows(), "k1", skip_existing=True), + lambda: connector.delete_table("units"), + lambda: connector.delete_table("absent"), + lambda: connector.validate_records(_rows()), + lambda: connector.unstorable_column_reason("v", pa.int64(), primary_key=False), + ): + with pytest.raises(SpiralDBWriteNotSupportedError, match="ITL-1186"): + write() + assert connector.get_table_names() == ["swapped", "units"] + assert connector.get_row_count_estimate("units") == 3 + + +@pytest.mark.parametrize("flush", [False, True]) +def test_a_database_refuses_rows_before_it_holds_them( + project: Any, flush: bool +) -> None: + """Review finding B3.""" + database = ConnectorArrowDatabase(SpiralDBConnector("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) + assert database.get_all_records(("t",)) is None + database.flush() + assert database.list_table_paths() == [("swapped",), ("units",)] + + +def test_a_job_storing_there_is_refused_before_anything_runs(project: Any) -> None: + calls: list[int] = [] + + @function_pod(output_keys="w") + def double(v: int) -> int: + calls.append(v) + return 2 * v + + source = DictSource([{"k": 1, "v": 1}], tag_columns=["k"], source_id="s") + job = PipelineJob(name="j", database=ConnectorArrowDatabase(SpiralDBConnector("p"))) + with pytest.raises(SpiralDBWriteNotSupportedError): + with job: + double.pod(source, label="double") + job.run() + assert calls == [] + + +def test_a_job_reads_a_source_and_stores_elsewhere( + project: Any, tmp_path: Path +) -> None: + from orcapod.databases import DeltaTableDatabase + + fake.migrate("p", {"units": _WRITTEN}) + + @function_pod(output_keys="w") + def double(z: float) -> float: + return 2 * z + + job = PipelineJob(name="j", database=DeltaTableDatabase(tmp_path / "store")) + with job: + double.pod( + SpiralDBTableSource("p", "units", tag_only_columns=True), label="double" + ) + job.run() + node = job.nodes["double"] + assert isinstance(node, FunctionJobNode) + assert sorted(cast("list[float]", node.as_table()["w"].to_pylist())) == [ + 2.0, + 4.0, + 6.0, + ] + job.save(tmp_path / "job.json") + loaded = PipelineJob.load(tmp_path / "job.json") + (source,) = [ + n.bound_source for n in loaded.nodes.values() if hasattr(n, "bound_source") + ] + assert isinstance(source, SpiralDBTableSource) + assert ( + source.source_id + == SpiralDBTableSource("p", "units", tag_only_columns=True).source_id + ) + + +# -------------------------------------------------------------------- client and lifetime + + +def test_the_one_override_is_the_address(project: Any) -> None: + overrides = {"server.url": "https://api.example.invalid"} + connector = SpiralDBConnector("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", + "project_id": "p", + "dataset": "default", + "overrides": overrides, + } + with pytest.raises(ValueError, match="authn.token"): + SpiralDBConnector("p", overrides={"authn.token": "x", **overrides}) + + +def test_a_closed_connector_reads_nothing(project: Any) -> None: + with SpiralDBConnector("p") as connector: + shared = connector.share_client() + handle = connector.lookup_table("units") + connector.close() + for use in ( + connector.get_table_names, + lambda: connector.lookup_table("units"), + lambda: list(connector.scan_batches("units")), + handle.version, + handle.arrow_schema, + connector.to_config, + connector.share_client, + ): + with pytest.raises(RuntimeError, match="closed"): + use() + assert shared.get_table_names() == ["swapped", "units"] + + +def test_an_abandoned_read_closes_its_reader(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + source = SpiralDBTableSource("p", "units", tag_only_columns=True) + fake.scan_log.clear() + rows: Any = source.iter_data() + next(rows) + rows.close() + assert [scan.closed for scan in fake.scan_log] == [True] + + +def test_a_cancelled_async_read_closes_its_reader( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + fake.migrate("p", {"units": _WRITTEN}) + source = SpiralDBTableSource("p", "units", tag_only_columns=True) + started, release = threading.Event(), threading.Event() + original = fake.FakeReader.read_next_batch + threads: set[int] = set() + + def slow(self: Any) -> pa.RecordBatch: + threads.add(threading.get_ident()) + if self._record.identifier.endswith(".units"): + started.set() + release.wait(10) + return original(self) + + async def read() -> None: + async for _ in source.async_iter_data(): + pass + + async def cancel() -> None: + # Before the read that blocks: what it looks up runs on the same thread. + task = asyncio.create_task(read()) + for _ in range(1000): + if started.is_set() or task.done(): + break + await asyncio.sleep(0.01) + if task.done(): + await task # an early failure is this test's failure + assert started.is_set() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + _ = source.row_count_estimate # counted before, so only the read is slowed + fake.scan_log.clear() + monkeypatch.setattr(fake.FakeReader, "read_next_batch", slow) + try: + asyncio.run(cancel()) + assert not any(scan.closed for scan in fake.scan_log) # still being read + finally: + release.set() + deadline = threading.Event() + for _ in range(200): + if all(scan.closed for scan in fake.scan_log): + break + deadline.wait(0.01) + assert [scan.closed for scan in fake.scan_log] == [True] + assert len(threads) == 1 # one thread owned the reader + assert threading.get_ident() not in threads + + +def test_many_threads_read_through_one_connector(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) + connector = SpiralDBConnector("p") + + def read(i: int) -> tuple[list[str], int]: + name = ("units", "swapped")[i % 2] + table = pa.Table.from_batches(connector.scan_batches(name)) + return connector.get_arrow_schema(name).names[:2], table.num_rows + + with ThreadPoolExecutor(8) as pool: + results = list(pool.map(read, range(64))) + assert results == [(["k2", "k1"], 3), (["k1", "k2"], 3)] * 32 + + +@pytest.mark.skipif(sys.platform == "win32", reason="os.fork is POSIX") +def test_a_forked_child_is_refused_instead_of_hanging( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + connector = SpiralDBConnector("p") + monkeypatch.setattr(os, "getpid", lambda: -1) + with pytest.raises(RuntimeError, match="after a fork"): + connector.lookup_table("units") + + +_AFTER_FORK = { + "read": lambda source: source.as_table(), + "head": lambda source: source.head(), + "check": lambda source: source.check_for_new_data(), + "where": lambda source: source.where(k1="a"), + "close": lambda source: source.close(), +} + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="os.fork is POSIX") +@pytest.mark.parametrize("held", [False, True], ids=["lock free", "lock held"]) +@pytest.mark.parametrize("use", sorted(_AFTER_FORK)) +def test_a_source_in_a_forked_child_is_refused_and_never_waits( + project: Any, use: str, held: bool +) -> None: + """Review finding B7: the process is checked before the inherited lock, which a + thread that does not exist in the child may hold for ever.""" + fake.migrate("p", {"units": _WRITTEN}) + source = SpiralDBTableSource("p", "units", tag_only_columns=True) + lock = source._connection_lock # pyright: ignore[reportPrivateUsage] # the inherited lock is the subject + taken, release = threading.Event(), threading.Event() + + def hold() -> None: + with lock: + taken.set() + release.wait(30) + + holder = threading.Thread(target=hold) + if held: + holder.start() + assert taken.wait(10) + try: + with warnings.catch_warnings(): + # Python warns of a fork with threads: that is what is tested. + warnings.simplefilter("ignore") + pid = os.fork() + if pid == 0: # the child: never returns to pytest + code = 3 + try: + _AFTER_FORK[use](source) + code = 1 + except RuntimeError as exc: + code = 0 if "after a fork" in str(exc) else 2 + finally: + os._exit(code) + status: int | None = None + for _ in range(1000): + done, found = os.waitpid(pid, os.WNOHANG) + if done: + status = os.waitstatus_to_exitcode(found) + break + time.sleep(0.01) + if status is None: + os.kill(pid, signal.SIGKILL) + _ = os.waitpid(pid, 0) + assert status == 0, "the child waited for the lock" if status is None else "" + finally: + release.set() + if held: + holder.join(10) + # The parent is not affected. + assert source.as_table().num_rows == 3 + + +def test_a_missing_table_is_told_apart_from_other_failures( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + connector = SpiralDBConnector("p") + with pytest.raises(connector_module.SpiralDBTableNotFoundError): + connector.lookup_table("absent") + + def denied(*_given: Any, **_options: Any) -> None: + raise fake.SpiralError("remote service returned an unknown error (status 404)") + + monkeypatch.setattr(fake.FakeClient, "keyed_table", denied) + with pytest.raises(fake.SpiralError, match="404") as raised: + connector.lookup_table("absent") + assert raised.value.__notes__ == ["SpiralDB: could not open table p/default/absent"] + + +@pytest.mark.parametrize( + "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)) + 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")) diff --git a/tests/test_databases/test_spiraldb_schema_table.py b/tests/test_databases/test_spiraldb_schema_table.py new file mode 100644 index 000000000..5885ec4df --- /dev/null +++ b/tests/test_databases/test_spiraldb_schema_table.py @@ -0,0 +1,339 @@ +"""The schema table's stored form, frozen by test vectors, and its refusals (ITL-1186). + +The form of a row and of the completion marker is a data format (version 1): rows written +by the migration tool are read by every later Orcapod. A vector that fails is a bug in the +change; a new form is a new ``FORMAT_VERSION``. +""" + +from __future__ import annotations + +import asyncio +import base64 +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +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 + +_SCHEMA = pa.schema( + [ + pa.field("k", pa.large_string(), False), + pa.field("a", pa.int64(), True, {"unit": "mV", "note": "x", "b": "1"}), + pa.field("g", pa.struct([pa.field("y", pa.int8(), False)]), False), + pa.field("l", pa.large_list(pa.field("item", pa.float32(), False))), + ], + metadata={"z": "1", "a": "2"}, +) +# The bytes pyarrow 23.0.1 encoded ``_SCHEMA`` to: given, so that the vectors do not +# depend on how another pyarrow encodes it. +_BYTES = base64.b64decode( + (Path(__file__).parent / "spiraldb_schema_v1.b64").read_text() +) +_ROW = st.SchemaRow( + "table_1", "units", ("k",), _BYTES, st.FROM_RECORD, 1795550964587941 +) +_SCOPE = st.Scope("p", "d", "f" * 64) + + +def test_the_stored_columns() -> None: + assert [(f.name, str(f.type)) for f in st.ROW_SCHEMA] == [ + ("table_id", "large_string"), + ("table_name", "large_string"), + ("format", "large_string"), + ("format_version", "int64"), + ("nullability", "large_string"), + ("schema", "large_binary"), + ("key_columns", "large_string"), + ("nullable_columns", "large_string"), + ("captured_version", "int64"), + ("project", "large_string"), + ("dataset", "large_string"), + ("plan_digest", "large_string"), + ("table_count", "int64"), + ("rows_digest", "large_string"), + ("written_at", "large_string"), + ("written_by", "large_string"), + ] + assert (st.SCHEMA_TABLE, st.MARKER_KEY) == ("__orcapod_schemas__", "__complete__") + + +def test_a_stored_row() -> None: + assert _ROW.schema.equals(_SCHEMA, check_metadata=True) + assert _ROW.stored() == { + "table_id": "table_1", + "table_name": "units", + "format": "orcapod.table_schema", + "format_version": 1, + "nullability": "record", + "captured_version": 1795550964587941, + "schema": _BYTES, + "key_columns": '["k"]', + "nullable_columns": '[["a"],["l"]]', + } + assert st.SchemaRow.from_stored(_ROW.stored()) == _ROW + + +def test_the_marker() -> None: + other = st.SchemaRow("table_0", "a", ("k", "a"), _BYTES, st.FROM_SERVICE, 0) + marker = st.marker_values(_SCOPE, [_ROW, other]) + assert {k: v for k, v in marker.items() if v is not None} == { + "table_id": "__complete__", + "format": "orcapod.table_schema", + "format_version": 1, + "project": "p", + "dataset": "d", + "plan_digest": "f" * 64, + "table_count": 2, + "rows_digest": "93540c92016a267d6c7c61f00214c863ffe4452d5b095b41fd9209524a9d99bc", + } + # The order the rows are given in is not part of it. + assert marker == st.marker_values(_SCOPE, [other, _ROW]) + rows = {r.table_id: r for r in (_ROW, other)} + st.require_complete("p", "d", rows, marker) + + +@pytest.mark.parametrize( + "change", + [ + {"table_id": "table_2"}, + {"table_name": "other"}, + {"key_columns": ("a",)}, + {"nullability": st.FROM_SERVICE}, + {"captured_version": 2}, + ], +) +def test_the_digest_covers_every_part_of_a_row(change: dict[str, Any]) -> None: + values: dict[str, Any] = { + "table_id": _ROW.table_id, + "table_name": _ROW.table_name, + "key_columns": _ROW.key_columns, + "schema_bytes": _ROW.schema_bytes, + "nullability": _ROW.nullability, + "captured_version": _ROW.captured_version, + } + changed = st.SchemaRow(**{**values, **change}) + assert st.rows_digest(_SCOPE, [changed]) != st.rows_digest(_SCOPE, [_ROW]) + + +def test_the_digest_does_not_depend_on_registered_extension_types() -> None: + """Review finding B5: the stored bytes are digested, never a schema encoded again.""" + + class Measured(pa.ExtensionType): + """A synthetic extension type.""" + + def __init__(self) -> None: + super().__init__(pa.large_binary(), "orcapod.test.measured") + + def __arrow_ext_serialize__(self) -> bytes: + return b"meta" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: Any) -> Any: + return cls() + + schema = pa.schema( + [ + pa.field("k", pa.large_string(), False), + pa.field( + "v", + pa.large_binary(), + metadata={ + "a": "1", + "ARROW:extension:name": "orcapod.test.measured", + "z": "2", + "ARROW:extension:metadata": "meta", + }, + ), + ] + ) + row = st.SchemaRow( + "t", "n", ("k",), schema.serialize().to_pybytes(), st.FROM_RECORD, 1 + ) + stored = row.stored() + marker = st.marker_values(_SCOPE, [row]) + before = st.SchemaRow.from_stored(stored) + pa.register_extension_type(cast(Any, Measured())) + try: + after = st.SchemaRow.from_stored(stored) + assert before == after == row + st.require_complete("p", "d", {"t": after}, marker) + assert after.schema.equals(before.schema, check_metadata=True) + assert after.schema.field("v").type == pa.large_binary() + finally: + pa.unregister_extension_type("orcapod.test.measured") + + +@pytest.mark.parametrize( + ("change", "message"), + [ + ({"format": "other"}, "unknown format"), + ({"format_version": 2}, "format version 2"), + ({"nullability": "maybe"}, "unknown nullability"), + ({"schema": b"broken"}, "cannot be decoded"), + ({"schema": None}, "cannot be decoded"), + ({"key_columns": "[]"}, "key_columns"), + ({"key_columns": '["gone"]'}, "key_columns"), + ({"key_columns": "no json"}, "cannot be decoded"), + ({"nullable_columns": "[]"}, "disagree"), + ({"captured_version": None}, "captured_version"), + ], +) +def test_a_row_that_cannot_be_read_in_full_is_refused( + change: dict[str, Any], message: str +) -> None: + with pytest.raises(TableSchemaError, match=message): + st.SchemaRow.from_stored({**_ROW.stored(), **change}) + + +# ------------------------------------------------------------- a dataset's schema table + + +_WRITTEN = pa.schema( + [ + pa.field("k", pa.string(), False), + pa.field("j", pa.int32(), False), + pa.field("v", pa.int64(), False), + pa.field("w", pa.string()), + ] +) + + +@pytest.fixture() +def project(tmp_path: Path): + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + for name, keys in (("units", ["k", "j"]), ("trials", ["j", "k"])): + made.create_table( + f"default.{name}", key_schema=[_WRITTEN.field(key) for key in keys] + ).write( + pa.table( + { + "w": ["x", None], + "k": ["a", "b"], + "v": [1, 2], + "j": pa.array([2, 1], pa.int32()), + } + ) + ) + yield made + + +def _edit_schema_table(**change: Any) -> None: + """Overwrite the marker's values in the stored schema table.""" + client = fake.FakeClient() + table = client.keyed_table("p", "default", st.SCHEMA_TABLE) + (marker,) = [ + r for r in table.scan().to_table().to_pylist() if r["table_id"] == st.MARKER_KEY + ] + table.append(pa.Table.from_pylist([{**marker, **change}], schema=st.ROW_SCHEMA)) + + +# 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"), + "bounded count": lambda: ( + SpiralDBConnector("p").lookup_table("units").count_rows(at_most=1) + ), + "listing": lambda: SpiralDBConnector("p").get_table_names(), +} + + +@pytest.mark.parametrize("path", sorted(_PATHS)) +@pytest.mark.parametrize( + "damage", + [ + "no marker", + "another count", + "another digest", + "another dataset", + "another project", + "another plan", + "withdrawn", + ], +) +def test_a_schema_table_that_is_not_complete_is_refused_on_every_path( + project: Any, path: str, damage: str +) -> None: + """Review finding B1.""" + fake.migrate("p", {"units": _WRITTEN}, complete=damage != "no marker") + if damage != "no marker": + _edit_schema_table( + **{ + "another count": {"table_count": 3}, + "another digest": {"rows_digest": "0" * 64}, + "another dataset": {"dataset": "other"}, + "another project": {"project": "other"}, + "another plan": {"plan_digest": "1" * 64}, + "withdrawn": {"rows_digest": "withdrawn: the dataset changed"}, + }[damage] + ) + with pytest.raises(TableSchemaError): + _PATHS[path]() + + +async def _collect(source: SpiralDBTableSource) -> list[Any]: + return [pair async for pair in source.async_iter_data()] + + +@pytest.mark.parametrize("name", ["units", "trials"]) +@pytest.mark.parametrize("tag_only", [True, False], ids=["plain tags", "data-tags"]) +def test_open_readers_refuse_too(project: Any, name: str, tag_only: bool) -> None: + """A source and its previews, built while the table was complete, sync and async.""" + fake.migrate("p", {"units": _WRITTEN, "trials": _WRITTEN}) + source = SpiralDBTableSource("p", name, tag_only_columns=tag_only) + assert len(asyncio.run(_collect(source))) == len(list(source.iter_data())) == 2 + _edit_schema_table(table_count=9) + for read in ( + source.as_table, + lambda: list(source.iter_data()), + lambda: asyncio.run(_collect(source)), + source.head, + lambda: source.row_count_estimate, + source.check_for_new_data, + ): + with pytest.raises(TableSchemaError): + read() + + +def test_a_display_names_the_refusal_and_shows_no_row(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + source = SpiralDBTableSource("p", "units", tag_only_columns=True) + _edit_schema_table(table_count=9) + html = source._repr_html_() + assert "could not read" in html and "completion marker" in html + assert "" - f"" + f"" f"" f"" f"" @@ -1078,10 +1091,10 @@ def _asset(name: str) -> str: def _inputs(nodes: Sequence[_Node], edges: Sequence[_Edge]) -> dict[int, list[str]]: - """The labels of each node's inputs, by node index, in edge order.""" + """The drawn names of each node's inputs, by node index, in edge order.""" inputs: dict[int, list[str]] = {} for edge in edges: - inputs.setdefault(edge.target, []).append(nodes[edge.source].label) + inputs.setdefault(edge.target, []).append(nodes[edge.source].text) return inputs @@ -1244,6 +1257,8 @@ def to_dict(self) -> dict[str, Any]: ``label``, ``kind`` (its ``node_type``), ``kind_text``, ``detail``, ``status`` (``""`` for a pipeline), ``tag_schema`` and ``data_schema`` (lists of ``[column, type text]``) and ``facts`` (lists of ``[name, text]``); + a source node whose bound source has an assigned label also has ``text``, the + name drawn, and the fact ``source id``; each edge has ``source`` and ``target`` (node indices) and ``folded`` (the labels of the steps folded into it). With a highlight, every node and edge also has ``highlighted``, and the model has the highlight's ``note``. @@ -1282,6 +1297,8 @@ def _plain_model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any] "tag_schema": [list(pair) for pair in node.tag_schema], "data_schema": [list(pair) for pair in node.data_schema], "facts": [list(fact) for fact in node.facts], + # Only where a source's assigned label is drawn (ITL-1454). + **({"text": node.shown} if node.shown else {}), } for node in nodes ], @@ -1297,8 +1314,10 @@ def to_text(self) -> str: In development: this interface may change. Returns: - A title line, then ``
" not in html + + +def test_a_foreign_table_at_the_reserved_name_is_refused(tmp_path: Path) -> None: + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + made.create_table("default.units", key_schema=[("k", pa.string())]).write( + pa.table({"k": ["a"], "v": [1]}) + ) + made.create_table( + f"default.{st.SCHEMA_TABLE}", key_schema=[("x", pa.string())] + ).write(pa.table({"x": ["a"], "y": [1]})) + with pytest.raises(TableSchemaError, match="key columns"): + SpiralDBTableSource("p", "units", tag_only_columns=True) + + +def test_the_reserved_name_is_refused_and_unlisted(project: Any) -> None: + fake.migrate("p", {"units": _WRITTEN}) + connector = SpiralDBConnector("p") + assert connector.get_table_names() == ["trials", "units"] + for use in (connector.lookup_table, connector.get_column_info): + with pytest.raises(ValueError, match="reserved"): + use(st.SCHEMA_TABLE) + with pytest.raises(ValueError, match="reserved"): + SpiralDBTableSource("p", st.SCHEMA_TABLE) diff --git a/tests/test_databases/test_spiraldb_sign_in.py b/tests/test_databases/test_spiraldb_sign_in.py new file mode 100644 index 000000000..fdb488674 --- /dev/null +++ b/tests/test_databases/test_spiraldb_sign_in.py @@ -0,0 +1,154 @@ +"""``require_sign_in``: refuse before spiral-sdk would ask a person to sign in (ITL-1186). + +No test makes a client or reads a credential: the rule looks at the environment and at +whether the saved login's file has content. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +from orcapod.databases import SpiralDBConnector, spiraldb_connector +from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.errors import SpiralDBSignInError +from orcapod.sources import SpiralDBTableSource + +_VARIABLES = ( + "SPIRAL_TOKEN", + "SPIRAL_WORKLOAD_ID", + "SPIRAL_CLIENT_ID", + "SPIRAL_PRIVATE_KEY", + "SPIRAL_CLIENT_SECRET", + "SPIRAL_AUTH_FILE", + "SPIRAL__DEV", + "XDG_CONFIG_HOME", +) + + +@pytest.fixture(autouse=True) +def empty_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """An environment with no credential and an empty home.""" + for name in _VARIABLES: + monkeypatch.delenv(name, raising=False) + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + return home + + +def _save(path: Path, text: str = "{}") -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +def test_an_empty_home_is_refused_naming_the_command() -> None: + with pytest.raises(SpiralDBSignInError, match="uv run spiral login"): + require_sign_in() + + +@pytest.mark.parametrize( + "given", + [ + {"SPIRAL_TOKEN": "t"}, + {"SPIRAL_WORKLOAD_ID": "w"}, + {"SPIRAL_CLIENT_ID": "c", "SPIRAL_PRIVATE_KEY": "k"}, + {"SPIRAL_CLIENT_ID": "c", "SPIRAL_CLIENT_SECRET": "s"}, + ], +) +def test_each_credential_in_the_environment_is_accepted( + given: dict[str, str], monkeypatch: pytest.MonkeyPatch +) -> None: + for name, value in given.items(): + monkeypatch.setenv(name, value) + require_sign_in() + + +@pytest.mark.parametrize( + "given", + [ + {"SPIRAL_TOKEN": ""}, + {"SPIRAL_CLIENT_ID": "sentinel-id-1"}, + {"SPIRAL_PRIVATE_KEY": "sentinel-key-1"}, + {"SPIRAL_CLIENT_SECRET": "sentinel-secret-1"}, + {"SPIRAL_CLIENT_ID": "sentinel-id-1", "SPIRAL_PRIVATE_KEY": ""}, + ], +) +def test_half_a_credential_is_refused( + given: dict[str, str], monkeypatch: pytest.MonkeyPatch +) -> None: + for name, value in given.items(): + monkeypatch.setenv(name, value) + with pytest.raises(SpiralDBSignInError) as refused: + require_sign_in() + for value in given.values(): + assert not value or value not in str(refused.value) + + +@pytest.mark.parametrize("platform", ["darwin", "linux"]) +def test_the_saved_login_of_each_platform( + platform: str, empty_home: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(sys, "platform", platform) + folder = { + "darwin": empty_home / "Library" / "Application Support", + "linux": empty_home / ".config", + }[platform] + path = saved_login_path({"HOME": str(empty_home)}) + assert path == folder / "pyspiral" / "auth.json" + _save(path, "") + with pytest.raises(SpiralDBSignInError): # an empty file is no login + require_sign_in() + _save(path) + require_sign_in() + + +def test_xdg_moves_the_file_on_linux_only( + tmp_path: Path, empty_home: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + environ = {"HOME": str(empty_home), "XDG_CONFIG_HOME": str(tmp_path / "xdg")} + monkeypatch.setattr(sys, "platform", "linux") + assert saved_login_path(environ) == tmp_path / "xdg" / "pyspiral" / "auth.json" + monkeypatch.setattr(sys, "platform", "darwin") + assert str(empty_home) in str(saved_login_path(environ)) + + +def test_the_override_names_the_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "elsewhere" / "login.json" + monkeypatch.setenv("SPIRAL_AUTH_FILE", str(path)) + with pytest.raises(SpiralDBSignInError, match="login.json"): + require_sign_in() + _save(path) + require_sign_in() + + +def test_a_source_and_a_connector_refuse_before_a_client_is_made( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class NoClient: + """A module whose client must not be made.""" + + @staticmethod + def Client(**_options: object) -> None: + raise AssertionError("a client was made") + + monkeypatch.setattr(spiraldb_connector, "sp", NoClient) + with pytest.raises(SpiralDBSignInError): + SpiralDBConnector("p") + with pytest.raises(SpiralDBSignInError): + SpiralDBTableSource("p", "t") + + +def test_pyspiral_in_place_of_the_sdk_is_named( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class Pyspiral: + """A ``spiral`` module without ``Client``.""" + + monkeypatch.setattr(spiraldb_connector, "sp", Pyspiral) + with pytest.raises(ImportError, match="pyspiral"): + SpiralDBConnector("p") diff --git a/tests/test_databases/test_unstorable_columns.py b/tests/test_databases/test_unstorable_columns.py index 4619b9de8..f7e3f644c 100644 --- a/tests/test_databases/test_unstorable_columns.py +++ b/tests/test_databases/test_unstorable_columns.py @@ -353,176 +353,7 @@ def test_postgresql_rule(self, arrow_type, storable): assert (reason is None) is storable, reason -# --------------------------------------------------------------------------- -# SpiralDB: reserved column names (ITL-1164), through the pyspiral fake -# --------------------------------------------------------------------------- - - -@pytest.fixture -def spiral_database(tmp_path: pathlib.Path): - """A ``ConnectorArrowDatabase`` over ``SpiralDBConnector``, stored by the fake.""" - from orcapod.databases import SpiralDBConnector - from tests.test_databases import fake_pyspiral - - with fake_pyspiral.install(tmp_path / "spiral"): - connector = SpiralDBConnector("p") - try: - yield ConnectorArrowDatabase(connector) - finally: - connector.close() - - -class TestSpiralDBRefusesReservedNames: - def test_function_node_refused_before_anything_runs(self, spiral_database): - job = PipelineJob(name="p", database=spiral_database) - - with pytest.raises(UnstorableColumnError) as exc_info: - with job: - _ = double.pod(_source(), label="dbl") - - err = exc_info.value - assert err.node_label == "dbl" - assert err.database_kind == "SpiralDBConnector" - assert err.column == "__input_data_hash" - assert "'__' prefix" in err.reason - assert "InMemoryArrowDatabase" in str(err) - assert CALLS == [] - assert spiral_database.list_table_paths() == [] - - def test_side_effect_node_refused_before_delivery(self, spiral_database): - job = PipelineJob(name="p", database=spiral_database) - - with pytest.raises(UnstorableColumnError) as exc_info: - with job: - _ = deliver.process(_source(), label="out") - - assert exc_info.value.node_label == "out" - # The first column it cannot store: the time-zone-aware timestamp. - assert exc_info.value.column == "executed_at" - assert DELIVERED == [] - - def test_operator_cache_refused_when_attached(self, spiral_database): - job = PipelineJob(name="p", database=spiral_database) - with job: - _ = SelectDataColumns(["x"])(_source(), label="sel") - - with pytest.raises(UnstorableColumnError) as exc_info: - job.nodes["sel"].attach_databases( - pipeline_database=spiral_database.at("p"), cache_mode=CacheMode.LOG - ) - - assert exc_info.value.node_label == "sel" - assert exc_info.value.column == "__node_content_hash" - - def test_operator_without_cache_runs(self, spiral_database): - """An operator whose cache is off stores nothing, so nothing is refused.""" - job = PipelineJob(name="p", database=spiral_database) - with job: - _ = SelectDataColumns(["x"])(_source(), label="sel") - _ = job.run() - assert sorted(job.nodes["sel"].as_table()["x"].to_pylist()) == [1, 2] - - def test_cached_source_refused_when_built(self, spiral_database): - from orcapod.core.sources.cached_source import CachedSource - - with pytest.raises(UnstorableColumnError) as exc_info: - _ = CachedSource(_source(), cache_database=spiral_database) - - assert exc_info.value.column == "__data_context" - - @pytest.mark.parametrize( - "name, reason", - [ - ("__value", "'__' prefix"), - ("a.b", "'.'"), - ], - ) - def test_write_refuses_reserved_name(self, spiral_database, name, reason): - table = pa.table({name: pa.array([1], type=pa.int64())}) - - with pytest.raises(UnstorableColumnError) as exc_info: - spiral_database.add_record(("t",), b"1", table) - - assert exc_info.value.column == name - assert reason in exc_info.value.reason - spiral_database.flush() - assert spiral_database.list_table_paths() == [] - - def test_write_refuses_time_zone_aware_timestamp(self, spiral_database): - """SpiralDB drops the time zone, so the column would read back as another type.""" - table = pa.table( - { - "ts": pa.array( - [datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)], - type=pa.timestamp("us", tz="UTC"), - ) - } - ) - - with pytest.raises(UnstorableColumnError) as exc_info: - spiral_database.add_record(("t",), b"1", table) - - assert exc_info.value.column == "ts" - assert "time zone" in exc_info.value.reason - assert "timestamp[us]" in exc_info.value.reason - spiral_database.flush() - assert spiral_database.list_table_paths() == [] - - def test_key_column_may_start_with_double_underscore(self, spiral_database): - """``__record_id`` is the key, which SpiralDB accepts; lists are stored.""" - table = pa.table( - { - "v": pa.array([[{"key": "a", "value": "b"}]], type=EXECUTOR_INFO_TYPE), - "ts": pa.array( - [datetime.datetime(2026, 1, 1)], type=pa.timestamp("us") - ), - } - ) - spiral_database.add_record(("t",), b"1", table, flush=True) - stored = spiral_database.get_all_records(("t",)) - assert stored is not None - assert stored.num_rows == 1 - - -class TestSpiralFakeRefusesLikeSpiralDB: - """The fake refuses the names SpiralDB refuses, with its messages (ITL-1164).""" - - @pytest.mark.parametrize( - "name, message", - [ - ( - "__input_data_hash", - "Column name '__input_data_hash' has reserved prefix: column group " - "columns must not start with '__'", - ), - ("a.b", "Column 'a.b' contains a reserved dot-separator"), - ], - ) - def test_connector_write_refused(self, tmp_path: pathlib.Path, name, message): - from orcapod.databases import SpiralDBConnector - from orcapod.types import ColumnInfo - from tests.test_databases import fake_pyspiral - - with fake_pyspiral.install(tmp_path / "spiral"): - connector = SpiralDBConnector("p") - connector.create_table_if_not_exists( - "t", - [ - ColumnInfo("k", pa.large_string(), nullable=False), - ColumnInfo(name, pa.int64(), nullable=True), - ], - pk_column="k", - ) - rows = pa.table( - { - "k": pa.array(["a"], type=pa.large_string()), - name: pa.array([1], type=pa.int64()), - } - ) - with pytest.raises(ValueError, match="reserved") as exc_info: - connector.upsert_records("t", rows, id_column="k") - connector.close() - assert message in str(exc_info.value) +# SpiralDB refuses every write for now: tests/test_databases/test_spiraldb_reading.py. # --------------------------------------------------------------------------- @@ -622,16 +453,6 @@ def test_extension_type_refused_as_unstorable_column(self, tmp_path: pathlib.Pat assert exc_info.value.column == "u" - def test_null_column_is_not_a_large_string_column(self, spiral_database): - """The schema comparison keeps ``null``: a later ``large_string`` is a change.""" - null_table = pa.table({"v": pa.array([None], type=pa.null())}) - text_table = pa.table({"v": pa.array(["a"], type=pa.large_string())}) - spiral_database.add_record(("t",), b"1", null_table, flush=True) - - spiral_database.add_record(("t",), b"2", text_table) - with pytest.raises(ValueError, match="Schema mismatch"): - spiral_database.flush() - def test_buffered_text_reads_with_committed_text(self, tmp_path: pathlib.Path): """Buffered ``string`` rows read together with committed ``large_string`` rows.""" database = _sqlite_database(tmp_path) @@ -813,24 +634,6 @@ def test_postgresql_refuses_system_column_names(self, name): connector._conn = None assert reason is not None and "system column" in reason - @pytest.mark.parametrize( - "arrow_type", - [ - pa.large_list(pa.timestamp("us", tz="UTC")), - pa.struct([("t", pa.timestamp("us", tz="UTC"))]), - pa.map_(pa.large_string(), pa.timestamp("ms", tz="UTC")), - ], - ) - def test_spiraldb_refuses_nested_time_zone_aware_timestamp( - self, spiral_database, arrow_type - ): - table = pa.table({"v": pa.array([None], type=arrow_type)}) - - with pytest.raises(UnstorableColumnError) as exc_info: - spiral_database.add_record(("t",), b"1", table) - - assert "time zone" in exc_info.value.reason - def test_union_refused_before_any_cast(self, tmp_path: pathlib.Path): """A refused column raises the refusal, not an Arrow cast error.""" database = _sqlite_database(tmp_path) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index be47d4377..614e9900e 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -23,7 +23,7 @@ the PostgreSQL cell comes from the connector's own storability rule (``unstorable_column_reason`` and ``validate_records``, over a mocked connection), so it is ``KEPT BY RULE`` or ``REFUSED``, never a measured read; the SpiralDB cell is measured -through the disk fake (``tests/test_databases/fake_pyspiral.py``). No database tells tag +through the disk fake (``tests/test_databases/fake_spiral_sdk.py``). No database tells tag columns from data columns: the connector databases tell only the record-id key, which Orcapod always writes as ``large_binary``. """ @@ -50,7 +50,6 @@ InMemoryArrowDatabase, PostgreSQLConnector, SQLiteConnector, - SpiralDBConnector, ) from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] from orcapod.databases.utils import identity_node @@ -62,7 +61,7 @@ REFUSED = "REFUSED" SILENT = "SILENT" -DATABASES = ("in-memory", "Delta", "SQLite", "PostgreSQL", "SpiralDB") +DATABASES = ("in-memory", "Delta", "SQLite", "PostgreSQL") @dataclasses.dataclass(frozen=True) @@ -636,12 +635,6 @@ def open_database(name: str, root: Path) -> Iterator[Any]: yield DeltaTableDatabase(root / "delta") elif name == "SQLite": yield ConnectorArrowDatabase(SQLiteConnector(str(root / "store.db"))) - elif name == "SpiralDB": - from tests.test_databases import fake_pyspiral - - with fake_pyspiral.install(root / "spiral"): - fake_pyspiral.FakeSpiral().project("p") - yield ConnectorArrowDatabase(SpiralDBConnector("p")) elif name == "PostgreSQL": with patch("psycopg.connect") as connect: connect.return_value = MagicMock() @@ -1047,29 +1040,25 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: the same values under another logical type identifier (another extension name over the same storage), which would otherwise read back as the stored type. Every batch written is read back with `get_all_records`. -The SpiralDB column is measured through the test suite's disk fake of SpiralDB, which -models what SpiralDB does to a column (no SpiralDB is used). No database tells tag +No database tells tag columns from data columns, so a type is kept or refused the same way in either role. The library value types (NumPy, pandas, Polars, torch) are [provisional](../concepts/arrays.md): their stored form may change in a later release. The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and -`ConnectorArrowDatabase` over `SQLiteConnector`, `PostgreSQLConnector` and -`SpiralDBConnector`. See [The database](../concepts/pipeline-job.md#the-database) for how a +`ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads +SpiralDB but does not write it for now (`SpiralDBWriteNotSupportedError`). 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: -- SpiralDB cannot store a null struct, so a struct column with a null row is refused - (the rows below have one); a struct column with no null row is kept. - SQLite reads a NaN back as NULL and `-0.0` as `0.0`, so a `double` column holding one is refused (the float rows below hold both); one without them is kept. - Delta has no `null` type: a new column, or a new nested field, holding only nulls with no type is refused (the `null` row below), while a `null`-typed value is kept where the table already stores a type. -- Delta and SpiralDB give a map's key and item fields back as `key` and `value`, so a map - with other names is refused. SpiralDB does not keep metadata on a map's key or item - field, so a map with such metadata is refused there. +- Delta gives a map's key and item fields back as `key` and `value`, so a map with other + names is refused. - A fixed-size list or fixed-size binary read back by Delta with another length or width than its type is refused on read, never padded or cut. - Delta refuses a column whose name holds a backtick, or is one deltalake's MERGE reserves @@ -1134,14 +1123,10 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: type, the same field attributes), are put in the held order, whether the table was flushed in between or not. The in-memory database matches them to the rows still pending, else the stored table; Delta to the rows still pending (it matches a stored table by name -itself); a connector database (SQLite, PostgreSQL, SpiralDB) to the rows it has pending, +itself); a connector database (SQLite, PostgreSQL) to the rows it has pending, and to the stored table when it writes or reads them, checking them first against the table as it is then, by exact name and type (a column with field metadata stays in its -queued order at a flush; SpiralDB, which keeps field metadata, matches a write by name -itself). A table keeps the column -order the database gave its first write: the first write's order, except in SpiralDB, -which stores and reads a table's key columns first and then its other columns sorted by -name, whatever the order written (measured on SpiralDB itself). An append that also +queued order at a flush). A table keeps the column order of its first write. An append that also adds, omits or retypes a column keeps each database's own rule. The order of a struct's fields is not covered: a struct whose fields are in another order is another type here. """ diff --git a/tests/test_pipeline/test_run_warnings_caller_globals.py b/tests/test_pipeline/test_run_warnings_caller_globals.py index ba96a0af8..f7efe6431 100644 --- a/tests/test_pipeline/test_run_warnings_caller_globals.py +++ b/tests/test_pipeline/test_run_warnings_caller_globals.py @@ -41,7 +41,7 @@ ) from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.sources import DictSource, SpiralDBTableSource -from tests.test_databases import fake_pyspiral +from tests.test_databases import fake_spiral_sdk RUN_WARNINGS = ( RestrictedAggregationWarning, @@ -216,8 +216,8 @@ def _rows(n: int) -> list[dict[str, Any]]: @pytest.fixture() def spiral(tmp_path: Path) -> Iterator[None]: """Provide a fake SpiralDB project with two tables, ``event`` and ``trial``.""" - with fake_pyspiral.install(tmp_path / "spiral"): - project = fake_pyspiral.FakeSpiral().project(_PROJECT) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) for name in ("event", "trial"): project.create_table(f"default.{name}", key_schema=_KEYS).write( pa.table( diff --git a/uv.lock b/uv.lock index 31a050573..1eac880a4 100644 --- a/uv.lock +++ b/uv.lock @@ -265,19 +265,6 @@ version = "4.9.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/3e/38/7859ff46355f76f8d19459005ca000b6e7012f2f1ca597746cbcd1fbfe5e/antlr4-python3-runtime-4.9.3.tar.gz", hash = "sha256:f224469b4168294902bb1efa80a8bf7855f24c99aef99cbefc1bcd3cce77881b", size = 117034, upload-time = "2021-11-06T17:52:23.524Z" } -[[package]] -name = "anyio" -version = "4.14.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, -] - [[package]] name = "appnope" version = "0.1.4" @@ -384,19 +371,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/31/87045d1c66ee10a52486c9d2047bc69f00f2689f69401bb1e998afb4b205/beartype-0.21.0-py3-none-any.whl", hash = "sha256:b6a1bd56c72f31b0a496a36cc55df6e2f475db166ad07fa4acc7e74f4c7f34c0", size = 1191340, upload-time = "2025-05-22T05:09:24.606Z" }, ] -[[package]] -name = "betterproto2" -version = "0.9.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "python-dateutil" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/ac/02/4ae507aa18b8aa1681ea6e9f0dec08fabd610a94ade584fd9b071d286bf1/betterproto2-0.9.1.tar.gz", hash = "sha256:59d518cfbdd316e216c3d7f53448a6956432c7bd86ab9918fd8793c88c623cce", size = 143980, upload-time = "2025-10-15T09:36:24.425Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3e/a3/44f9d1188ee3802d2402efb121e7a9ce4c825eaa34ca739fbfb8979526a2/betterproto2-0.9.1-py3-none-any.whl", hash = "sha256:de0544b4b2b6b5a05ce0c1bfac36d232f745087b02907e748f31466becfc3dbd", size = 19562, upload-time = "2025-10-15T09:36:23.169Z" }, -] - [[package]] name = "blinker" version = "1.9.0" @@ -831,15 +805,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/2b/238f02a4927fa2e27aa995371d240a468b52e42eae44a678434aff736b38/distlib-0.4.4-py2.py3-none-any.whl", hash = "sha256:cf09d55b1e85a89576b036aeb71550bfd68320f3f21761ca329eadadad918638", size = 472099, upload-time = "2026-10-16T13:56:32.053Z" }, ] -[[package]] -name = "dnspython" -version = "2.9.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/76/49/900383b471c645a3c397f47b3211d1fcecb3a540c98f683494cdf86b33de/dnspython-2.9.2.tar.gz", hash = "sha256:8d4d39a513e649d634004ce4d39ade2352efcea472a0247535a5c2d18a9d7ba9", size = 455484, upload-time = "2026-11-03T23:56:53.601Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1e/0c/5346358b3a20275d256978c35203ddc2c8617f78c1b23795b79ba22ced6d/dnspython-2.9.2-py3-none-any.whl", hash = "sha256:af15f7d385a6ae2fb35a796fde2138004c8c42c7389090e2addc83e3b3340fd8", size = 360455, upload-time = "2026-11-03T23:56:52.088Z" }, -] - [[package]] name = "docker" version = "7.1.0" @@ -854,19 +819,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl", hash = "sha256:c96b93b7f0a746f9e77d325bcfb87422a3d8bd4f03136ae8a85b37f1898d5fc0", size = 147774, upload-time = "2024-05-23T11:13:55.01Z" }, ] -[[package]] -name = "email-validator" -version = "2.3.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "dnspython" }, - { name = "idna" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f5/22/900cb125c76b7aaa450ce02fd727f452243f2e91a61af068b40adba60ea9/email_validator-2.3.0.tar.gz", hash = "sha256:9fc05c37f2f6cf439ff414f8fc46d917929974a82244c20eb10231ba60c54426", size = 51238, upload-time = "2025-08-26T13:09:06.831Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/de/15/545e2b6cf2e3be84bc1ed85613edd75b8aea69807a71c26f4ca6a9258e82/email_validator-2.3.0-py3-none-any.whl", hash = "sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4", size = 35604, upload-time = "2025-08-26T13:09:05.858Z" }, -] - [[package]] name = "execnet" version = "2.1.2" @@ -1064,58 +1016,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/17/63/b19553b658a1692443c62bd07e5868adaa0ad746a0751ba62c59568cd45b/google_auth-2.40.3-py2.py3-none-any.whl", hash = "sha256:1370d4593e86213563547f97a92752fc658456fe4514c809544f330fed45a7ca", size = 216137, upload-time = "2025-06-04T18:04:55.573Z" }, ] -[[package]] -name = "google-re2" -version = "1.1.20251105" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/6b/60/805c654ba53d685513df955ee745f71920fe8e6a284faf0f9b9dc19b659c/google_re2-1.1.20251105.tar.gz", hash = "sha256:1db14a292ee8303b91e91e7c37e05ac17d3c467f29416c79ac70a78be3e65bda", size = 11676, upload-time = "2025-11-05T14:58:07.324Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/8d/4d/203a08dab1bdb5c83b46dd424c01a789ecb5a37dbc80f33d016bd116a9d7/google_re2-1.1.20251105-1-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:329efa209ea7baa44f0facf0402fa34e655dc97fdeb10d0b83fc06354f5575fd", size = 483717, upload-time = "2025-11-05T14:57:04.808Z" }, - { url = "https://files.pythonhosted.org/packages/78/88/466026b43ff5c7d740f5ede090992ec63b60d1810ab14fe35dfc00677e0a/google_re2-1.1.20251105-1-cp311-cp311-macosx_13_0_x86_64.whl", hash = "sha256:aa2ad5f6f48921ec137a7b7f1b1da903ddef8627a2dc30bc878a9a69d9925719", size = 515547, upload-time = "2025-11-05T14:57:06.013Z" }, - { url = "https://files.pythonhosted.org/packages/f3/6a/c6c9fdb00c98990e4f7a6cd650e209d7b5d2754ca0404b72c69ac9909a69/google_re2-1.1.20251105-1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:ac1cb2526cc88f050a0661fc7245ad009ee454bddc541b2e653f1d007585000d", size = 485396, upload-time = "2025-11-05T14:57:07.592Z" }, - { url = "https://files.pythonhosted.org/packages/a2/f6/529c44f607c47f96cfa29c1fe3a690fe75b2fdb48e9b0d6b54e5f0a75e59/google_re2-1.1.20251105-1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:50c7205182ad66c23c07abe8072f720ca2f7d595b61e28fd9b63623614f9afd6", size = 517150, upload-time = "2025-11-05T14:57:09.376Z" }, - { url = "https://files.pythonhosted.org/packages/df/d2/ccc07860e31ab81965c63f9ed4eb69ea0d3449a9b4e1610f71883694bbe8/google_re2-1.1.20251105-1-cp311-cp311-macosx_15_0_arm64.whl", hash = "sha256:4cb5acee61e35772503b8b1db3c592a46b8e6a9bc0ab54d7d6233654ea2bf93d", size = 482807, upload-time = "2025-11-05T14:57:11.057Z" }, - { url = "https://files.pythonhosted.org/packages/bd/43/5fb20d16664457f61670bdd95f39039d43ee8b7732511c688e2f322a4317/google_re2-1.1.20251105-1-cp311-cp311-macosx_15_0_x86_64.whl", hash = "sha256:1617097d63620c2d46bdfc0e48f24f66cd341664fc75718636d234f67473fe7f", size = 508839, upload-time = "2025-11-05T14:57:12.338Z" }, - { url = "https://files.pythonhosted.org/packages/0e/f2/6e470338271e164dd3c5e508876f99aec3ed23bf419c7d54a5672fd5b05f/google_re2-1.1.20251105-1-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:18a5610b26742b90cb1d64ead2b16fe0e3bd7e67add03fd3779cd1b85e401661", size = 573718, upload-time = "2025-11-05T14:57:13.635Z" }, - { url = "https://files.pythonhosted.org/packages/91/21/4566fc344c21cf3c49082d13ddab785994b5e3b8b7fd4631242538f698a2/google_re2-1.1.20251105-1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:03156291269f145eccddff63118f2df02d395792f51fc039f09955818943815a", size = 590749, upload-time = "2025-11-05T14:57:14.864Z" }, - { url = "https://files.pythonhosted.org/packages/94/19/5981fb798bb8d08933b815b1fd9e55d179c380b9d8c21a49197b9b7c5967/google_re2-1.1.20251105-1-cp311-cp311-win32.whl", hash = "sha256:54f51762b51dc238eceddf49b56cc2b64594fe72d9328c1c39d615aa990e1f87", size = 434066, upload-time = "2025-11-05T14:57:16.22Z" }, - { url = "https://files.pythonhosted.org/packages/49/e5/f83053a36cfc4762d843748e4f7a9c1141937dcf74cd6fc3f4598292dda3/google_re2-1.1.20251105-1-cp311-cp311-win_amd64.whl", hash = "sha256:f5f856ff5036a8f22b3bad57f376d4e3b97b59b64f311bdb1f83c8dabded2492", size = 491025, upload-time = "2025-11-05T14:57:17.746Z" }, - { url = "https://files.pythonhosted.org/packages/56/be/4315c3b38f42f9a2888fa76260545c98547502f1c35aa63a672d39011b2e/google_re2-1.1.20251105-1-cp311-cp311-win_arm64.whl", hash = "sha256:913864f97de4151eaa8bb7746ca230fd193656501e07fb658ce2cd46d4f6efcc", size = 642194, upload-time = "2025-11-05T14:57:19.374Z" }, - { url = "https://files.pythonhosted.org/packages/67/20/73b487538e9107c2fd96aed737e3f3890dfce3e292622e4ffb2f9c810ee5/google_re2-1.1.20251105-1-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:b30f09b4d63249c72e65ccae4cbf6b331b48c22fc7cb439f1d85f347b9d07ceb", size = 485591, upload-time = "2025-11-05T14:57:20.961Z" }, - { url = "https://files.pythonhosted.org/packages/b9/9a/ca3a993bdb5dc6d5b2616b9657b2872a83d1827f8bd3ab50cd629eb751c7/google_re2-1.1.20251105-1-cp312-cp312-macosx_13_0_x86_64.whl", hash = "sha256:9a77892c524b8bdf3d47d7cad1cc2ac3a0108bdd65007ef4c02888fa46baf8ee", size = 518780, upload-time = "2025-11-05T14:57:22.18Z" }, - { url = "https://files.pythonhosted.org/packages/df/37/b2e367987371514253ec9e514637f457deaacb7acc1c900814f3a6421e0f/google_re2-1.1.20251105-1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a3ac51b28cbf25c100dfd8849212d878d7005d1d4a7e129a10789043c56b6021", size = 486966, upload-time = "2025-11-05T14:57:24.575Z" }, - { url = "https://files.pythonhosted.org/packages/d9/69/1db6742943c0ac254bfb7d8a37a5d3f73f016a65cfa1f84fe3a0451820f6/google_re2-1.1.20251105-1-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:9f7158afc9825ac2654c6561aea94a1f7edb5b5b88e6e3639bb80bb817d102ac", size = 520225, upload-time = "2025-11-05T14:57:26.039Z" }, - { url = "https://files.pythonhosted.org/packages/f4/0a/0747c92dbebe2c09a26bd7386d372b5c5a9926236b4f3d69bb8f15db05cb/google_re2-1.1.20251105-1-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:5320da07dc3b7ac7f407514f42ac17d67e771ac7c7562d449571185e6fb601b2", size = 482943, upload-time = "2025-11-05T14:57:27.353Z" }, - { url = "https://files.pythonhosted.org/packages/7f/14/6bfc6838bb6cb561824ac03deeab2bd11d5d9a93505f536c8fa2f6bd46c4/google_re2-1.1.20251105-1-cp312-cp312-macosx_15_0_x86_64.whl", hash = "sha256:5a4e5785bc30d52ce655d805b07ad2d8a4905429a5f690ae9c2f1caa76665709", size = 510384, upload-time = "2025-11-05T14:57:29.139Z" }, - { url = "https://files.pythonhosted.org/packages/8a/0a/6add090c917ee39f6f0be753037cafceb3bad904b424efc155fb38082635/google_re2-1.1.20251105-1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2b7a3b90f747130310d4b3b8e19ebb845d0d97c1deb63b36f76c7242dacbd736", size = 572446, upload-time = "2025-11-05T14:57:30.495Z" }, - { url = "https://files.pythonhosted.org/packages/0d/1c/8b1ccbeade96a21435d55b5185cd6d9b2ceab5a9af998a4d9099e0540759/google_re2-1.1.20251105-1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:809c5fa5d08279413b29c2e2c5c528e85cd94a0e0fd897db595a0c09eeee2782", size = 591348, upload-time = "2025-11-05T14:57:31.808Z" }, - { url = "https://files.pythonhosted.org/packages/62/cf/7bdd7a1ae7828b613011da808eafec4da3132f43c3be6af5e0bd670ebe8b/google_re2-1.1.20251105-1-cp312-cp312-win32.whl", hash = "sha256:d8424e63a9ec0fe5bde03d97876b2431f8a746af33eb475fa1ae39144bd05b2a", size = 433787, upload-time = "2025-11-05T14:57:33.071Z" }, - { url = "https://files.pythonhosted.org/packages/31/e9/5dd951c35acaabfe87c67228b9af2cdcd7779d9167edbe6b9094b8a8e529/google_re2-1.1.20251105-1-cp312-cp312-win_amd64.whl", hash = "sha256:062313c309f93dfeb6966372f4c446580e98879133ec155522eea8aaf568a5cd", size = 491726, upload-time = "2025-11-05T14:57:34.39Z" }, - { url = "https://files.pythonhosted.org/packages/60/8d/c1afd29fc2cb475fd4c634f3d3c8099c0efb662362c10b27a9eaf11c9357/google_re2-1.1.20251105-1-cp312-cp312-win_arm64.whl", hash = "sha256:558f144b26a9555ae4e9467cc3aa3299a8ce13217f328b21ae326ca0633be19b", size = 642673, upload-time = "2025-11-05T14:57:35.693Z" }, - { url = "https://files.pythonhosted.org/packages/a5/b9/c441722196598fc3de0f654606ad9975a968c71dc27f516b5a4c9ebb94fd/google_re2-1.1.20251105-1-cp313-cp313-macosx_13_0_arm64.whl", hash = "sha256:9f3cf610e857a7d6f02916cf2b7fc159a5429b8bcb23164500d46e5e233f2924", size = 485549, upload-time = "2025-11-05T14:57:36.939Z" }, - { url = "https://files.pythonhosted.org/packages/ea/87/cf588255e5ada1dfb555cc96de35be78438bb0b6faba64df5fe91cecc224/google_re2-1.1.20251105-1-cp313-cp313-macosx_13_0_x86_64.whl", hash = "sha256:a21c2807bf4d5d00f206a4ecb3b043aad674e28c451b697b740280f608872078", size = 518840, upload-time = "2025-11-05T14:57:38.115Z" }, - { url = "https://files.pythonhosted.org/packages/0d/39/da66e4ca9be0c51546efc6fb39cf1683c4be8245d8199cb54a9808e8d5fa/google_re2-1.1.20251105-1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8314144eefeee7b88b742081c2038418f677e63901039ca9dbfbc0c5bb6d2911", size = 487037, upload-time = "2025-11-05T14:57:39.467Z" }, - { url = "https://files.pythonhosted.org/packages/75/dd/24ba65692dd58dca6ff178428551f4e9b776d1489a1251f5c8539e598baa/google_re2-1.1.20251105-1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:28a46be978e53c772139d0f5c9ba69f53563fcdd4225407e4d34d51208b828f1", size = 520285, upload-time = "2025-11-05T14:57:40.666Z" }, - { url = "https://files.pythonhosted.org/packages/61/12/cfdbb92bed24af6474970a75a26145c424f98cfbcc633fdd185985f0efe0/google_re2-1.1.20251105-1-cp313-cp313-macosx_15_0_arm64.whl", hash = "sha256:83292e23963aa1b219d5f64a65365b0880448a6a060276027b55270bc5b18c7e", size = 482981, upload-time = "2025-11-05T14:57:41.928Z" }, - { url = "https://files.pythonhosted.org/packages/97/bf/5fc32ded9279e69a87b88d7261e7e77e2e26325d4e27ca1303a3215e430a/google_re2-1.1.20251105-1-cp313-cp313-macosx_15_0_x86_64.whl", hash = "sha256:1920b15dc9b1bdfeca5aa2c60900373c6f27cd1056d53cd299456ea5540a6fff", size = 510366, upload-time = "2025-11-05T14:57:43.21Z" }, - { url = "https://files.pythonhosted.org/packages/71/71/f927ddc7aef1b8d7ccc8a649c335d311f29f3dea658209e30e37720e4891/google_re2-1.1.20251105-1-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0b1458d9ca588124cd61aa1bf5388a216e1247e7d474f8e5e1530498044f5c87", size = 572390, upload-time = "2025-11-05T14:57:44.422Z" }, - { url = "https://files.pythonhosted.org/packages/f0/8c/23075e589038284c9487f41cde531d35873f9da622fb4ac7d1d97bd9086e/google_re2-1.1.20251105-1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a52cb204e49d20cdbb66faf394d57f476e96c39c23a328442ab0194fc6bd1a2b", size = 591386, upload-time = "2025-11-05T14:57:45.713Z" }, - { url = "https://files.pythonhosted.org/packages/f1/7f/858453ef689f6b9895cd02b466836a9d1a6e4ba535d1a275b01bf73baa1d/google_re2-1.1.20251105-1-cp313-cp313-win32.whl", hash = "sha256:67c5c73d7ebcf3f0e0a3b528b41bd8c6c04900f1598aebf05bbdf15a06cf5f9a", size = 433807, upload-time = "2025-11-05T14:57:46.92Z" }, - { url = "https://files.pythonhosted.org/packages/08/24/6ea87fe682e115ffd296e91eb5c5a266349d1ee8414ce8ece3f99ec1ac84/google_re2-1.1.20251105-1-cp313-cp313-win_amd64.whl", hash = "sha256:0bcba63ad3ea8926fb0c71bb5044e33d405bb9395f5b5444393cd5f28f0bf6d3", size = 491734, upload-time = "2025-11-05T14:57:48.304Z" }, - { url = "https://files.pythonhosted.org/packages/34/85/32ba71b06f3cf5f9856ae95b3d6463b971742453631a5ae2c5be338ea377/google_re2-1.1.20251105-1-cp313-cp313-win_arm64.whl", hash = "sha256:64ee189ea857f2126c5e42073cfa9b03e9f4cbaf073edbedb575059074841aa0", size = 642654, upload-time = "2025-11-05T14:57:49.602Z" }, - { url = "https://files.pythonhosted.org/packages/5e/7f/7eb238bdcd06182b5f427afd305cf413b7cf4ea71047308bbf35912cf923/google_re2-1.1.20251105-1-cp314-cp314-macosx_13_0_arm64.whl", hash = "sha256:cc151cf6a585d9ebe711da32b23683fcff40f78db8c8587c7f4b209ef4658809", size = 484719, upload-time = "2025-11-05T14:57:51.326Z" }, - { url = "https://files.pythonhosted.org/packages/6d/62/eed28eab67f939f4b9383c47b1db11638ade6ac30785c15cb960de85ba43/google_re2-1.1.20251105-1-cp314-cp314-macosx_13_0_x86_64.whl", hash = "sha256:7e2186d2c90488c1e11895343941f35ca2f58e9ba6c6b034fd531abe22ef77cc", size = 517698, upload-time = "2025-11-05T14:57:52.597Z" }, - { url = "https://files.pythonhosted.org/packages/f7/16/a1e6768513f788bf9c67a1cfe379ef34a793983eee46e4b653e42b558b78/google_re2-1.1.20251105-1-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:41be22359c3dceb582937739b4365dd8e279de24ad0a5b10e653503abaff2ed7", size = 486421, upload-time = "2025-11-05T14:57:53.852Z" }, - { url = "https://files.pythonhosted.org/packages/ca/fc/7a97ffd36d451e5a8bfaff2f9022b14807795d588f98227ff96e8da99856/google_re2-1.1.20251105-1-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:f3168d7bbac247c862ea85b2f3c011d3a04bedcb6892b37f14d488f4133b206e", size = 519037, upload-time = "2025-11-05T14:57:55.078Z" }, - { url = "https://files.pythonhosted.org/packages/5f/ee/8b6f7d94bb689dafdf60de8dd8f8f6296ad40d4d15c933fcda4da7a3a06b/google_re2-1.1.20251105-1-cp314-cp314-macosx_15_0_arm64.whl", hash = "sha256:79ce664038194a31bbcf422137f9607ae3d9946a5cff98cf0efbeb7f9411e64b", size = 483373, upload-time = "2025-11-05T14:57:56.297Z" }, - { url = "https://files.pythonhosted.org/packages/d1/a6/16a09e03d1de128f821869e4252688c21319f5017d9209f4d0e71ea5c951/google_re2-1.1.20251105-1-cp314-cp314-macosx_15_0_x86_64.whl", hash = "sha256:0476b07421b8882b279d5ceb5b760c15c62d581ded95274697fc1227e3869ee6", size = 510167, upload-time = "2025-11-05T14:57:57.653Z" }, - { url = "https://files.pythonhosted.org/packages/c4/9d/213dce5de401527369fb5af11096b18c06001d9eb71f3318fe5eba1ec706/google_re2-1.1.20251105-1-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:85feec3161ffdc12f6b144e37a2f91f80b771c72ffadde60191e89a49f6d7e81", size = 573176, upload-time = "2025-11-05T14:57:59.211Z" }, - { url = "https://files.pythonhosted.org/packages/03/be/a8def96aa4a80b233e105767d22e3de961dcde5a04f0a05cb4f3ddb4df78/google_re2-1.1.20251105-1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7bfaa2cf55daf0c5c650e68526bb20b61e37d7f3ae53f6893013acc1c91c116", size = 591483, upload-time = "2025-11-05T14:58:00.416Z" }, - { url = "https://files.pythonhosted.org/packages/14/ea/144bbc4b9359da89aec07b4c2a91a6bfe7119914885386577c665b07bb01/google_re2-1.1.20251105-1-cp314-cp314-win32.whl", hash = "sha256:214c1accdc60fff9ce1bf812b157147ca361844f496ed9e0d5f357b0e562ced8", size = 433773, upload-time = "2025-11-05T14:58:01.594Z" }, - { url = "https://files.pythonhosted.org/packages/96/b3/74e301211699f1b650ba7690a3e4e52146ac4266fcd62f3ea0a945b9eda4/google_re2-1.1.20251105-1-cp314-cp314-win_amd64.whl", hash = "sha256:6d4d5fdadd329a2ed193463899d00ef2fd126172f36a4c01c9def271f19801b6", size = 491893, upload-time = "2025-11-05T14:58:02.969Z" }, - { url = "https://files.pythonhosted.org/packages/6f/d1/4adcfcb9c95e3d064c9f7aaf6cb3a4fc842d86115014b9d4094db4d465b5/google_re2-1.1.20251105-1-cp314-cp314-win_arm64.whl", hash = "sha256:1d27f3a2a947ec1f721d0f14f661108acfd4f4d34f357ce28db951cc036656e5", size = 643093, upload-time = "2025-11-05T14:58:05.761Z" }, -] - [[package]] name = "googleapis-common-protos" version = "1.70.0" @@ -1175,63 +1075,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/34/80/de3eb55eb581815342d097214bed4c59e806b05f1b3110df03b2280d6dfd/grpcio-1.74.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd3c71aeee838299c5887230b8a1822795325ddfea635edd82954c1eaa831e24", size = 4489214, upload-time = "2025-07-24T18:53:59.771Z" }, ] -[[package]] -name = "grpclib" -version = "0.4.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "h2" }, - { name = "multidict" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5b/28/5a2c299ec82a876a252c5919aa895a6f1d1d35c96417c5ce4a4660dc3a80/grpclib-0.4.9.tar.gz", hash = "sha256:cc589c330fa81004c6400a52a566407574498cb5b055fa927013361e21466c46", size = 84798, upload-time = "2025-12-14T22:23:14.349Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/90/b0cbbd9efcc82816c58f31a34963071aa19fb792a212a5d9caf8e0fc3097/grpclib-0.4.9-py3-none-any.whl", hash = "sha256:7762ec1c8ed94dfad597475152dd35cbd11aecaaca2f243e29702435ca24cf0e", size = 77063, upload-time = "2025-12-14T22:23:13.224Z" }, -] - -[[package]] -name = "h11" -version = "0.16.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, -] - -[[package]] -name = "h2" -version = "4.4.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "hpack" }, - { name = "hyperframe" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e7/85/7c366e69d84c17bb778fe41419e1fbcce3033d5b7ce29bbffff0a98b859f/h2-4.4.1.tar.gz", hash = "sha256:4e866ffb1a869ae14dd9b5e6beb5c24a13da0495ad72b65925ded182521c1516", size = 2157281, upload-time = "2026-08-03T11:45:09.509Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/22/e85faf23bd72a92d1921e37d674ca56eb298a3c8be31fdecef0ff2b3aaac/h2-4.4.1-py3-none-any.whl", hash = "sha256:0e25f1462b23c9cb82d9eb02e28bc706dac2a68cb457c6a0d74d63c8a2a5d0e6", size = 62636, upload-time = "2026-08-03T11:44:59.164Z" }, -] - -[[package]] -name = "hpack" -version = "4.2.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/26/5b/fcabf6028144a8723726318b07a32c2f3314acdff6265743cf08a344b18e/hpack-4.2.0.tar.gz", hash = "sha256:0895cfa3b5531fc65fe439c05eb65144f123bf7a394fcaa56aa423548d8e45c0", size = 51300, upload-time = "2026-06-23T18:34:46.667Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/71/b4/4a9fcfb2aef6ba44d9073ecd301443aa00b3dac95de5619f2a7de7ec8a91/hpack-4.2.0-py3-none-any.whl", hash = "sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986", size = 34246, upload-time = "2026-06-23T18:34:45.472Z" }, -] - -[[package]] -name = "httpcore" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, -] - [[package]] name = "httpie" version = "3.2.4" @@ -1253,21 +1096,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/03/b6/39bcf01e1185882f34bc9fb77d1fb4a27911a55f60ab407de34abc8a2347/httpie-3.2.4-py3-none-any.whl", hash = "sha256:4bd0435cc4b9bca59501bc65089de96f3e93b393803f32a81951db62050ebf0b", size = 127860, upload-time = "2024-11-01T17:31:22.962Z" }, ] -[[package]] -name = "httpx" -version = "0.28.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, -] - [[package]] name = "hydra-core" version = "1.3.8" @@ -1282,15 +1110,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/13/69/8e5cf7ad847538fc180fbd06e8442b8bede53ee4852458a16e24231395e9/hydra_core-1.3.8-py3-none-any.whl", hash = "sha256:d5f184c291691cba835c7f04bc4e36270ad88b1d7e394a3712f5af084c30b394", size = 168949, upload-time = "2026-10-25T13:42:20.959Z" }, ] -[[package]] -name = "hyperframe" -version = "6.1.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/02/e7/94f8232d4a74cc99514c13a9f995811485a6903d48e5d952771ef6322e30/hyperframe-6.1.0.tar.gz", hash = "sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08", size = 26566, upload-time = "2025-01-22T21:41:49.302Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/48/30/47d0bf6072f7252e6521f3447ccfa40b421b6824517f82854703d0f5a98b/hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5", size = 13007, upload-time = "2025-01-22T21:41:47.295Z" }, -] - [[package]] name = "hypothesis" version = "6.151.10" @@ -2065,9 +1884,9 @@ dependencies = [ all = [ { name = "ipywidgets" }, { name = "psycopg", extra = ["binary"] }, - { name = "pyspiral" }, { name = "ray", extra = ["default"] }, { name = "redis" }, + { name = "spiral-sdk" }, { name = "torch", version = "2.15.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" }, { name = "torch", version = "2.15.0+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform == 'linux'" }, ] @@ -2082,7 +1901,7 @@ redis = [ { name = "redis" }, ] spiraldb = [ - { name = "pyspiral" }, + { name = "spiral-sdk" }, ] torch = [ { name = "torch", version = "2.15.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" }, @@ -2137,13 +1956,13 @@ requires-dist = [ { name = "psycopg", extras = ["binary"], marker = "extra == 'postgresql'", specifier = ">=3.1.17" }, { name = "pyarrow", specifier = ">=22.0.0" }, { name = "pydantic", specifier = ">=2.0" }, - { name = "pyspiral", marker = "extra == 'all'", specifier = ">=0.16.33" }, - { name = "pyspiral", marker = "extra == 'spiraldb'", specifier = ">=0.16.33" }, { name = "ray", extras = ["default"], marker = "extra == 'all'", specifier = ">=2.60.0,<3" }, { name = "ray", extras = ["default"], marker = "extra == 'ray'", specifier = ">=2.60.0,<3" }, { name = "redis", marker = "extra == 'all'", specifier = ">=6.2.0" }, { name = "redis", marker = "extra == 'redis'", specifier = ">=6.2.0" }, { name = "s3fs", specifier = ">=2025.12.0" }, + { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.74" }, + { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.74" }, { name = "starfix", specifier = ">=0.6.0,<0.7" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'all'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'torch'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, @@ -2190,74 +2009,6 @@ dev = [ { name = "typing-extensions" }, ] -[[package]] -name = "orjson" -version = "3.11.7" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/45/b268004f745ede84e5798b48ee12b05129d19235d0e15267aa57dcdb400b/orjson-3.11.7.tar.gz", hash = "sha256:9b1a67243945819ce55d24a30b59d6a168e86220452d2c96f4d1f093e71c0c49", size = 6144992, upload-time = "2026-02-02T15:38:49.29Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/37/02/da6cb01fc6087048d7f61522c327edf4250f1683a58a839fdcc435746dd5/orjson-3.11.7-cp311-cp311-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:9487abc2c2086e7c8eb9a211d2ce8855bae0e92586279d0d27b341d5ad76c85c", size = 228664, upload-time = "2026-02-02T15:37:25.542Z" }, - { url = "https://files.pythonhosted.org/packages/c1/c2/5885e7a5881dba9a9af51bc564e8967225a642b3e03d089289a35054e749/orjson-3.11.7-cp311-cp311-macosx_15_0_arm64.whl", hash = "sha256:79cacb0b52f6004caf92405a7e1f11e6e2de8bdf9019e4f76b44ba045125cd6b", size = 125344, upload-time = "2026-02-02T15:37:26.92Z" }, - { url = "https://files.pythonhosted.org/packages/a4/1d/4e7688de0a92d1caf600dfd5fb70b4c5bfff51dfa61ac555072ef2d0d32a/orjson-3.11.7-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c2e85fe4698b6a56d5e2ebf7ae87544d668eb6bde1ad1226c13f44663f20ec9e", size = 128404, upload-time = "2026-02-02T15:37:28.108Z" }, - { url = "https://files.pythonhosted.org/packages/2f/b2/ec04b74ae03a125db7bd69cffd014b227b7f341e3261bf75b5eb88a1aa92/orjson-3.11.7-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b8d14b71c0b12963fe8a62aac87119f1afdf4cb88a400f61ca5ae581449efcb5", size = 123677, upload-time = "2026-02-02T15:37:30.287Z" }, - { url = "https://files.pythonhosted.org/packages/4c/69/f95bdf960605f08f827f6e3291fe243d8aa9c5c9ff017a8d7232209184c3/orjson-3.11.7-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:91c81ef070c8f3220054115e1ef468b1c9ce8497b4e526cb9f68ab4dc0a7ac62", size = 128950, upload-time = "2026-02-02T15:37:31.595Z" }, - { url = "https://files.pythonhosted.org/packages/a4/1b/de59c57bae1d148ef298852abd31909ac3089cff370dfd4cd84cc99cbc42/orjson-3.11.7-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:411ebaf34d735e25e358a6d9e7978954a9c9d58cfb47bc6683cdc3964cd2f910", size = 141756, upload-time = "2026-02-02T15:37:32.985Z" }, - { url = "https://files.pythonhosted.org/packages/ee/9e/9decc59f4499f695f65c650f6cfa6cd4c37a3fbe8fa235a0a3614cb54386/orjson-3.11.7-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a16bcd08ab0bcdfc7e8801d9c4a9cc17e58418e4d48ddc6ded4e9e4b1a94062b", size = 130812, upload-time = "2026-02-02T15:37:34.204Z" }, - { url = "https://files.pythonhosted.org/packages/28/e6/59f932bcabd1eac44e334fe8e3281a92eacfcb450586e1f4bde0423728d8/orjson-3.11.7-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c0b51672e466fd7e56230ffbae7f1639e18d0ce023351fb75da21b71bc2c960", size = 133444, upload-time = "2026-02-02T15:37:35.446Z" }, - { url = "https://files.pythonhosted.org/packages/f1/36/b0f05c0eaa7ca30bc965e37e6a2956b0d67adb87a9872942d3568da846ae/orjson-3.11.7-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:136dcd6a2e796dfd9ffca9fc027d778567b0b7c9968d092842d3c323cef88aa8", size = 138609, upload-time = "2026-02-02T15:37:36.657Z" }, - { url = "https://files.pythonhosted.org/packages/b8/03/58ec7d302b8d86944c60c7b4b82975d5161fcce4c9bc8c6cb1d6741b6115/orjson-3.11.7-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:7ba61079379b0ae29e117db13bda5f28d939766e410d321ec1624afc6a0b0504", size = 408918, upload-time = "2026-02-02T15:37:38.076Z" }, - { url = "https://files.pythonhosted.org/packages/06/3a/868d65ef9a8b99be723bd510de491349618abd9f62c826cf206d962db295/orjson-3.11.7-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:0527a4510c300e3b406591b0ba69b5dc50031895b0a93743526a3fc45f59d26e", size = 143998, upload-time = "2026-02-02T15:37:39.706Z" }, - { url = "https://files.pythonhosted.org/packages/5b/c7/1e18e1c83afe3349f4f6dc9e14910f0ae5f82eac756d1412ea4018938535/orjson-3.11.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a709e881723c9b18acddcfb8ba357322491ad553e277cf467e1e7e20e2d90561", size = 134802, upload-time = "2026-02-02T15:37:41.002Z" }, - { url = "https://files.pythonhosted.org/packages/d4/0b/ccb7ee1a65b37e8eeb8b267dc953561d72370e85185e459616d4345bab34/orjson-3.11.7-cp311-cp311-win32.whl", hash = "sha256:c43b8b5bab288b6b90dac410cca7e986a4fa747a2e8f94615aea407da706980d", size = 127828, upload-time = "2026-02-02T15:37:42.241Z" }, - { url = "https://files.pythonhosted.org/packages/af/9e/55c776dffda3f381e0f07d010a4f5f3902bf48eaba1bb7684d301acd4924/orjson-3.11.7-cp311-cp311-win_amd64.whl", hash = "sha256:6543001328aa857187f905308a028935864aefe9968af3848401b6fe80dbb471", size = 124941, upload-time = "2026-02-02T15:37:43.444Z" }, - { url = "https://files.pythonhosted.org/packages/aa/8e/424a620fa7d263b880162505fb107ef5e0afaa765b5b06a88312ac291560/orjson-3.11.7-cp311-cp311-win_arm64.whl", hash = "sha256:1ee5cc7160a821dfe14f130bc8e63e7611051f964b463d9e2a3a573204446a4d", size = 126245, upload-time = "2026-02-02T15:37:45.18Z" }, - { url = "https://files.pythonhosted.org/packages/80/bf/76f4f1665f6983385938f0e2a5d7efa12a58171b8456c252f3bae8a4cf75/orjson-3.11.7-cp312-cp312-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:bd03ea7606833655048dab1a00734a2875e3e86c276e1d772b2a02556f0d895f", size = 228545, upload-time = "2026-02-02T15:37:46.376Z" }, - { url = "https://files.pythonhosted.org/packages/79/53/6c72c002cb13b5a978a068add59b25a8bdf2800ac1c9c8ecdb26d6d97064/orjson-3.11.7-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:89e440ebc74ce8ab5c7bc4ce6757b4a6b1041becb127df818f6997b5c71aa60b", size = 125224, upload-time = "2026-02-02T15:37:47.697Z" }, - { url = "https://files.pythonhosted.org/packages/2c/83/10e48852865e5dd151bdfe652c06f7da484578ed02c5fca938e3632cb0b8/orjson-3.11.7-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ede977b5fe5ac91b1dffc0a517ca4542d2ec8a6a4ff7b2652d94f640796342a", size = 128154, upload-time = "2026-02-02T15:37:48.954Z" }, - { url = "https://files.pythonhosted.org/packages/6e/52/a66e22a2b9abaa374b4a081d410edab6d1e30024707b87eab7c734afe28d/orjson-3.11.7-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b7b1dae39230a393df353827c855a5f176271c23434cfd2db74e0e424e693e10", size = 123548, upload-time = "2026-02-02T15:37:50.187Z" }, - { url = "https://files.pythonhosted.org/packages/de/38/605d371417021359f4910c496f764c48ceb8997605f8c25bf1dfe58c0ebe/orjson-3.11.7-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ed46f17096e28fb28d2975834836a639af7278aa87c84f68ab08fbe5b8bd75fa", size = 129000, upload-time = "2026-02-02T15:37:51.426Z" }, - { url = "https://files.pythonhosted.org/packages/44/98/af32e842b0ffd2335c89714d48ca4e3917b42f5d6ee5537832e069a4b3ac/orjson-3.11.7-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3726be79e36e526e3d9c1aceaadbfb4a04ee80a72ab47b3f3c17fefb9812e7b8", size = 141686, upload-time = "2026-02-02T15:37:52.607Z" }, - { url = "https://files.pythonhosted.org/packages/96/0b/fc793858dfa54be6feee940c1463370ece34b3c39c1ca0aa3845f5ba9892/orjson-3.11.7-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0724e265bc548af1dedebd9cb3d24b4e1c1e685a343be43e87ba922a5c5fff2f", size = 130812, upload-time = "2026-02-02T15:37:53.944Z" }, - { url = "https://files.pythonhosted.org/packages/dc/91/98a52415059db3f374757d0b7f0f16e3b5cd5976c90d1c2b56acaea039e6/orjson-3.11.7-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e7745312efa9e11c17fbd3cb3097262d079da26930ae9ae7ba28fb738367cbad", size = 133440, upload-time = "2026-02-02T15:37:55.615Z" }, - { url = "https://files.pythonhosted.org/packages/dc/b6/cb540117bda61791f46381f8c26c8f93e802892830a6055748d3bb1925ab/orjson-3.11.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f904c24bdeabd4298f7a977ef14ca2a022ca921ed670b92ecd16ab6f3d01f867", size = 138386, upload-time = "2026-02-02T15:37:56.814Z" }, - { url = "https://files.pythonhosted.org/packages/63/1a/50a3201c334a7f17c231eee5f841342190723794e3b06293f26e7cf87d31/orjson-3.11.7-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b9fc4d0f81f394689e0814617aadc4f2ea0e8025f38c226cbf22d3b5ddbf025d", size = 408853, upload-time = "2026-02-02T15:37:58.291Z" }, - { url = "https://files.pythonhosted.org/packages/87/cd/8de1c67d0be44fdc22701e5989c0d015a2adf391498ad42c4dc589cd3013/orjson-3.11.7-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:849e38203e5be40b776ed2718e587faf204d184fc9a008ae441f9442320c0cab", size = 144130, upload-time = "2026-02-02T15:38:00.163Z" }, - { url = "https://files.pythonhosted.org/packages/0f/fe/d605d700c35dd55f51710d159fc54516a280923cd1b7e47508982fbb387d/orjson-3.11.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4682d1db3bcebd2b64757e0ddf9e87ae5f00d29d16c5cdf3a62f561d08cc3dd2", size = 134818, upload-time = "2026-02-02T15:38:01.507Z" }, - { url = "https://files.pythonhosted.org/packages/e4/e4/15ecc67edb3ddb3e2f46ae04475f2d294e8b60c1825fbe28a428b93b3fbd/orjson-3.11.7-cp312-cp312-win32.whl", hash = "sha256:f4f7c956b5215d949a1f65334cf9d7612dde38f20a95f2315deef167def91a6f", size = 127923, upload-time = "2026-02-02T15:38:02.75Z" }, - { url = "https://files.pythonhosted.org/packages/34/70/2e0855361f76198a3965273048c8e50a9695d88cd75811a5b46444895845/orjson-3.11.7-cp312-cp312-win_amd64.whl", hash = "sha256:bf742e149121dc5648ba0a08ea0871e87b660467ef168a3a5e53bc1fbd64bb74", size = 125007, upload-time = "2026-02-02T15:38:04.032Z" }, - { url = "https://files.pythonhosted.org/packages/68/40/c2051bd19fc467610fed469dc29e43ac65891571138f476834ca192bc290/orjson-3.11.7-cp312-cp312-win_arm64.whl", hash = "sha256:26c3b9132f783b7d7903bf1efb095fed8d4a3a85ec0d334ee8beff3d7a4749d5", size = 126089, upload-time = "2026-02-02T15:38:05.297Z" }, - { url = "https://files.pythonhosted.org/packages/89/25/6e0e52cac5aab51d7b6dcd257e855e1dec1c2060f6b28566c509b4665f62/orjson-3.11.7-cp313-cp313-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:1d98b30cc1313d52d4af17d9c3d307b08389752ec5f2e5febdfada70b0f8c733", size = 228390, upload-time = "2026-02-02T15:38:06.8Z" }, - { url = "https://files.pythonhosted.org/packages/a5/29/a77f48d2fc8a05bbc529e5ff481fb43d914f9e383ea2469d4f3d51df3d00/orjson-3.11.7-cp313-cp313-macosx_15_0_arm64.whl", hash = "sha256:d897e81f8d0cbd2abb82226d1860ad2e1ab3ff16d7b08c96ca00df9d45409ef4", size = 125189, upload-time = "2026-02-02T15:38:08.181Z" }, - { url = "https://files.pythonhosted.org/packages/89/25/0a16e0729a0e6a1504f9d1a13cdd365f030068aab64cec6958396b9969d7/orjson-3.11.7-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:814be4b49b228cfc0b3c565acf642dd7d13538f966e3ccde61f4f55be3e20785", size = 128106, upload-time = "2026-02-02T15:38:09.41Z" }, - { url = "https://files.pythonhosted.org/packages/66/da/a2e505469d60666a05ab373f1a6322eb671cb2ba3a0ccfc7d4bc97196787/orjson-3.11.7-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d06e5c5fed5caedd2e540d62e5b1c25e8c82431b9e577c33537e5fa4aa909539", size = 123363, upload-time = "2026-02-02T15:38:10.73Z" }, - { url = "https://files.pythonhosted.org/packages/23/bf/ed73f88396ea35c71b38961734ea4a4746f7ca0768bf28fd551d37e48dd0/orjson-3.11.7-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:31c80ce534ac4ea3739c5ee751270646cbc46e45aea7576a38ffec040b4029a1", size = 129007, upload-time = "2026-02-02T15:38:12.138Z" }, - { url = "https://files.pythonhosted.org/packages/73/3c/b05d80716f0225fc9008fbf8ab22841dcc268a626aa550561743714ce3bf/orjson-3.11.7-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f50979824bde13d32b4320eedd513431c921102796d86be3eee0b58e58a3ecd1", size = 141667, upload-time = "2026-02-02T15:38:13.398Z" }, - { url = "https://files.pythonhosted.org/packages/61/e8/0be9b0addd9bf86abfc938e97441dcd0375d494594b1c8ad10fe57479617/orjson-3.11.7-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9e54f3808e2b6b945078c41aa8d9b5834b28c50843846e97807e5adb75fa9705", size = 130832, upload-time = "2026-02-02T15:38:14.698Z" }, - { url = "https://files.pythonhosted.org/packages/c9/ec/c68e3b9021a31d9ec15a94931db1410136af862955854ed5dd7e7e4f5bff/orjson-3.11.7-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a12b80df61aab7b98b490fe9e4879925ba666fccdfcd175252ce4d9035865ace", size = 133373, upload-time = "2026-02-02T15:38:16.109Z" }, - { url = "https://files.pythonhosted.org/packages/d2/45/f3466739aaafa570cc8e77c6dbb853c48bf56e3b43738020e2661e08b0ac/orjson-3.11.7-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:996b65230271f1a97026fd0e6a753f51fbc0c335d2ad0c6201f711b0da32693b", size = 138307, upload-time = "2026-02-02T15:38:17.453Z" }, - { url = "https://files.pythonhosted.org/packages/e1/84/9f7f02288da1ffb31405c1be07657afd1eecbcb4b64ee2817b6fe0f785fa/orjson-3.11.7-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:ab49d4b2a6a1d415ddb9f37a21e02e0d5dbfe10b7870b21bf779fc21e9156157", size = 408695, upload-time = "2026-02-02T15:38:18.831Z" }, - { url = "https://files.pythonhosted.org/packages/18/07/9dd2f0c0104f1a0295ffbe912bc8d63307a539b900dd9e2c48ef7810d971/orjson-3.11.7-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:390a1dce0c055ddf8adb6aa94a73b45a4a7d7177b5c584b8d1c1947f2ba60fb3", size = 144099, upload-time = "2026-02-02T15:38:20.28Z" }, - { url = "https://files.pythonhosted.org/packages/a5/66/857a8e4a3292e1f7b1b202883bcdeb43a91566cf59a93f97c53b44bd6801/orjson-3.11.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1eb80451a9c351a71dfaf5b7ccc13ad065405217726b59fdbeadbcc544f9d223", size = 134806, upload-time = "2026-02-02T15:38:22.186Z" }, - { url = "https://files.pythonhosted.org/packages/0a/5b/6ebcf3defc1aab3a338ca777214966851e92efb1f30dc7fc8285216e6d1b/orjson-3.11.7-cp313-cp313-win32.whl", hash = "sha256:7477aa6a6ec6139c5cb1cc7b214643592169a5494d200397c7fc95d740d5fcf3", size = 127914, upload-time = "2026-02-02T15:38:23.511Z" }, - { url = "https://files.pythonhosted.org/packages/00/04/c6f72daca5092e3117840a1b1e88dfc809cc1470cf0734890d0366b684a1/orjson-3.11.7-cp313-cp313-win_amd64.whl", hash = "sha256:b9f95dcdea9d4f805daa9ddf02617a89e484c6985fa03055459f90e87d7a0757", size = 124986, upload-time = "2026-02-02T15:38:24.836Z" }, - { url = "https://files.pythonhosted.org/packages/03/ba/077a0f6f1085d6b806937246860fafbd5b17f3919c70ee3f3d8d9c713f38/orjson-3.11.7-cp313-cp313-win_arm64.whl", hash = "sha256:800988273a014a0541483dc81021247d7eacb0c845a9d1a34a422bc718f41539", size = 126045, upload-time = "2026-02-02T15:38:26.216Z" }, - { url = "https://files.pythonhosted.org/packages/e9/1e/745565dca749813db9a093c5ebc4bac1a9475c64d54b95654336ac3ed961/orjson-3.11.7-cp314-cp314-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:de0a37f21d0d364954ad5de1970491d7fbd0fb1ef7417d4d56a36dc01ba0c0a0", size = 228391, upload-time = "2026-02-02T15:38:27.757Z" }, - { url = "https://files.pythonhosted.org/packages/46/19/e40f6225da4d3aa0c8dc6e5219c5e87c2063a560fe0d72a88deb59776794/orjson-3.11.7-cp314-cp314-macosx_15_0_arm64.whl", hash = "sha256:c2428d358d85e8da9d37cba18b8c4047c55222007a84f97156a5b22028dfbfc0", size = 125188, upload-time = "2026-02-02T15:38:29.241Z" }, - { url = "https://files.pythonhosted.org/packages/9d/7e/c4de2babef2c0817fd1f048fd176aa48c37bec8aef53d2fa932983032cce/orjson-3.11.7-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c4bc6c6ac52cdaa267552544c73e486fecbd710b7ac09bc024d5a78555a22f6", size = 128097, upload-time = "2026-02-02T15:38:30.618Z" }, - { url = "https://files.pythonhosted.org/packages/eb/74/233d360632bafd2197f217eee7fb9c9d0229eac0c18128aee5b35b0014fe/orjson-3.11.7-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bd0d68edd7dfca1b2eca9361a44ac9f24b078de3481003159929a0573f21a6bf", size = 123364, upload-time = "2026-02-02T15:38:32.363Z" }, - { url = "https://files.pythonhosted.org/packages/79/51/af79504981dd31efe20a9e360eb49c15f06df2b40e7f25a0a52d9ae888e8/orjson-3.11.7-cp314-cp314-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:623ad1b9548ef63886319c16fa317848e465a21513b31a6ad7b57443c3e0dcf5", size = 129076, upload-time = "2026-02-02T15:38:33.68Z" }, - { url = "https://files.pythonhosted.org/packages/67/e2/da898eb68b72304f8de05ca6715870d09d603ee98d30a27e8a9629abc64b/orjson-3.11.7-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6e776b998ac37c0396093d10290e60283f59cfe0fc3fccbd0ccc4bd04dd19892", size = 141705, upload-time = "2026-02-02T15:38:34.989Z" }, - { url = "https://files.pythonhosted.org/packages/c5/89/15364d92acb3d903b029e28d834edb8780c2b97404cbf7929aa6b9abdb24/orjson-3.11.7-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:652c6c3af76716f4a9c290371ba2e390ede06f6603edb277b481daf37f6f464e", size = 130855, upload-time = "2026-02-02T15:38:36.379Z" }, - { url = "https://files.pythonhosted.org/packages/c2/8b/ecdad52d0b38d4b8f514be603e69ccd5eacf4e7241f972e37e79792212ec/orjson-3.11.7-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a56df3239294ea5964adf074c54bcc4f0ccd21636049a2cf3ca9cf03b5d03cf1", size = 133386, upload-time = "2026-02-02T15:38:37.704Z" }, - { url = "https://files.pythonhosted.org/packages/b9/0e/45e1dcf10e17d0924b7c9162f87ec7b4ca79e28a0548acf6a71788d3e108/orjson-3.11.7-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:bda117c4148e81f746655d5a3239ae9bd00cb7bc3ca178b5fc5a5997e9744183", size = 138295, upload-time = "2026-02-02T15:38:39.096Z" }, - { url = "https://files.pythonhosted.org/packages/63/d7/4d2e8b03561257af0450f2845b91fbd111d7e526ccdf737267108075e0ba/orjson-3.11.7-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:23d6c20517a97a9daf1d48b580fcdc6f0516c6f4b5038823426033690b4d2650", size = 408720, upload-time = "2026-02-02T15:38:40.634Z" }, - { url = "https://files.pythonhosted.org/packages/78/cf/d45343518282108b29c12a65892445fc51f9319dc3c552ceb51bb5905ed2/orjson-3.11.7-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:8ff206156006da5b847c9304b6308a01e8cdbc8cce824e2779a5ba71c3def141", size = 144152, upload-time = "2026-02-02T15:38:42.262Z" }, - { url = "https://files.pythonhosted.org/packages/a9/3a/d6001f51a7275aacd342e77b735c71fa04125a3f93c36fee4526bc8c654e/orjson-3.11.7-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:962d046ee1765f74a1da723f4b33e3b228fe3a48bd307acce5021dfefe0e29b2", size = 134814, upload-time = "2026-02-02T15:38:43.627Z" }, - { url = "https://files.pythonhosted.org/packages/1d/d3/f19b47ce16820cc2c480f7f1723e17f6d411b3a295c60c8ad3aa9ff1c96a/orjson-3.11.7-cp314-cp314-win32.whl", hash = "sha256:89e13dd3f89f1c38a9c9eba5fbf7cdc2d1feca82f5f290864b4b7a6aac704576", size = 127997, upload-time = "2026-02-02T15:38:45.06Z" }, - { url = "https://files.pythonhosted.org/packages/12/df/172771902943af54bf661a8d102bdf2e7f932127968080632bda6054b62c/orjson-3.11.7-cp314-cp314-win_amd64.whl", hash = "sha256:845c3e0d8ded9c9271cd79596b9b552448b885b97110f628fb687aee2eed11c1", size = 124985, upload-time = "2026-02-02T15:38:46.388Z" }, - { url = "https://files.pythonhosted.org/packages/6f/1c/f2a8d8a1b17514660a614ce5f7aac74b934e69f5abc2700cc7ced882a009/orjson-3.11.7-cp314-cp314-win_arm64.whl", hash = "sha256:4a2e9c5be347b937a2e0203866f12bba36082e89b402ddb9e927d5822e43088d", size = 126038, upload-time = "2026-02-02T15:38:47.703Z" }, -] - [[package]] name = "packaging" version = "26.3" @@ -2798,11 +2549,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fd/7b/122376b1fd3c62c1ed9dc80c931ace4844b3c55407b6fb2d199377c9736f/pydantic-2.13.4-py3-none-any.whl", hash = "sha256:45a282cde31d808236fd7ea9d919b128653c8b38b393d1c4ab335c62924d9aba", size = 472262, upload-time = "2026-05-06T13:43:02.641Z" }, ] -[package.optional-dependencies] -email = [ - { name = "email-validator" }, -] - [[package]] name = "pydantic-core" version = "2.46.4" @@ -2945,20 +2691,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/69/c0087d19c8d8e8530acee3ba485d54aedeebf2963784a16692ca4b439566/pyiceberg-0.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:124793c54a0c2fb5ac4ab19c38da116c068e277c85cbaa7e4064e635a70b595e", size = 595512, upload-time = "2025-04-30T14:59:14.464Z" }, ] -[[package]] -name = "pyjwt" -version = "2.15.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" }, -] - -[package.optional-dependencies] -crypto = [ - { name = "cryptography" }, -] - [[package]] name = "pyparsing" version = "3.2.3" @@ -2968,15 +2700,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/05/e7/df2285f3d08fee213f2d041540fa4fc9ca6c2d44cf36d3a035bf2a8d2bcc/pyparsing-3.2.3-py3-none-any.whl", hash = "sha256:a749938e02d6fd0b59b356ca504a24982314bb090c383e3cf201c95ef7e2bfcf", size = 111120, upload-time = "2025-03-25T05:01:24.908Z" }, ] -[[package]] -name = "pyperclip" -version = "1.11.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e8/52/d87eba7cb129b81563019d1679026e7a112ef76855d6159d24754dbd2a51/pyperclip-1.11.0.tar.gz", hash = "sha256:244035963e4428530d9e3a6101a1ef97209c6825edab1567beac148ccc1db1b6", size = 12185, upload-time = "2025-09-26T14:40:37.245Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/df/80/fc9d01d5ed37ba4c42ca2b55b4339ae6e200b456be3a1aaddf4a9fa99b8c/pyperclip-1.11.0-py3-none-any.whl", hash = "sha256:299403e9ff44581cb9ba2ffeed69c7aa96a008622ad0c46cb575ca75b5b84273", size = 11063, upload-time = "2025-09-26T14:40:36.069Z" }, -] - [[package]] name = "pyright" version = "1.1.404" @@ -2999,32 +2722,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8d/59/b4572118e098ac8e46e399a1dd0f2d85403ce8bbaad9ec79373ed6badaf9/PySocks-1.7.1-py3-none-any.whl", hash = "sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5", size = 16725, upload-time = "2019-09-20T02:06:22.938Z" }, ] -[[package]] -name = "pyspiral" -version = "0.16.33" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "betterproto2" }, - { name = "click" }, - { name = "google-re2" }, - { name = "grpclib" }, - { name = "httpx" }, - { name = "orjson" }, - { name = "pyarrow" }, - { name = "pydantic", extra = ["email"] }, - { name = "pyjwt", extra = ["crypto"] }, - { name = "pyperclip" }, - { name = "questionary" }, - { name = "substrait" }, - { name = "typer" }, - { name = "zstandard" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/99/fe/4dfe30304cd10ecd49b52e6a3b217e25e82c4646ab2dc0f2150c749fbdb0/pyspiral-0.16.33-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:2dc394bbe2f9d57b2bb12ce829602db333cbeb77ceb1a87992226e6fd236fd27", size = 38610323, upload-time = "2026-10-21T12:29:58.326Z" }, - { url = "https://files.pythonhosted.org/packages/ac/53/9f0cbe798684d4177b92a6e156ffb7377afc9210e4001635cfa14440271d/pyspiral-0.16.33-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b88378adedc2db9c42d66f3e39e1fe0a95377f8c0fd492dca1f5a949f22f9bc3", size = 46341849, upload-time = "2026-10-21T12:30:01.633Z" }, - { url = "https://files.pythonhosted.org/packages/ad/99/cc2976bdb3a1c7aee7dee220882248beee8dd37625e48861c951596aae7b/pyspiral-0.16.33-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:19f05646d2fcac06c3f6c0ea654ff27bc02fd515f848e9e3e2d583db4a2239f7", size = 45783449, upload-time = "2026-10-21T12:30:04.678Z" }, -] - [[package]] name = "pytest" version = "8.3.5" @@ -3229,18 +2926,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/13/9c/d8073bd898eb896e94c679abe82e47506e2b750eb261cf6010ced869797c/pyzmq-26.4.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:a222ad02fbe80166b0526c038776e8042cd4e5f0dec1489a006a1df47e9040e0", size = 555371, upload-time = "2025-04-04T12:05:20.702Z" }, ] -[[package]] -name = "questionary" -version = "2.1.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "prompt-toolkit" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f6/45/eafb0bba0f9988f6a2520f9ca2df2c82ddfa8d67c95d6625452e97b204a5/questionary-2.1.1.tar.gz", hash = "sha256:3d7e980292bb0107abaa79c68dd3eee3c561b83a0f89ae482860b181c8bd412d", size = 25845, upload-time = "2025-08-28T19:00:20.851Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3c/26/1062c7ec1b053db9e499b4d2d5bc231743201b74051c973dadeac80a8f43/questionary-2.1.1-py3-none-any.whl", hash = "sha256:a51af13f345f1cdea62347589fbb6df3b290306ab8930713bfae4d475a7d4a59", size = 36753, upload-time = "2025-08-28T19:00:19.56Z" }, -] - [[package]] name = "ray" version = "2.60.0" @@ -3607,6 +3292,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, ] +[[package]] +name = "spiral-sdk" +version = "0.16.74" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "pyarrow" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/e4/35/68f43088c6d1ec1db947620a58ea9d3096b6871b22367cb7aee86da88387/spiral_sdk-0.16.74-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:3f624ce767c074fbc04e0d2c96db6b4587fae2f8b653f1b15a8c9d35bc524586", size = 78387050, upload-time = "2026-11-24T19:03:05.807Z" }, + { url = "https://files.pythonhosted.org/packages/b4/23/47a6e94f2b86ed7113f1c2ee2c7289667168829d8098d5a3cdcd75bd1b9a/spiral_sdk-0.16.74-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ab2278a9b47828f98d93f76e2b93d57f16cf0b2008fc723ae7f788ea8607d495", size = 87372785, upload-time = "2026-11-24T19:03:11.829Z" }, + { url = "https://files.pythonhosted.org/packages/b9/d0/96107cf185d1bef4cfd427775553594c4decf420997019913a26eb8e5c38/spiral_sdk-0.16.74-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:46bb6f94583e507fcf31b2a3344ab4a582129c495c1bd782aaf64b4dd513ac9b", size = 90075516, upload-time = "2026-11-24T19:03:17.262Z" }, +] + [[package]] name = "stack-data" version = "0.6.3" @@ -3650,41 +3349,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/96/7c/a81ef5ef10978dd073a854e0fa93b5d8021d0594b639cc8f6453c3c78a1d/strictyaml-1.7.3-py3-none-any.whl", hash = "sha256:fb5c8a4edb43bebb765959e420f9b3978d7f1af88c80606c03fb420888f5d1c7", size = 123917, upload-time = "2023-03-10T12:50:17.242Z" }, ] -[[package]] -name = "substrait" -version = "0.30.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "protobuf" }, - { name = "substrait-extensions" }, - { name = "substrait-protobuf" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7c/38/86cd5a2d856d5e837d358ed71bd07abd27791c522844aa1cfb0875ac7622/substrait-0.30.0.tar.gz", hash = "sha256:3ec97768ef5685fc47e89e0b5f152282a01594086e70586f48efcd6ac5bd6567", size = 225857, upload-time = "2026-07-29T13:23:26.789Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3c/3f/8892a5ca5891e965ab0566db4e66358ebe36188b8cba185cbdd314131746/substrait-0.30.0-py3-none-any.whl", hash = "sha256:7961c84d54da92526d11a7c346c511e5410823a6ef6c71282d72c615b41341e7", size = 95635, upload-time = "2026-07-29T13:23:25.265Z" }, -] - -[[package]] -name = "substrait-extensions" -version = "0.99.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d5/f4/86c5b06b3bdd33b6fbed3cd51dd94ef875887865583dc46e48ddcd032c6a/substrait_extensions-0.99.0.tar.gz", hash = "sha256:aff47c9e5b02af5dd4909109eb8eb64b035d625cf22d79951ac5a31b2dba3986", size = 57027, upload-time = "2026-07-26T05:28:14.73Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b4/c2/6494244aafe28da69e671ba8c0d3fa644d7c411f0d353c78c6c1c2374462/substrait_extensions-0.99.0-py3-none-any.whl", hash = "sha256:762c25bebd84af6dfee26ec7f0c18615457e773c4b45324ff8a8082dc527f2b4", size = 112906, upload-time = "2026-07-26T05:28:15.504Z" }, -] - -[[package]] -name = "substrait-protobuf" -version = "0.99.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "protobuf" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/59/c1/74612fbf902bb65240b05990b6dcdbe9424550309fae11a67678ec8cc081/substrait_protobuf-0.99.0.tar.gz", hash = "sha256:79f5f422dd4089c5538017cb0955df098e68f9709e543e991956ddfa3b9ae210", size = 65077, upload-time = "2026-07-26T05:28:31.907Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7a/21/84474cbe254b10533f0a79c4a20dcd13cf65bb7012f9c85062ab89066eaa/substrait_protobuf-0.99.0-py3-none-any.whl", hash = "sha256:6d00c8a4f6d5d822a2358f870d642f8fda0350e110025c978daf624ae2491f16", size = 70932, upload-time = "2026-07-26T05:28:32.7Z" }, -] - [[package]] name = "sympy" version = "1.14.0" @@ -4306,77 +3970,3 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/91/41e284ca2cf5211e05dae031d126a3668aea88fa759df56e7e35c6ad25ba/yarl-1.25.1-cp315-cp315t-win_arm64.whl", hash = "sha256:783dd1467083f4d3f7722ad6a313f24c173e7571372738fcb7a6e6d1ba48df25", size = 101804, upload-time = "2026-09-15T19:34:57.231Z" }, { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, ] - -[[package]] -name = "zstandard" -version = "0.25.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/83/c3ca27c363d104980f1c9cee1101cc8ba724ac8c28a033ede6aab89585b1/zstandard-0.25.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:933b65d7680ea337180733cf9e87293cc5500cc0eb3fc8769f4d3c88d724ec5c", size = 795254, upload-time = "2025-09-14T22:16:26.137Z" }, - { url = "https://files.pythonhosted.org/packages/ac/4d/e66465c5411a7cf4866aeadc7d108081d8ceba9bc7abe6b14aa21c671ec3/zstandard-0.25.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a3f79487c687b1fc69f19e487cd949bf3aae653d181dfb5fde3bf6d18894706f", size = 640559, upload-time = "2025-09-14T22:16:27.973Z" }, - { url = "https://files.pythonhosted.org/packages/12/56/354fe655905f290d3b147b33fe946b0f27e791e4b50a5f004c802cb3eb7b/zstandard-0.25.0-cp311-cp311-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:0bbc9a0c65ce0eea3c34a691e3c4b6889f5f3909ba4822ab385fab9057099431", size = 5348020, upload-time = "2025-09-14T22:16:29.523Z" }, - { url = "https://files.pythonhosted.org/packages/3b/13/2b7ed68bd85e69a2069bcc72141d378f22cae5a0f3b353a2c8f50ef30c1b/zstandard-0.25.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:01582723b3ccd6939ab7b3a78622c573799d5d8737b534b86d0e06ac18dbde4a", size = 5058126, upload-time = "2025-09-14T22:16:31.811Z" }, - { url = "https://files.pythonhosted.org/packages/c9/dd/fdaf0674f4b10d92cb120ccff58bbb6626bf8368f00ebfd2a41ba4a0dc99/zstandard-0.25.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:5f1ad7bf88535edcf30038f6919abe087f606f62c00a87d7e33e7fc57cb69fcc", size = 5405390, upload-time = "2025-09-14T22:16:33.486Z" }, - { url = "https://files.pythonhosted.org/packages/0f/67/354d1555575bc2490435f90d67ca4dd65238ff2f119f30f72d5cde09c2ad/zstandard-0.25.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:06acb75eebeedb77b69048031282737717a63e71e4ae3f77cc0c3b9508320df6", size = 5452914, upload-time = "2025-09-14T22:16:35.277Z" }, - { url = "https://files.pythonhosted.org/packages/bb/1f/e9cfd801a3f9190bf3e759c422bbfd2247db9d7f3d54a56ecde70137791a/zstandard-0.25.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9300d02ea7c6506f00e627e287e0492a5eb0371ec1670ae852fefffa6164b072", size = 5559635, upload-time = "2025-09-14T22:16:37.141Z" }, - { url = "https://files.pythonhosted.org/packages/21/88/5ba550f797ca953a52d708c8e4f380959e7e3280af029e38fbf47b55916e/zstandard-0.25.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:bfd06b1c5584b657a2892a6014c2f4c20e0db0208c159148fa78c65f7e0b0277", size = 5048277, upload-time = "2025-09-14T22:16:38.807Z" }, - { url = "https://files.pythonhosted.org/packages/46/c0/ca3e533b4fa03112facbe7fbe7779cb1ebec215688e5df576fe5429172e0/zstandard-0.25.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:f373da2c1757bb7f1acaf09369cdc1d51d84131e50d5fa9863982fd626466313", size = 5574377, upload-time = "2025-09-14T22:16:40.523Z" }, - { url = "https://files.pythonhosted.org/packages/12/9b/3fb626390113f272abd0799fd677ea33d5fc3ec185e62e6be534493c4b60/zstandard-0.25.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6c0e5a65158a7946e7a7affa6418878ef97ab66636f13353b8502d7ea03c8097", size = 4961493, upload-time = "2025-09-14T22:16:43.3Z" }, - { url = "https://files.pythonhosted.org/packages/cb/d3/23094a6b6a4b1343b27ae68249daa17ae0651fcfec9ed4de09d14b940285/zstandard-0.25.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:c8e167d5adf59476fa3e37bee730890e389410c354771a62e3c076c86f9f7778", size = 5269018, upload-time = "2025-09-14T22:16:45.292Z" }, - { url = "https://files.pythonhosted.org/packages/8c/a7/bb5a0c1c0f3f4b5e9d5b55198e39de91e04ba7c205cc46fcb0f95f0383c1/zstandard-0.25.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:98750a309eb2f020da61e727de7d7ba3c57c97cf6213f6f6277bb7fb42a8e065", size = 5443672, upload-time = "2025-09-14T22:16:47.076Z" }, - { url = "https://files.pythonhosted.org/packages/27/22/503347aa08d073993f25109c36c8d9f029c7d5949198050962cb568dfa5e/zstandard-0.25.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:22a086cff1b6ceca18a8dd6096ec631e430e93a8e70a9ca5efa7561a00f826fa", size = 5822753, upload-time = "2025-09-14T22:16:49.316Z" }, - { url = "https://files.pythonhosted.org/packages/e2/be/94267dc6ee64f0f8ba2b2ae7c7a2df934a816baaa7291db9e1aa77394c3c/zstandard-0.25.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:72d35d7aa0bba323965da807a462b0966c91608ef3a48ba761678cb20ce5d8b7", size = 5366047, upload-time = "2025-09-14T22:16:51.328Z" }, - { url = "https://files.pythonhosted.org/packages/7b/a3/732893eab0a3a7aecff8b99052fecf9f605cf0fb5fb6d0290e36beee47a4/zstandard-0.25.0-cp311-cp311-win32.whl", hash = "sha256:f5aeea11ded7320a84dcdd62a3d95b5186834224a9e55b92ccae35d21a8b63d4", size = 436484, upload-time = "2025-09-14T22:16:55.005Z" }, - { url = "https://files.pythonhosted.org/packages/43/a3/c6155f5c1cce691cb80dfd38627046e50af3ee9ddc5d0b45b9b063bfb8c9/zstandard-0.25.0-cp311-cp311-win_amd64.whl", hash = "sha256:daab68faadb847063d0c56f361a289c4f268706b598afbf9ad113cbe5c38b6b2", size = 506183, upload-time = "2025-09-14T22:16:52.753Z" }, - { url = "https://files.pythonhosted.org/packages/8c/3e/8945ab86a0820cc0e0cdbf38086a92868a9172020fdab8a03ac19662b0e5/zstandard-0.25.0-cp311-cp311-win_arm64.whl", hash = "sha256:22a06c5df3751bb7dc67406f5374734ccee8ed37fc5981bf1ad7041831fa1137", size = 462533, upload-time = "2025-09-14T22:16:53.878Z" }, - { url = "https://files.pythonhosted.org/packages/82/fc/f26eb6ef91ae723a03e16eddb198abcfce2bc5a42e224d44cc8b6765e57e/zstandard-0.25.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7b3c3a3ab9daa3eed242d6ecceead93aebbb8f5f84318d82cee643e019c4b73b", size = 795738, upload-time = "2025-09-14T22:16:56.237Z" }, - { url = "https://files.pythonhosted.org/packages/aa/1c/d920d64b22f8dd028a8b90e2d756e431a5d86194caa78e3819c7bf53b4b3/zstandard-0.25.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:913cbd31a400febff93b564a23e17c3ed2d56c064006f54efec210d586171c00", size = 640436, upload-time = "2025-09-14T22:16:57.774Z" }, - { url = "https://files.pythonhosted.org/packages/53/6c/288c3f0bd9fcfe9ca41e2c2fbfd17b2097f6af57b62a81161941f09afa76/zstandard-0.25.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:011d388c76b11a0c165374ce660ce2c8efa8e5d87f34996aa80f9c0816698b64", size = 5343019, upload-time = "2025-09-14T22:16:59.302Z" }, - { url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" }, - { url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" }, - { url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" }, - { url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" }, - { url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" }, - { url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" }, - { url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" }, - { url = "https://files.pythonhosted.org/packages/18/e1/97680c664a1bf9a247a280a053d98e251424af51f1b196c6d52f117c9720/zstandard-0.25.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:809c5bcb2c67cd0ed81e9229d227d4ca28f82d0f778fc5fea624a9def3963f91", size = 5268008, upload-time = "2025-09-14T22:17:13.627Z" }, - { url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" }, - { url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" }, - { url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" }, - { url = "https://files.pythonhosted.org/packages/ff/8d/0309daffea4fcac7981021dbf21cdb2e3427a9e76bafbcdbdf5392ff99a4/zstandard-0.25.0-cp312-cp312-win32.whl", hash = "sha256:23ebc8f17a03133b4426bcc04aabd68f8236eb78c3760f12783385171b0fd8bd", size = 436922, upload-time = "2025-09-14T22:17:24.398Z" }, - { url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" }, - { url = "https://files.pythonhosted.org/packages/ea/6b/8b51697e5319b1f9ac71087b0af9a40d8a6288ff8025c36486e0c12abcc4/zstandard-0.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:181eb40e0b6a29b3cd2849f825e0fa34397f649170673d385f3598ae17cca2e9", size = 462679, upload-time = "2025-09-14T22:17:23.147Z" }, - { url = "https://files.pythonhosted.org/packages/35/0b/8df9c4ad06af91d39e94fa96cc010a24ac4ef1378d3efab9223cc8593d40/zstandard-0.25.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ec996f12524f88e151c339688c3897194821d7f03081ab35d31d1e12ec975e94", size = 795735, upload-time = "2025-09-14T22:17:26.042Z" }, - { url = "https://files.pythonhosted.org/packages/3f/06/9ae96a3e5dcfd119377ba33d4c42a7d89da1efabd5cb3e366b156c45ff4d/zstandard-0.25.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a1a4ae2dec3993a32247995bdfe367fc3266da832d82f8438c8570f989753de1", size = 640440, upload-time = "2025-09-14T22:17:27.366Z" }, - { url = "https://files.pythonhosted.org/packages/d9/14/933d27204c2bd404229c69f445862454dcc101cd69ef8c6068f15aaec12c/zstandard-0.25.0-cp313-cp313-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:e96594a5537722fdfb79951672a2a63aec5ebfb823e7560586f7484819f2a08f", size = 5343070, upload-time = "2025-09-14T22:17:28.896Z" }, - { url = "https://files.pythonhosted.org/packages/6d/db/ddb11011826ed7db9d0e485d13df79b58586bfdec56e5c84a928a9a78c1c/zstandard-0.25.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:bfc4e20784722098822e3eee42b8e576b379ed72cca4a7cb856ae733e62192ea", size = 5063001, upload-time = "2025-09-14T22:17:31.044Z" }, - { url = "https://files.pythonhosted.org/packages/db/00/87466ea3f99599d02a5238498b87bf84a6348290c19571051839ca943777/zstandard-0.25.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:457ed498fc58cdc12fc48f7950e02740d4f7ae9493dd4ab2168a47c93c31298e", size = 5394120, upload-time = "2025-09-14T22:17:32.711Z" }, - { url = "https://files.pythonhosted.org/packages/2b/95/fc5531d9c618a679a20ff6c29e2b3ef1d1f4ad66c5e161ae6ff847d102a9/zstandard-0.25.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:fd7a5004eb1980d3cefe26b2685bcb0b17989901a70a1040d1ac86f1d898c551", size = 5451230, upload-time = "2025-09-14T22:17:34.41Z" }, - { url = "https://files.pythonhosted.org/packages/63/4b/e3678b4e776db00f9f7b2fe58e547e8928ef32727d7a1ff01dea010f3f13/zstandard-0.25.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8e735494da3db08694d26480f1493ad2cf86e99bdd53e8e9771b2752a5c0246a", size = 5547173, upload-time = "2025-09-14T22:17:36.084Z" }, - { url = "https://files.pythonhosted.org/packages/4e/d5/ba05ed95c6b8ec30bd468dfeab20589f2cf709b5c940483e31d991f2ca58/zstandard-0.25.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3a39c94ad7866160a4a46d772e43311a743c316942037671beb264e395bdd611", size = 5046736, upload-time = "2025-09-14T22:17:37.891Z" }, - { url = "https://files.pythonhosted.org/packages/50/d5/870aa06b3a76c73eced65c044b92286a3c4e00554005ff51962deef28e28/zstandard-0.25.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:172de1f06947577d3a3005416977cce6168f2261284c02080e7ad0185faeced3", size = 5576368, upload-time = "2025-09-14T22:17:40.206Z" }, - { url = "https://files.pythonhosted.org/packages/5d/35/398dc2ffc89d304d59bc12f0fdd931b4ce455bddf7038a0a67733a25f550/zstandard-0.25.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3c83b0188c852a47cd13ef3bf9209fb0a77fa5374958b8c53aaa699398c6bd7b", size = 4954022, upload-time = "2025-09-14T22:17:41.879Z" }, - { url = "https://files.pythonhosted.org/packages/9a/5c/36ba1e5507d56d2213202ec2b05e8541734af5f2ce378c5d1ceaf4d88dc4/zstandard-0.25.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1673b7199bbe763365b81a4f3252b8e80f44c9e323fc42940dc8843bfeaf9851", size = 5267889, upload-time = "2025-09-14T22:17:43.577Z" }, - { url = "https://files.pythonhosted.org/packages/70/e8/2ec6b6fb7358b2ec0113ae202647ca7c0e9d15b61c005ae5225ad0995df5/zstandard-0.25.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:0be7622c37c183406f3dbf0cba104118eb16a4ea7359eeb5752f0794882fc250", size = 5433952, upload-time = "2025-09-14T22:17:45.271Z" }, - { url = "https://files.pythonhosted.org/packages/7b/01/b5f4d4dbc59ef193e870495c6f1275f5b2928e01ff5a81fecb22a06e22fb/zstandard-0.25.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:5f5e4c2a23ca271c218ac025bd7d635597048b366d6f31f420aaeb715239fc98", size = 5814054, upload-time = "2025-09-14T22:17:47.08Z" }, - { url = "https://files.pythonhosted.org/packages/b2/e5/fbd822d5c6f427cf158316d012c5a12f233473c2f9c5fe5ab1ae5d21f3d8/zstandard-0.25.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4f187a0bb61b35119d1926aee039524d1f93aaf38a9916b8c4b78ac8514a0aaf", size = 5360113, upload-time = "2025-09-14T22:17:48.893Z" }, - { url = "https://files.pythonhosted.org/packages/8e/e0/69a553d2047f9a2c7347caa225bb3a63b6d7704ad74610cb7823baa08ed7/zstandard-0.25.0-cp313-cp313-win32.whl", hash = "sha256:7030defa83eef3e51ff26f0b7bfb229f0204b66fe18e04359ce3474ac33cbc09", size = 436936, upload-time = "2025-09-14T22:17:52.658Z" }, - { url = "https://files.pythonhosted.org/packages/d9/82/b9c06c870f3bd8767c201f1edbdf9e8dc34be5b0fbc5682c4f80fe948475/zstandard-0.25.0-cp313-cp313-win_amd64.whl", hash = "sha256:1f830a0dac88719af0ae43b8b2d6aef487d437036468ef3c2ea59c51f9d55fd5", size = 506232, upload-time = "2025-09-14T22:17:50.402Z" }, - { url = "https://files.pythonhosted.org/packages/d4/57/60c3c01243bb81d381c9916e2a6d9e149ab8627c0c7d7abb2d73384b3c0c/zstandard-0.25.0-cp313-cp313-win_arm64.whl", hash = "sha256:85304a43f4d513f5464ceb938aa02c1e78c2943b29f44a750b48b25ac999a049", size = 462671, upload-time = "2025-09-14T22:17:51.533Z" }, - { url = "https://files.pythonhosted.org/packages/3d/5c/f8923b595b55fe49e30612987ad8bf053aef555c14f05bb659dd5dbe3e8a/zstandard-0.25.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:e29f0cf06974c899b2c188ef7f783607dbef36da4c242eb6c82dcd8b512855e3", size = 795887, upload-time = "2025-09-14T22:17:54.198Z" }, - { url = "https://files.pythonhosted.org/packages/8d/09/d0a2a14fc3439c5f874042dca72a79c70a532090b7ba0003be73fee37ae2/zstandard-0.25.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:05df5136bc5a011f33cd25bc9f506e7426c0c9b3f9954f056831ce68f3b6689f", size = 640658, upload-time = "2025-09-14T22:17:55.423Z" }, - { url = "https://files.pythonhosted.org/packages/5d/7c/8b6b71b1ddd517f68ffb55e10834388d4f793c49c6b83effaaa05785b0b4/zstandard-0.25.0-cp314-cp314-manylinux2010_i686.manylinux_2_12_i686.manylinux_2_28_i686.whl", hash = "sha256:f604efd28f239cc21b3adb53eb061e2a205dc164be408e553b41ba2ffe0ca15c", size = 5379849, upload-time = "2025-09-14T22:17:57.372Z" }, - { url = "https://files.pythonhosted.org/packages/a4/86/a48e56320d0a17189ab7a42645387334fba2200e904ee47fc5a26c1fd8ca/zstandard-0.25.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:223415140608d0f0da010499eaa8ccdb9af210a543fac54bce15babbcfc78439", size = 5058095, upload-time = "2025-09-14T22:17:59.498Z" }, - { url = "https://files.pythonhosted.org/packages/f8/ad/eb659984ee2c0a779f9d06dbfe45e2dc39d99ff40a319895df2d3d9a48e5/zstandard-0.25.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e54296a283f3ab5a26fc9b8b5d4978ea0532f37b231644f367aa588930aa043", size = 5551751, upload-time = "2025-09-14T22:18:01.618Z" }, - { url = "https://files.pythonhosted.org/packages/61/b3/b637faea43677eb7bd42ab204dfb7053bd5c4582bfe6b1baefa80ac0c47b/zstandard-0.25.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ca54090275939dc8ec5dea2d2afb400e0f83444b2fc24e07df7fdef677110859", size = 6364818, upload-time = "2025-09-14T22:18:03.769Z" }, - { url = "https://files.pythonhosted.org/packages/31/dc/cc50210e11e465c975462439a492516a73300ab8caa8f5e0902544fd748b/zstandard-0.25.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e09bb6252b6476d8d56100e8147b803befa9a12cea144bbe629dd508800d1ad0", size = 5560402, upload-time = "2025-09-14T22:18:05.954Z" }, - { url = "https://files.pythonhosted.org/packages/c9/ae/56523ae9c142f0c08efd5e868a6da613ae76614eca1305259c3bf6a0ed43/zstandard-0.25.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a9ec8c642d1ec73287ae3e726792dd86c96f5681eb8df274a757bf62b750eae7", size = 4955108, upload-time = "2025-09-14T22:18:07.68Z" }, - { url = "https://files.pythonhosted.org/packages/98/cf/c899f2d6df0840d5e384cf4c4121458c72802e8bda19691f3b16619f51e9/zstandard-0.25.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:a4089a10e598eae6393756b036e0f419e8c1d60f44a831520f9af41c14216cf2", size = 5269248, upload-time = "2025-09-14T22:18:09.753Z" }, - { url = "https://files.pythonhosted.org/packages/1b/c0/59e912a531d91e1c192d3085fc0f6fb2852753c301a812d856d857ea03c6/zstandard-0.25.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f67e8f1a324a900e75b5e28ffb152bcac9fbed1cc7b43f99cd90f395c4375344", size = 5430330, upload-time = "2025-09-14T22:18:11.966Z" }, - { url = "https://files.pythonhosted.org/packages/a0/1d/7e31db1240de2df22a58e2ea9a93fc6e38cc29353e660c0272b6735d6669/zstandard-0.25.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9654dbc012d8b06fc3d19cc825af3f7bf8ae242226df5f83936cb39f5fdc846c", size = 5811123, upload-time = "2025-09-14T22:18:13.907Z" }, - { url = "https://files.pythonhosted.org/packages/f6/49/fac46df5ad353d50535e118d6983069df68ca5908d4d65b8c466150a4ff1/zstandard-0.25.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4203ce3b31aec23012d3a4cf4a2ed64d12fea5269c49aed5e4c3611b938e4088", size = 5359591, upload-time = "2025-09-14T22:18:16.465Z" }, - { url = "https://files.pythonhosted.org/packages/c2/38/f249a2050ad1eea0bb364046153942e34abba95dd5520af199aed86fbb49/zstandard-0.25.0-cp314-cp314-win32.whl", hash = "sha256:da469dc041701583e34de852d8634703550348d5822e66a0c827d39b05365b12", size = 444513, upload-time = "2025-09-14T22:18:20.61Z" }, - { url = "https://files.pythonhosted.org/packages/3a/43/241f9615bcf8ba8903b3f0432da069e857fc4fd1783bd26183db53c4804b/zstandard-0.25.0-cp314-cp314-win_amd64.whl", hash = "sha256:c19bcdd826e95671065f8692b5a4aa95c52dc7a02a4c5a0cac46deb879a017a2", size = 516118, upload-time = "2025-09-14T22:18:17.849Z" }, - { url = "https://files.pythonhosted.org/packages/f0/ef/da163ce2450ed4febf6467d77ccb4cd52c4c30ab45624bad26ca0a27260c/zstandard-0.25.0-cp314-cp314-win_arm64.whl", hash = "sha256:d7541afd73985c630bafcd6338d2518ae96060075f9463d7dc14cfb33514383d", size = 476940, upload-time = "2025-09-14T22:18:19.088Z" }, -] From f32881f7f8991a9fca92895e8f519baa3059c426 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 17:48:00 -0800 Subject: [PATCH 2/7] feat(pipeline): show a source by its assigned label (ITL-1454) (#551) * feat(pipeline): show a source by its assigned label (ITL-1454) Display only: the diagram, node preview, explain(), trace() and RestrictedAggregationWarning. No name, hash, id or stored path changes. Co-Authored-By: Claude Opus 5.5 * fix(sources): read a source's label past its class's hooks (ITL-1454) Co-Authored-By: Claude Opus 5.5 * test(pipeline): read the display-name tables through the spiral-sdk fake (ITL-1454) Co-Authored-By: Claude Opus 5.5 * fix(spiraldb): hold no lock while issuing UnrecordedTableSchemaWarning (ITL-1454) A warning hook may wait for another thread that reads an unrecorded table. Addresses CodeRabbit's last thread on #550 (discussion_r4687711390). Co-Authored-By: Claude Opus 5.5 * fix(pipeline): narrow source labels to the diagram, preview and warning (ITL-1454) explain() and trace() are main's again: their public values must not move. Reading a label never raises, runs no metaclass hook, and a line break in a label is shown escaped. Co-Authored-By: Claude Opus 5.5 * test(pipeline): bind two labelled sources in either order (ITL-1454) Co-Authored-By: Claude Opus 5.5 * fix(sources): read class data past metaclass properties too (ITL-1454) Co-Authored-By: Claude Opus 5.5 * fix(sources): use only plain display parts (ITL-1454) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- changelog.d/ITL-1454.md | 7 + docs/concepts/pipeline-job.md | 11 + docs/concepts/sources.md | 3 +- src/orcapod/core/nodes/source_node.py | 10 + src/orcapod/core/sources/base.py | 4 + src/orcapod/core/sources/display_names.py | 200 +++++++ .../core/sources/spiraldb_table_source.py | 2 + src/orcapod/databases/spiraldb_connector.py | 28 +- src/orcapod/errors.py | 3 +- src/orcapod/pipeline/diagram.py | 41 +- .../pipeline/diagram_assets/diagram.js | 4 +- src/orcapod/pipeline/restrictions.py | 12 +- tests/test_databases/test_spiraldb_reading.py | 74 ++- .../test_source_display_names.py | 499 ++++++++++++++++++ 14 files changed, 870 insertions(+), 28 deletions(-) create mode 100644 changelog.d/ITL-1454.md create mode 100644 src/orcapod/core/sources/display_names.py create mode 100644 tests/test_pipeline/test_source_display_names.py diff --git a/changelog.d/ITL-1454.md b/changelog.d/ITL-1454.md new file mode 100644 index 000000000..51a265fd4 --- /dev/null +++ b/changelog.d/ITL-1454.md @@ -0,0 +1,7 @@ +### Changed + +- **A job shows a source by its own label.** Where the source bound to a slot has an assigned label, the job's diagram, the node's preview and `RestrictedAggregationWarning` name it by that label instead of its slot's name; the diagram's details and the warning give the full source id. Sources sharing a label, or a label that is another node's name, are shown as `label (part)`, with the shortest part that tells them apart (a SpiralDB table's dataset, then its project, then the source's name). Display only: slot names, node labels, the keys of `job.nodes`, saved files, hashes, ids and stored paths are unchanged, and so is the text of a source without a label and of a loaded job. (ITL-1454) + +### Fixed + +- **`UnrecordedTableSchemaWarning` holds no lock while it warns.** A warning hook may wait for another thread that reads an unrecorded SpiralDB table, or read the table itself. The warning is usually shown once per table and process: threads reading a table at the same time may each show it, and once shown it is not shown again. Turned into an error, it is raised by every reader. (ITL-1454) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 499cbd724..10c01b935 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -429,6 +429,17 @@ function of a function pod, the class of a bound source), and for a job its stat A selected node also shows the row counts of the job's last run (`job.last_run`). +A source bound with a label (`DictSource(..., label="mice")`, `SpiralDBTableSource(..., +label="units")`) is shown in a job's diagram, in its node's preview, and in +`RestrictedAggregationWarning` by that label; the diagram's details (`source id`) and the +warning give its full source id. `explain()` and `trace()` name it by its id. Two sources with one +label, or a label that is another node's name, are shown as `label (part)`: a SpiralDB +table's dataset, else its project, else the source's name. A single node's preview shows the label +alone. This is display only: the slot +keeps its name, the one `job.nodes[...]` and `bind` take. In a diagram, a source without a label is shown +by its slot's name, as is every source of a `Pipeline` (which binds none) and of a loaded +job (a source's label is not saved). + The options: - `direction="TB"` lays the graph out top to bottom instead of left to right. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4ed1897b1..de39979ad 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -695,7 +695,8 @@ every depth and metadata. The name is reserved, and listings leave it out. - **A table that is not recorded** (its dataset has no `__orcapod_schemas__`, or no row for it) reads as SpiralDB reports it: every column has the type `T | None` and no metadata, and a function pod must accept `None` (`x: float | None`). `UnrecordedTableSchemaWarning` says - so, once per table and process. + so, usually once per table and process (threads reading it at the same time may each + show it; once shown, it is not shown again). - **A record that is not complete** is refused: the last row written says for which project and dataset, how many tables, and a digest of their rows. When it is missing or does not fit, every read that opens a table of the dataset raises `TableSchemaError`, and so does a diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index e2b83b4e0..b6b8bc0f6 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1948,6 +1948,16 @@ def _typed_zero_row_table(self) -> "pa.Table | None": return table return self._declared_form.apply(table) + def _display_name(self) -> str: + """The name a preview header shows: the bound source's assigned label, else the + node's own. The node's label and the slot's name are not changed (ITL-1454).""" + from orcapod.core.sources.display_names import labelled_source + + source = labelled_source(self._bound_source) + if source is None or self.has_assigned_label: + return self.label + return source.label + def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the bound source.""" return self._bound_source is not None and schema_requires_io( diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index b719c6315..07221924c 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -127,6 +127,10 @@ class RootSource(StreamBase): values, other Arrow types, another record id): a new version is a new source id. """ + # The attributes holding what tells two sources of one label apart in a display, + # nearest first (``core/sources/display_names.py``); ``""`` for a kind without them. + DISPLAY_PARTS: ClassVar[tuple[str, str]] = ("", "") + @classmethod def kind_part(cls) -> str: """The kind part of this class's source ids: ``_v``.""" diff --git a/src/orcapod/core/sources/display_names.py b/src/orcapod/core/sources/display_names.py new file mode 100644 index 000000000..5d10e7c3d --- /dev/null +++ b/src/orcapod/core/sources/display_names.py @@ -0,0 +1,200 @@ +"""How a source is named where a pipeline is shown (ITL-1454): by its assigned label. + +Display only: a slot's name, a node's label, every hash, id and stored path are what they +are without it. Everything is read from what a source stores; no method or property of a +source is called, so showing a pipeline runs no user code. +""" + +from __future__ import annotations + +from collections.abc import Collection, Iterable, Mapping +from dataclasses import dataclass +from types import GetSetDescriptorType +from typing import Any + + +@dataclass(frozen=True) +class LabelledSource: + """A source with an assigned label, as a display names it. + + Attributes: + label: The assigned label. + source_id: The full source id (``_v:``). + parts: What tells it apart from a source of the same label, shortest first + (a SpiralDB table's dataset, its project, both, then any source's name and + id); ``""`` for a part its kind lacks. + """ + + label: str + source_id: str + parts: tuple[str, ...] + + +# The slots of ``type`` itself: an attribute or property a metaclass defines under the +# same name is not read. +_TYPE_MRO: Any = type.__dict__["__mro__"] +_TYPE_DICT: Any = type.__dict__["__dict__"] + + +def _mro(cls: type) -> tuple[type, ...]: + """Return a class and its bases, read past any metaclass hook.""" + return _TYPE_MRO.__get__(cls) + + +def _class_dicts(cls: type) -> list[Mapping[str, Any]]: + """Return the dictionaries of a class and its bases, read past any metaclass hook.""" + return [_TYPE_DICT.__get__(base) for base in _mro(cls)] + + +def _is_a(source: object, cls: type) -> bool: + """Whether ``source`` is an instance of ``cls`` by its real type.""" + return any(b is cls for b in _mro(type(source))) + + +def _stored(source: object) -> Mapping[str, Any]: + """Return an object's instance dictionary, read past any hook its class defines.""" + for namespace in _class_dicts(type(source)): + found = namespace.get("__dict__") + if type(found) is GetSetDescriptorType: + return found.__get__(source) + return {} + + +def _class_value(source: object, name: str) -> Any: + """Return what the class of ``source`` or its nearest base declares as ``name``.""" + return next(d[name] for d in _class_dicts(type(source)) if name in d) + + +_LINE_BREAKS = "\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029" + + +def _stored_text(source: object, name: str) -> str: + """Return the text stored under ``name``, as a plain ``str``; ``""`` for none.""" + value = _stored(source).get(name) + return str.__str__(value) if isinstance(value, str) else "" + + +def _one_line(text: str) -> str: + """Return ``text`` with its line breaks written as escapes.""" + return "".join(ascii(c)[1:-1] if c in _LINE_BREAKS else c for c in text) + + +def labelled_source(stream: Any) -> LabelledSource | None: + """Return the source as a display names it, or ``None`` when it has no label. + + ``None`` for a stream that is no source, a source with no assigned label and a + proxy of a source that could not be rebuilt. A ``CachedSource`` is named by its own + label and the id of the source it wraps. Never raises: a source whose label cannot + be read is shown as one without a label. + + Args: + stream: The source, or any stream bound to a slot. + """ + try: + return _labelled_source(stream) + except Exception: # noqa: BLE001 # a display never changes an outcome + return None + + +def _labelled_source(stream: Any) -> LabelledSource | None: + from orcapod.core.sources.base import RootSource + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_ids import build_source_id + from orcapod.core.sources.source_proxy import SourceProxy + + if not _is_a(stream, RootSource) or _is_a(stream, SourceProxy): + return None + label = _one_line(_stored_text(stream, "_label")) + if not label: + return None + source: Any = stream + while type(source) is CachedSource: + source = _stored(source).get("_source") + # A cache accepts any source-like object; only a root source holds a name to show. + if not _is_a(source, RootSource) or _is_a(source, SourceProxy): + return None + name = _stored_text(source, "_source_name") + if not name: + return None + source_id = build_source_id( + _class_value(source, "SOURCE_KIND"), + _class_value(source, "SOURCE_VERSION"), + name, + ) + declared = _class_value(source, "DISPLAY_PARTS") + # Only a plain tuple of two plain names is used, so reading it runs no code. + if ( + type(declared) is not tuple + or len(declared) != 2 + or not all(type(part) is str for part in declared) + ): + declared = ("", "") + near, far = declared + dataset, project = _stored_text(source, near), _stored_text(source, far) + both = f"{project}.{dataset}" if dataset and project else "" + parts = (dataset, project, both, name, source_id) + return LabelledSource(label, source_id, tuple(_one_line(p) for p in parts)) + + +def display_names( + sources: Mapping[str, LabelledSource], names: Collection[str] +) -> dict[str, str]: + """Return the text each labelled source is shown by: its label when that is enough. + + Sources sharing a label, and a source whose label is another shown name, are shown + as ``label (part)`` with the shortest part that tells all of them apart. A source no + part tells apart keeps its own name, so no two texts are ever equal. The order of + the sources changes nothing. + + Args: + sources: The labelled sources, by the name each is shown by without a label. + names: Every name the display shows (the nodes' labels), these included. + + Returns: + The text, by the same keys as ``sources``. + """ + groups: dict[str, list[str]] = {} + for name, source in sources.items(): + groups.setdefault(source.label, []).append(name) + texts: dict[str, str] = {} + for label, members in groups.items(): + taken = set(names) - set(members) + if len(members) == 1 and label not in taken: + texts[members[0]] = label + continue + taken.update(groups) + for level in zip(*(sources[m].parts for m in members), strict=True): + shown = [f"{label} ({part})" for part in level] + if all(level) and len(set(shown)) == len(shown) and not taken & set(shown): + texts.update(zip(members, shown)) + break + else: + texts.update({m: f"{label} ({m})" for m in members}) + used = list(texts.values()) + return { + n: t if used.count(t) == 1 and t not in set(names) - {n} else n + for n, t in texts.items() + } + + +def node_display_names(nodes: Iterable[Any]) -> dict[str, tuple[str, str]]: + """Return the text and full source id of each source node shown by its source's label. + + Args: + nodes: The nodes of one pipeline or job. + + Returns: + ``(text, source id)`` by node label, for the nodes whose bound source has an + assigned label; a node given a label of its own, an unbound slot and every other + node is not listed (it is shown by its own label). + """ + all_nodes = list(nodes) + found: dict[str, LabelledSource] = {} + for node in all_nodes: + if node.node_type != "source" or node.has_assigned_label: + continue + source = labelled_source(getattr(node, "bound_source", None)) + if source is not None: + found[node.label] = source + texts = display_names(found, {node.label for node in all_nodes}) + return {name: (text, found[name].source_id) for name, text in texts.items()} diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 5dd3d41a1..6312a677f 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -291,6 +291,8 @@ class SpiralDBTableSource(RootSource): """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" + + DISPLAY_PARTS: ClassVar[tuple[str, str]] = ("_dataset", "_project_id") TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 768c698a6..bd72e28fe 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -27,7 +27,7 @@ from collections.abc import Iterator, Mapping from contextlib import contextmanager from copy import copy -from threading import RLock +from threading import local from typing import TYPE_CHECKING, Any, cast import pyarrow as pa @@ -75,7 +75,7 @@ ) # Tables a warning was issued for in this process (``UnrecordedTableSchemaWarning``). _warned_unrecorded: set[tuple[str, str]] = set() -_warned_lock = RLock() # a warning hook may read a table itself +_warning_here = local() # ``keys``: what this thread is warning about right now # --------------------------------------------------------------------------- @@ -187,23 +187,33 @@ def _warn_unrecorded(table: str, table_id: str) -> None: def _warn_once(about: tuple[str, str], message: str) -> None: - """Issue an ``UnrecordedTableSchemaWarning`` once per ``about`` and process. + """Issue an ``UnrecordedTableSchemaWarning``, usually once per ``about`` and process. + + Once it has been shown it is not shown again. Threads reading one table at the same + time may each show it: no lock is held while warning, since a warning hook may wait + for another thread that reads an unrecorded table. A warning turned into an error is + not recorded as shown, so every reader raises it. A hook that reads the table itself + is not warned again about it. Args: about: What the warning is about. message: The warning. """ - # Held over the check, the warning and the record: while one thread's warning is - # turned into an error, another does not pass as if it had been shown. - with _warned_lock: - if about in _warned_unrecorded: - return + warning_now: set[tuple[str, str]] | None = getattr(_warning_here, "keys", None) + if warning_now is None: + warning_now = _warning_here.keys = set() + if about in _warned_unrecorded or about in warning_now: + return + warning_now.add(about) + try: warnings.warn( message, UnrecordedTableSchemaWarning, stacklevel=outside_orcapod_stacklevel(), ) - _warned_unrecorded.add(about) + finally: + warning_now.discard(about) + _warned_unrecorded.add(about) # --------------------------------------------------------------------------- diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a12be0ae7..7720e7980 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -619,7 +619,8 @@ class UnrecordedTableSchemaWarning(UserWarning): nullable, with no Arrow metadata. A table written by an Orcapod release on pyspiral reads this way until its dataset is migrated (``scripts/migrate_spiral_schemas.py``), so its schema and its hashes differ from - what they were. Issued once per table and process. + what they were. Usually issued once per table and process: threads reading the + table at the same time may each issue it. """ diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index 08525ecc9..613955179 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -39,6 +39,7 @@ from typing_extensions import override +from orcapod.core.sources.display_names import node_display_names from orcapod.types.provenance import Highlight from orcapod.utils.in_development import warn_in_development @@ -86,6 +87,13 @@ class _Node: highlighted: bool = False mark: str = "" asked: str = "" + shown: str = "" + + @property + def text(self) -> str: + """The name drawn: the bound source's assigned label (``shown``), else the + node's label.""" + return self.shown or self.label @property def kind_line(self) -> str: @@ -369,11 +377,15 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: by_label[label], (statuses[upstream] for upstream in preds[label]) ) + source_names = node_display_names(by_label.values()) nodes: list[_Node] = [] for label in shown: node = by_label[label] summary = summaries.get(label) facts = _run_facts(summary) if is_job else () + source_text, source_id = source_names.get(label, ("", "")) + if source_id: + facts = (("source id", source_id), *facts) try: tag_schema, data_schema = node.output_schema() except ValueError as error: @@ -396,6 +408,7 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: # A highlight shows the provenance question only: no run status. status="" if highlight is not None else statuses.get(label, ""), facts=facts, + shown=source_text, highlighted=highlight is not None and label in highlight.nodes, mark="" if highlight is None else highlight.mark(label), asked=highlight.asked_text or "asked here" @@ -486,7 +499,7 @@ def _text_room(node: _Node) -> float: kind, the detail, the status), within the node width limits (ITL-1232).""" parts = [*node.kind_line.split(" · "), node.mark, node.asked] text = max( - len(node.label) * _CHAR_W, max(len(part) for part in parts) * _SMALL_CHAR_W + len(node.text) * _CHAR_W, max(len(part) for part in parts) * _SMALL_CHAR_W ) return max(_MIN_W - 2 * _PAD, min(_MAX_W - 2 * _PAD, text)) @@ -834,7 +847,7 @@ def _schema_text(pairs: Sequence[tuple[str, str]]) -> str: def _tooltip(node: _Node, inputs: Sequence[str]) -> str: """The node's details as plain text, shown on hover over the inline picture.""" - lines = [f"{node.label} ({node.kind_line})"] + lines = [f"{node.text} ({node.kind_line})"] lines.append(f"tags: {_schema_text(node.tag_schema)}") lines.append(f"data: {_schema_text(node.data_schema)}") if inputs: @@ -901,7 +914,7 @@ def _svg( f'stroke-opacity="{"0.3" if lit else "0.5"}" stroke-width="1.4">' ) for edge, points in layout.edges: - tip = f"{nodes[edge.source].label} → {nodes[edge.target].label}" + tip = f"{nodes[edge.source].text} → {nodes[edge.target].text}" if edge.folded: tip += f" (through {', '.join(edge.folded)})" dash = ' stroke-dasharray="5 3"' if edge.folded else "" @@ -932,7 +945,7 @@ def _svg( ) stroke_width = "1.4" if node.kind == "operator" else "2.2" dash = ' stroke-dasharray="4 3"' if node.status in _DASHED_STATUSES else "" - label = f"{node.label}, {node.kind_line}" + label = f"{node.text}, {node.kind_line}" emphasis = "" stroke = colour if node.highlighted: @@ -990,7 +1003,7 @@ def _svg( parts.append( f'' - f"{_escape(_clip(node.label, w, _CHAR_W))}" + f"{_escape(_clip(node.text, w, _CHAR_W))}" ) parts.append("" if caption else "") return "".join(parts) @@ -1000,7 +1013,7 @@ def _table(nodes: Sequence[_Node], inputs: Mapping[int, Sequence[str]]) -> str: """Every node with its inputs, schema and run facts: shown where scripts do not run.""" rows = "".join( "
{_escape(node.label)}{_escape(node.text)}{_escape(node.kind_line)}{_escape(', '.join(inputs.get(node.index, ())))}{_escape(_schema_text(node.tag_schema))}