diff --git a/.gitignore b/.gitignore index 0f91c5cb0..cb4a61fdc 100644 --- a/.gitignore +++ b/.gitignore @@ -216,6 +216,7 @@ docs/dev/* !docs/dev/notes !docs/dev/orcapod-design.md !docs/dev/security-exceptions.md +!docs/dev/documentation-style.md # General JSON files at project root /*.json diff --git a/README.md b/README.md index 9beb91fca..a774f33bf 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,10 @@ Orcapod to a uv project (start one with `uv init` in a new directory), and `uv r your code in that project's environment: ```bash -uv add "orcapod>=0.4.0rc4" +uv add "orcapod>=0.4.0rc7" ``` -In an environment not managed by uv, use `pip install "orcapod>=0.4.0rc4"` instead. For the +In an environment not managed by uv, use `pip install "orcapod>=0.4.0rc7"` instead. For the development version, install from the repository: `uv add git+https://github.com/metamorphic-labs/orcapod-python`. @@ -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 | @@ -99,9 +99,10 @@ session. - [Getting Started](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/getting-started.md): sources, streams and function pods, step by step. -- [Tutorial](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/tutorial/index.md): - a self-paced course in eleven short parts, from a first stream to a stored, re-runnable - pipeline over files, with exercises. +- [Tutorials](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/tutorial/index.md): + a self-paced core course in seven parts, from a first stream to a stored, re-runnable + pipeline, and short tutorials on files, inspecting results, tracing a value, chaining + pipelines and handling errors, with exercises. - [Concepts](https://github.com/metamorphic-labs/orcapod-python/tree/main/docs/concepts): sources, streams, function pods, operators, pipelines and jobs, identity and hashing, file types, arrays and your own data types. 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/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/changelog.d/ITL-1455.md b/changelog.d/ITL-1455.md new file mode 100644 index 000000000..0d7dff6de --- /dev/null +++ b/changelog.d/ITL-1455.md @@ -0,0 +1,3 @@ +### Changed + +- **The pipeline diagram draws an input that only constrains apart.** The right input of a `SemiJoin` decides which rows of the left input pass and passes none on: the diagram draws it as a dashed edge entering the box from the side, its details say which tags the rows match on, and the text form says `<- a; constrained by b`. Folding (`collapse=True`) keeps it. An operator declares such inputs in `CONSTRAINING_INPUTS`. Display only: no hash, id, stored path, node label or saved file changes, and a diagram without such an input is drawn as before. (ITL-1455) diff --git a/changelog.d/ITL-1459.md b/changelog.d/ITL-1459.md new file mode 100644 index 000000000..b463e937d --- /dev/null +++ b/changelog.d/ITL-1459.md @@ -0,0 +1,5 @@ +### Changed + +- Getting Started and the tutorial are shorter and in plainer language, loop over a stream with + `for tag, data in stream`, and install at least 0.4.0rc7. Part 6 is titled "Re-runs" and + Part 9 "Handling errors". (ITL-1459) diff --git a/changelog.d/ITL-1460.md b/changelog.d/ITL-1460.md new file mode 100644 index 000000000..4430c0602 --- /dev/null +++ b/changelog.d/ITL-1460.md @@ -0,0 +1,9 @@ +### Changed + +- The tutorial section is "Tutorials": a core course (Parts 0 to 6) and short tutorials that + each cover one subject and can be read in any order afterwards. Part 8 is split into + "Inspecting results", "Tracing a value" and "Chaining pipelines"; Parts 7, 9 and 10 are + "Working with files", "Handling errors" and "Where next". Their pages have new addresses + (`docs/tutorial/files.md`, `inspecting-results.md`, `tracing-a-value.md`, + `chaining-pipelines.md`, `handling-errors.md`, `where-next.md`). The pages list a job's + steps with `print(job.diagram())`. (ITL-1460) diff --git a/changelog.d/ITL-1470.md b/changelog.d/ITL-1470.md new file mode 100644 index 000000000..893a88f7b --- /dev/null +++ b/changelog.d/ITL-1470.md @@ -0,0 +1,9 @@ +### Fixed + +- A chain of operators built before a job is opened, with a step over it added inside the + `with` block, gives the same nodes, system-tag column names, pipeline hashes and stored + tables as the same chain built inside the block (ITL-1470). The stream used to become a + source slot, which named its system-tag columns by its own schema and had its own + pipeline hash, while its content hash was that of the chain. The change that fixes it is + ITL-1387 (a stream given to a job brings its upstream steps); this entry adds the test + that compares the two forms, on the sync and the async path. 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/file-types.md b/docs/concepts/file-types.md index 7b435d582..73de2c2f3 100644 --- a/docs/concepts/file-types.md +++ b/docs/concepts/file-types.md @@ -4,7 +4,7 @@ Pipelines over scientific data pass references to files between steps. Orcapod h for this, and the choice of type decides **what a result's validity depends on**: the content of the file, or only its location. -For a guided introduction see the tutorial, [Part 7](../tutorial/07-files.md). +For a guided introduction see the tutorial [Working with files](../tutorial/files.md). ## The types diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index 010af6748..4a8f4e9c1 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -170,7 +170,7 @@ One row per function node: `rows` is every input row the run accounted for in th how many its function computed in this run, `from store` how many it read back from the database instead, `failed` how many raised, and `first error` the first of those errors, with the call that prints its full traceback (`job.last_run.print_traceback("rates")`). Here one `rates` row -was found in the store during the run itself ([Part 5](../tutorial/05-pipeline-job.md#record-then-run) +was found in the store during the run itself ([Part 5](../tutorial/05-pipeline-job.md#run-a-recorded-job) of the tutorial explains why). A load-only run (`job.run(load_only=True)`) shows how many rows each node loaded and how many had no stored result instead. The job keeps the summary as `job.last_run`. A cell that ends with `job.run();` (a semicolon) shows nothing. What a run @@ -218,7 +218,7 @@ print(job.nodes["rates"].run().header()) A view holds the default columns only (tags and data). For system tags, source info and the other hidden columns, ask the node: `as_table(columns=...)`, as in -[Part 8 of the tutorial](../tutorial/08-inspecting-and-tracing.md). `run()` on each kind of +the tutorial [Inspecting results](../tutorial/inspecting-results.md#tracing-rows). `run()` on each kind of object is the table "What `run()` does on each kind of object" in [Streams](streams.md#computing-a-stream-outside-a-job-run). @@ -256,6 +256,8 @@ laid out left to right. Here is `job` as the last line of a cell, after its run, - **A node's details.** Click a node (or focus it and press Enter) to see its schema: its tag and data columns, the nodes it reads from and, for a job, its run status and the row counts of the job's last run. +- **Constraining inputs.** The right input of a `SemiJoin` only decides which rows pass: a + dashed edge entering from the side of the box. - **Statuses.** Each node of a job shows one: `not run`, `current`, `stale`, `failed`, `loaded only`, `partial`, or `bound` or `unbound` for a source slot. Before `job.run()` every node but the sources says `not run`. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 47db51b8c..dd1bb370c 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -59,8 +59,8 @@ The three stages: and failed; see [Reading the run summary](function-pods.md#reading-the-run-summary). -Among `job.run()`'s optional arguments, the tutorial's -[Part 9](../tutorial/09-when-things-go-wrong.md) demonstrates `orchestrator=` (for example +Among `job.run()`'s optional arguments, the tutorial +[Handling errors](../tutorial/handling-errors.md) demonstrates `orchestrator=` (for example `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, `LoggingObserver`) to record what happened during the run. An observer only watches: one @@ -278,11 +278,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 @@ -290,9 +288,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 @@ -473,6 +471,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. @@ -489,6 +498,13 @@ shown first, and the one shown where scripts do not run. A selected node stays s when it is in the new layout. The checkboxes appear for graphs of up to 100 nodes: a larger diagram carries only the layout its arguments ask for, which keeps a notebook small. +An input that only decides which rows of another input pass (the right input of a +`SemiJoin`) is drawn as a dashed edge that enters the box from the side (from above or below +when the graph runs left to right); the data input enters as every other edge does. The node's +details give the tags the rows match on, and the text form lists such an input after the +others: `<- spikes; constrained by units`. `collapse=True` never hides it: folded steps on its +way are drawn dash-dotted. + In each node, the kind line under the name (kind, what it is, status) is wrapped onto short lines, so a node is about as wide as its name. diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 36c0d1878..8bc650427 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -192,7 +192,7 @@ The result is an `Absence`. Its fields hold: - `removed_by`: the step that removed it, a `Step`; - `because`: the reason, in words. -Tutorial [Part 8](../tutorial/08-inspecting-and-tracing.md) shows a row removed by a filter +The tutorial [Tracing a value](../tutorial/tracing-a-value.md#missing-rows) shows a row removed by a filter and one removed by a join. ## On the diagram @@ -247,7 +247,7 @@ print(warm.highlight().marks == trace.highlight().marks) ``` In a notebook the diagram is drawn as a picture, the mark as a bold line on its node. Here -is the job of tutorial [Part 8](../tutorial/08-inspecting-and-tracing.md), first plain, +is the job of the tutorial [Tracing a value](../tutorial/tracing-a-value.md), first plain, then with the trace of one firing rate highlighted. Its path stops at `rates`: the grouping after it is dimmed. That rate reused the result an equal input had computed, so `rates` is marked `reused`: diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index de40e30a3..f7a69e383 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,44 @@ 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, 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 + 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` @@ -918,7 +871,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/documentation-style.md b/docs/dev/documentation-style.md new file mode 100644 index 000000000..3b6d71abc --- /dev/null +++ b/docs/dev/documentation-style.md @@ -0,0 +1,67 @@ +# Documentation style + +How to write the published documentation, the tutorial above all (ITL-1459). CLAUDE.md, +"Documentation samples" and "Documentation site", has the mechanics. + +## Sentences + +Write short declarative sentences that say what happens or what to do. Cut any sentence that +announces, justifies or repeats another one. + +| Avoid | Before | After | +|---|---|---| +| Announcing what comes next | "Now the surprise. Suppose you edit the function:" | "Suppose you edit the function:" | +| Answering a doubt nobody raised | "63 times for 64 units. That is not a mistake: two units have the same inputs." | "63 times for 64 units, because two units have the same inputs." | +| Denying one thing to state another | "identified by the path, not the content" | "identified by the path" | +| "Always" and "never" that change nothing for the reader | "Refer to columns by name, never by position." | "Refer to columns by name." | +| A colon that only delays the sentence | "The habit that makes these quick to fix: print `keys()`." | "Print `keys()`." | +| An aside after a dash | "The schema is unchanged -- pods never modify tags." | "The schema is unchanged: a pod passes tags through." | +| Selling a feature | "Notice that this is why tags matter: you never wrote the lookup." | (cut) | +| Talking about the page | "These samples only serve to produce the clash." | (cut) | +| Emphasis by contrast | "It finishes. It is not finished successfully." | "A job can finish with failed rows." | + +A negative sentence is right when the reader would otherwise act wrongly: "A change after the +dot is **not** enough." + +## Headings + +- Name the subject: "Nodes", "Reuse rule", "Versioning a pod". A heading does not carry the + conclusion ("An edited function: nothing is recomputed"), ask a question, or say that one + thing is another ("A source is a stream"). +- A changed heading changes its anchor. Find every link to it with + `grep -rn '.md#' docs README.md`; the site build checks them. + +## Facts + +- State a fact once, on the page and at the place where the reader needs it. Elsewhere, link to + it. A message that every page can show (`ProvisionalHashWarning`) is explained in Setup only. +- Do not introduce what the page does not use. Link to the concept page instead. +- Check each sentence against the code, or run it. Show the output the library prints. +- Cutting words must not cut a trap. These stay wherever they apply: an edited function returns + its old values; comparisons in a filter need parentheses, and `and` drops a condition without + an error; a node reads empty before `run()`; a finished job can have failed rows; a stored + path outlives a deleted file. +- Show a number only when the reader can compare it with something. + +## Examples + +- Orcapod is general. Describe a feature in general terms, and use the workshop data as the + example. +- An example or exercise gives the domain facts it needs: "Unit numbers restart at 0 on every + probe." A reader must not have to know the field to answer. +- Code and text use the names of the columns they produce: `return temp_fahrenheit` for + `output_keys=["temp_fahrenheit"]`. +- Iterate with `for tag, data in stream`. +- The install lines name a release candidate that has every feature the pages use. + +## Tutorial pages + +- A part opens with what it adds, then a "You will" list. +- "Key points" ends the text, before the exercises. It repeats what the part taught and adds + nothing: no new term, link or feature, and no preview of the next part. +- No "Next: ..." line. The site has its own next-page link. +- The section is a core course (Parts 0 to 6, read in order) and short tutorials on one subject + each (ITL-1460). A short tutorial has no part number, says which core parts it needs in a + "**Before you start:**" line after its opening, and runs on its own from `make_dataset()`. +- List a job's steps with `print(job.diagram())`; do not write a helper that walks + `node.upstreams`. diff --git a/docs/dev/plans/itl-1470-stream-built-before-a-job.md b/docs/dev/plans/itl-1470-stream-built-before-a-job.md new file mode 100644 index 000000000..a8dc67727 --- /dev/null +++ b/docs/dev/plans/itl-1470-stream-built-before-a-job.md @@ -0,0 +1,107 @@ +# ITL-1470: a stream built before a job gets other system-tag column names + +## What was reproduced + +On `main` at 5eb327ad. `units` is a `DictSource` with tags `s`, `u` and data `x`, `y` +(`source_id="units"`); `add` is a function pod over `x`, `y`. + +| Chain before the pod | Built | Job nodes | System-tag columns of `add` | Content hash | Pipeline hash | +|---|---|---|---|---|---| +| `select_tag_columns(["s"])` | before the job | `SelectTagColumns:`, `add` | `...::5c54...` | `0050...` | `bc73...` | +| `select_tag_columns(["s"])` | inside the job | `SelectTagColumns`, `add`, `units` | `...::567d...` | `0050...` | `0c0f...` | +| `map_tags({"s": "site"})` | before | `MapTags:`, `add` | `...::ea17...` | `99c6...` | `db3d...` | +| `map_tags({"s": "site"})` | inside | `MapTags`, `add`, `units` | `...::567d...` | `99c6...` | `64c0...` | +| select then map | before | `MapTags:`, `add` | `...::b99c...` | `4c36...` | `d4fc...` | +| select then map | inside | `MapTags`, `SelectTagColumns`, `add`, `units` | `...::567d...` | `4c36...` | `6747...` | +| `join` with a second source | before | refused (`SourceSpecMismatchError`, ITL-1126) | | | | +| `join` with a second source | inside | `Join`, `SelectDataColumns`, `add`, both sources | two pairs | `2464...` | `4463...` | +| none (the source itself) | before or inside | `add`, `units` | `...::567d...` | `8f5e...` | `7817...` | + +The plain stream outside any job always equals the "inside" row. + +The content hash is equal in both forms, the pipeline hash is not. So the two forms write +their pipeline table at two paths (`.../schema:/pdb_v1`), each with its own +column names; they share the result table (same path), which holds no system-tag column. +No single table gets two sets of column names, but one node identity (content hash) has two +pipeline tables with different column names. + +## Cause + +`Pipeline.compile` makes every stream that has no recorded producer in the job a leaf: +`SourceJobNode.from_stream(stream)`. A stream built before the `with` block has a producer +(the select), but that step was not recorded, so the stream itself becomes a source slot +named `
"``. """ 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,336 @@ 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``, usually once per ``about`` and process. - The connector's metadata record (``_serialize_field_meta_tree``) does not descend - into a map, so such metadata would read back dropped (ITL-1334). + 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: - arrow_type: The column's Arrow type. + about: What the warning is about. + message: The warning. + """ + 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(), + ) + finally: + warning_now.discard(about) + _warned_unrecorded.add(about) - Returns: - ``True`` for such a map at any depth of lists, structs and maps. + +# --------------------------------------------------------------------------- +# 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: + pid: The process that made the client. + + 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 +471,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 +636,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 +711,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 +790,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 +831,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 +870,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 +881,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 +897,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 +912,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 +947,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 +958,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 +977,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 +992,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 +1037,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..7720e7980 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,45 @@ 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. Usually issued once per table and process: threads reading the + table at the same time may each issue it. + """ 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 +654,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/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index 08525ecc9..28b73c2c7 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 class_dicts, node_display_names from orcapod.types.provenance import Highlight from orcapod.utils.in_development import warn_in_development @@ -86,6 +87,14 @@ class _Node: highlighted: bool = False mark: str = "" asked: str = "" + shown: str = "" + keeps: tuple[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: @@ -102,6 +111,13 @@ class _Edge: target: int folded: tuple[str, ...] = () highlighted: bool = False + # The stream only decides which rows of the target's other inputs pass (ITL-1455). + constrains: bool = False + + @property + def key(self) -> tuple[int, int, bool]: + """What tells the edge apart: one stream can be both kinds of input.""" + return (self.source, self.target, self.constrains) # --------------------------------------------------------------------------- @@ -187,6 +203,73 @@ def _collapsible(node: Any) -> bool: ) +def _upstream_labels(node: Any, label_of: Mapping[int, str]) -> list[str | None]: + """The label of each of an operator node's inputs, in argument order. + + Args: + node: The node. + label_of: The label of each node of the graph, by the node's ``id()``. + + Returns: + One label per input; ``None`` for an input that is not a node of the graph. + """ + return [label_of.get(id(stream)) for stream in node.upstreams] + + +def _declared(producer: Any, name: str) -> Any: + """What an operator's class declares, read without running any code of the class. + + Args: + producer: The operator, or ``None``. + name: The class attribute. + + Returns: + The value the class or its nearest base holds, as stored; ``None`` for none. + """ + for namespace in class_dicts(type(producer)): + if name in namespace: + return namespace[name] + return None + + +def _input_roles( + node: Any, upstream_labels: Sequence[str], label_of: Mapping[int, str] +) -> list[tuple[str, bool]]: + """A node's inputs, each with whether it only constrains the others (ITL-1455). + + Which input positions constrain is declared by the operator's class + (``CONSTRAINING_INPUTS``). A stream that is both kinds of input is listed twice. + + Args: + node: The node. + upstream_labels: The labels of the nodes it reads from, in drawing order. + label_of: The label of each node of the graph, by the node's ``id()``. + + Returns: + The label and role of each input, in the order of ``upstream_labels``. + """ + plain = [(label, False) for label in upstream_labels] + if node.node_type != "operator": + return plain + producer = getattr(node, "producer", None) + positions = _declared(producer, "CONSTRAINING_INPUTS") + if type(positions) is not tuple or not positions: + return plain + ordered = _upstream_labels(node, label_of) + if not all(type(i) is int and 0 <= i < len(ordered) for i in positions): + return plain + if set(ordered) != set(upstream_labels): + # An input is missing (a loaded graph that lost a node): positions say nothing. + return plain + roles = {(label, i in positions) for i, label in enumerate(ordered)} + return [ + (label, constrains) + for label in upstream_labels + for constrains in (False, True) + if (label, constrains) in roles + ] + + def _run_facts(summary: NodeRunSummary | None) -> tuple[tuple[str, str], ...]: """What the job's last run did with a node's rows, from its ``NodeRunSummary``.""" if summary is None: @@ -251,6 +334,37 @@ def _failed_rows(node: Any) -> int: return _last_run_failed(node) if isinstance(node, FunctionJobNode) else 0 +def _constraint_fact( + node: Any, label_of: Mapping[int, str], by_label: Mapping[str, Any] +) -> tuple[str, str] | None: + """What a node's constraining inputs do, from its inputs' predicted tag columns. + + Args: + node: An operator node with a constraining input. + label_of: The label of each node of the graph, by the node's ``id()``. + by_label: The nodes, by label. + + Returns: + The tags the rows match on, or ``None`` when the operator does not declare that + it matches on the shared tags, or the columns are not available (a loaded node + whose saved types cannot be restored). + """ + if _declared(node.producer, "CONSTRAINT_MATCHES_SHARED_TAGS") is not True: + return None + try: + tag_keys = [ + tuple(by_label[label].output_schema()[0]) + for label in _upstream_labels(node, label_of) + if label is not None + ] + except ValueError: + return None + shared = set(tag_keys[0]).intersection(*tag_keys[1:]) + if not shared: + return ("keeps every row", "the inputs share no tag column") + return ("keeps the rows that match on", ", ".join(sorted(shared))) + + def _topological_labels( preds: Mapping[str, Sequence[str]], succs: Mapping[str, Sequence[str]] ) -> list[str]: @@ -317,12 +431,22 @@ def _build_model( for names in (*preds.values(), *succs.values()): names.sort() + label_of = {id(node): label for label, node in by_label.items()} + roles = { + label: _input_roles(node, preds[label], label_of) + for label, node in by_label.items() + } + folded: set[str] = set() if collapse: + # A step with a constraining input is never folded: the constraint would be + # drawn as data. folded = { label for label, node in by_label.items() - if _collapsible(node) and len(succs[label]) == 1 + if _collapsible(node) + and len(succs[label]) == 1 + and not any(constrains for _, constrains in roles[label]) } if highlight is not None: # The node the question was asked at is always shown, and so is a @@ -351,12 +475,15 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: found.extend(ends(upstream, (label, *via))) return found - edges: dict[tuple[int, int], tuple[str, ...]] = {} + edges: dict[tuple[int, int, bool], tuple[str, ...]] = {} + direct: set[tuple[int, int, bool]] = set() folded_into: dict[str, list[str]] = {} for label in shown: - for upstream in preds[label]: + for upstream, constrains in roles[label]: for end, via in ends(upstream, ()): - key = (index[end], index[label]) + key = (index[end], index[label], constrains) + if not via: + direct.add(key) edges[key] = tuple(dict.fromkeys((*edges.get(key, ()), *via))) folded_into.setdefault(label, []).extend(via) @@ -369,11 +496,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: @@ -382,6 +513,11 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: # draws the graph and says why the columns are missing. tag_schema, data_schema = {}, {} facts = (*facts, ("schema", f"not available: {error}")) + keeps: tuple[str, str] | None = None + if any(constrains for _, constrains in roles[label]): + keeps = _constraint_fact(node, label_of, by_label) + if keeps is not None: + facts = (*facts, keeps) steps = list(dict.fromkeys(folded_into.get(label, []))) if steps: facts = (*facts, ("folded steps", ", ".join(steps))) @@ -396,6 +532,8 @@ 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, + keeps=keeps or (), 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" @@ -404,13 +542,13 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: ) ) - def lit(source: int, target: int, via: tuple[str, ...]) -> bool: + def lit(key: tuple[int, int, bool], via: tuple[str, ...]) -> bool: """Whether a displayed edge is emphasized: some highlighted path leads from its start to its end through the steps folded into it (several folded paths merge into one displayed edge, so their labels are not one chain).""" if highlight is None: return False - start, end = shown[source], shown[target] + start, end = shown[key[0]], shown[key[1]] if not via: return (start, end) in highlight.edges inner = set(via) @@ -420,7 +558,7 @@ def lit(source: int, target: int, via: tuple[str, ...]) -> bool: for upstream, downstream in highlight.edges: if upstream != current: continue - if downstream == end: + if downstream == end and (current != start or key in direct): return True if downstream in inner and downstream not in seen: seen.add(downstream) @@ -432,9 +570,10 @@ def lit(source: int, target: int, via: tuple[str, ...]) -> bool: source=source, target=target, folded=via, - highlighted=lit(source, target, via), + highlighted=lit((source, target, constrains), via), + constrains=constrains, ) - for (source, target), via in sorted(edges.items()) + for (source, target, constrains), via in sorted(edges.items()) ] return nodes, edge_list @@ -455,6 +594,9 @@ def lit(source: int, target: int, via: tuple[str, ...]) -> bool: _LAYER_GAP = 56.0 _NODE_GAP = 22.0 _DUMMY_GAP = 10.0 +# The free lane kept beside a box on the side where a constraining edge enters it. +_LANE = 20.0 +_LANE_TURN = 12.0 # how far before the box's middle the edge turns towards it _MARGIN = 12.0 _SWEEPS = 12 _PLACEMENT_ROUNDS = 8 @@ -486,7 +628,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)) @@ -577,7 +719,7 @@ def _layout( for node in nodes: width, height = _node_size(node) boxes[node.index] = _Box(node.index, layer[node.index], width, height) - chains: dict[tuple[int, int], list[int]] = {} + chains: dict[tuple[int, int, bool], list[int]] = {} links: dict[int, list[int]] = {} back: dict[int, list[int]] = {} dummy = -1 @@ -588,7 +730,7 @@ def _layout( chain.append(dummy) dummy -= 1 chain.append(edge.target) - chains[(edge.source, edge.target)] = chain + chains[edge.key] = chain for upper, lower in zip(chain, chain[1:]): links.setdefault(upper, []).append(lower) back.setdefault(lower, []).append(upper) @@ -628,13 +770,38 @@ def barycenter(item: tuple[int, _Box]) -> tuple[float, int]: best, best_count = [list(row) for row in layers], count layers = best + # The side of each box a constraining edge enters it from (-1.0 or 1.0): where its + # last point lies among the other inputs' in the layer before, so that it does not + # cross them; after them when it does not differ. The lane beside the box is kept + # free there. + sides: dict[int, float] = {} + if any(edge.constrains for edge in edges): + order = {box.key: j for row in layers for j, box in enumerate(row)} + arriving: dict[int, dict[bool, list[int]]] = {} + for edge in edges: + arriving.setdefault(edge.target, {False: [], True: []})[ + edge.constrains + ].append(order[chains[edge.key][-2]]) + for target, by_role in arriving.items(): + if by_role[True]: + data, limits = by_role[False], by_role[True] + before = bool(data) and sum(limits) / len(limits) < sum(data) / len( + data + ) + sides[target] = -1.0 if before else 1.0 + + def lane(box: _Box, side: float) -> float: + """The room kept free beside a box, on the given side.""" + return _LANE if sides.get(box.key) == side else 0.0 + def extent(box: _Box) -> float: return (box.height if across else box.width) if box.key >= 0 else 0.0 def separation(row: Sequence[_Box], j: int) -> float: both_nodes = row[j - 1].key >= 0 and row[j].key >= 0 gap = _NODE_GAP if both_nodes else _DUMMY_GAP - return (extent(row[j - 1]) + extent(row[j])) / 2 + gap + lanes = lane(row[j - 1], 1.0) + lane(row[j], -1.0) + return (extent(row[j - 1]) + extent(row[j])) / 2 + gap + lanes for row in layers: cursor = 0.0 @@ -669,10 +836,16 @@ def place(row: Sequence[_Box], wanted: Sequence[float]) -> None: wanted.append(sum(found) / len(found) if found else box.pos) place(layers[i], wanted) - lowest = min((box.pos - extent(box) / 2 for box in boxes.values()), default=0.0) + lowest = min( + (box.pos - extent(box) / 2 - lane(box, -1.0) for box in boxes.values()), + default=0.0, + ) for box in boxes.values(): box.pos -= lowest - breadth = max((box.pos + extent(box) / 2 for box in boxes.values()), default=0.0) + breadth = max( + (box.pos + extent(box) / 2 + lane(box, 1.0) for box in boxes.values()), + default=0.0, + ) depth = [ max( @@ -712,7 +885,7 @@ def node_end(key: int, leaving: bool) -> tuple[float, float]: routed: list[tuple[_Edge, list[tuple[float, float]]]] = [] for edge in edges: - chain = chains[(edge.source, edge.target)] + chain = chains[edge.key] points = [node_end(edge.source, leaving=True)] for key in chain[1:-1]: box = boxes[key] @@ -720,7 +893,17 @@ def node_end(key: int, leaving: bool) -> tuple[float, float]: points.extend( [point(start, box.pos), point(start + depth[box.layer], box.pos)] ) - points.append(node_end(edge.target, leaving=False)) + if edge.constrains: + # Down the lane beside the box, to the corner where it turns, then in. + box = boxes[edge.target] + side = sides[edge.target] + middle = starts[box.layer] + depth[box.layer] / 2 + edge_of_box = box.pos + side * extent(box) / 2 + points.append(point(starts[box.layer], edge_of_box + side * _LANE * 0.8)) + points.append(point(middle, edge_of_box + side * _LANE * 0.8)) + points.append(point(middle, edge_of_box)) + else: + points.append(node_end(edge.target, leaving=False)) routed.append((edge, points)) breadth_total = breadth + 2 * _MARGIN @@ -811,6 +994,34 @@ def _edge_path(points: Sequence[tuple[float, float]], across: bool) -> str: return " ".join(out) +def _side_path(points: Sequence[tuple[float, float]], across: bool) -> str: + """The path of a constraining edge: to the lane beside its box, along it, and in. + + Its last three points are the lane's start, the corner and the box's side. + """ + (cx, cy), (x, y) = points[-2:] + turn = (cx - _LANE_TURN, cy) if across else (cx, cy - _LANE_TURN) + return ( + f"{_edge_path(points[:-2], across)} L{_num(turn[0])},{_num(turn[1])} " + f"Q{_num(cx)},{_num(cy)} {_num(x)},{_num(y)}" + ) + + +def _side_arrow_head( + corner: tuple[float, float], end: tuple[float, float], across: bool +) -> str: + """A filled triangle pointing from ``corner`` to ``end``, its tip at ``end``.""" + x, y = end + half = _ARROW / 2 + if across: + back = y + (_ARROW if corner[1] > y else -_ARROW) + corners = [(x - half, back), (x, y), (x + half, back)] + else: + back = x + (_ARROW if corner[0] > x else -_ARROW) + corners = [(back, y - half), (x, y), (back, y + half)] + return "M" + " L".join(f"{_num(a)},{_num(b)}" for a, b in corners) + " Z" + + def _arrow_head(end: tuple[float, float], across: bool) -> str: """A filled triangle pointing along the layer axis, its tip at ``end``.""" x, y = end @@ -828,17 +1039,22 @@ def _clip(text: str, width: float, char_width: float) -> str: return text if len(text) <= room else text[: max(room - 1, 1)] + "…" +def _keeps(node: _Node) -> str: + """What the node's constraining inputs keep, or ``""``.""" + return ": ".join(node.keeps) + + def _schema_text(pairs: Sequence[tuple[str, str]]) -> str: return ", ".join(f"{name}: {tp}" for name, tp in pairs) or "none" -def _tooltip(node: _Node, inputs: Sequence[str]) -> str: +def _tooltip(node: _Node, inputs: 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: - lines.append(f"inputs: {', '.join(inputs)}") + lines.append(f"inputs: {inputs}") lines.extend(f"{name}: {text}" for name, text in node.facts) return "\n".join(lines) @@ -846,7 +1062,7 @@ def _tooltip(node: _Node, inputs: Sequence[str]) -> str: def _svg( title: str, nodes: Sequence[_Node], - inputs: Mapping[int, Sequence[str]], + inputs: Mapping[int, str], layout: _Layout, across: bool, standalone: bool, @@ -857,7 +1073,7 @@ def _svg( Args: title: The diagram's title, the picture's accessible name. nodes: The nodes. - inputs: The labels of each node's inputs, by node index. + inputs: Each node's inputs as text, by node index. layout: Where the nodes and edges are drawn. across: Whether the layers advance left to right. standalone: Draw it for an image of its own: on a light background, in a fixed @@ -901,10 +1117,23 @@ 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 "" + if edge.constrains: + tip += ": only decides which rows pass" + note = _keeps(nodes[edge.target]) + if note: + tip += f"\n{note}" + # Told from a folded data edge by the pattern too; folded, by both. + pattern = "8 3 2 3" if edge.folded else "3 3" + dash = f' class="op-dag-constraint" stroke-dasharray="{pattern}"' + path = _side_path(points, across) + head = _side_arrow_head(points[-2], points[-1], across) + else: + path = _edge_path(points, across) + head = _arrow_head(points[-1], across) accent = ( f' class="op-dag-highlight" stroke="{_HIGHLIGHT_COLOUR}" ' 'stroke-opacity="1" stroke-width="2.6"' @@ -915,8 +1144,8 @@ def _svg( parts.append( f'' f"{_escape(tip)}" - f'' - f'' + f'' ) parts.append('') @@ -932,7 +1161,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: @@ -946,7 +1175,7 @@ def _svg( f'' - f"{_escape(_tooltip(node, inputs.get(node.index, ())))}" + f"{_escape(_tooltip(node, inputs.get(node.index, '')))}" f'' @@ -990,19 +1219,19 @@ 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) -def _table(nodes: Sequence[_Node], inputs: Mapping[int, Sequence[str]]) -> str: +def _table(nodes: Sequence[_Node], inputs: Mapping[int, str]) -> str: """Every node with its inputs, schema and run facts: shown where scripts do not run.""" rows = "".join( "" - f"" + f"" f"" - f"" + f"" f"" f"" f"" @@ -1077,11 +1306,24 @@ def _asset(name: str) -> str: return _compact(text, css=name.endswith(".css")) -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.""" - inputs: dict[int, list[str]] = {} +def _inputs(nodes: Sequence[_Node], edges: Sequence[_Edge]) -> dict[int, str]: + """Each node's inputs as text, by node index: drawn names in edge order. + + The inputs that only constrain follow the others: ``a; constrained by b``. + """ + data: dict[int, list[str]] = {} + limits: dict[int, list[str]] = {} for edge in edges: - inputs.setdefault(edge.target, []).append(nodes[edge.source].label) + names = limits if edge.constrains else data + names.setdefault(edge.target, []).append(nodes[edge.source].text) + inputs: dict[int, str] = {} + for target in dict.fromkeys(edge.target for edge in edges): + parts: list[str] = [] + if target in data: + parts.append(", ".join(data[target])) + if target in limits: + parts.append(f"constrained by {', '.join(limits[target])}") + inputs[target] = "; ".join(parts) return inputs @@ -1228,8 +1470,8 @@ def title(self) -> str: """ return f"{self._kind.capitalize()} {self._name!r}" - def _inputs(self) -> dict[int, list[str]]: - """The labels of each node's inputs, in edge order.""" + def _inputs(self) -> dict[int, str]: + """Each node's inputs as text, by node index.""" return _inputs(self._nodes, self._edges) def to_dict(self) -> dict[str, Any]: @@ -1244,8 +1486,13 @@ 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 + (the labels of the steps folded into it), and ``constrains`` (``True``) when + the stream only decides which rows of the other inputs pass (``SemiJoin``'s + right input); a stream that is both kinds of input of a node has two edges. + With a highlight, every node and edge also has ``highlighted``, and the model has the highlight's ``note``. """ return self._model(self._nodes, self._edges) @@ -1282,11 +1529,19 @@ 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 ], "edges": [ - {"source": e.source, "target": e.target, "folded": list(e.folded)} + { + "source": e.source, + "target": e.target, + "folded": list(e.folded), + # Only where the stream constrains the other inputs (ITL-1455). + **({"constrains": True} if e.constrains else {}), + } for e in edges ], } @@ -1297,8 +1552,11 @@ def to_text(self) -> str: In development: this interface may change. Returns: - A title line, then ``
{_escape(node.label)}{_escape(node.text)}{_escape(node.kind_line)}{_escape(', '.join(inputs.get(node.index, ())))}{_escape(inputs.get(node.index, ''))}{_escape(_schema_text(node.tag_schema))}{_escape(_schema_text(node.data_schema))}{_escape('; '.join(f'{n}: {t}' for n, t in node.facts))}
"``. - - 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..f11fee4e5 --- /dev/null +++ b/tests/test_databases/test_spiraldb_reading.py @@ -0,0 +1,920 @@ +"""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_warnings_from_many_threads_stop_once_shown(project: Any) -> None: + """Racing readers may each show it; once shown, nobody shows it again.""" + barrier = threading.Barrier(8) + + def build(_: int) -> None: + barrier.wait(10) + SpiralDBConnector("p").get_arrow_schema("units") + + def shown(seen: list[warnings.WarningMessage]) -> int: + return len([w for w in seen if w.category is UnrecordedTableSchemaWarning]) + + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + with ThreadPoolExecutor(8) as pool: + list(pool.map(build, range(8))) + before = shown(seen) + assert 1 <= before <= 8 + with ThreadPoolExecutor(8) as pool: + list(pool.map(build, range(8))) + assert shown(seen) == before + + +def test_every_concurrent_reader_raises_with_the_warning_as_an_error( + project: Any, +) -> None: + barrier = threading.Barrier(8) + + def build(_: int) -> str: + barrier.wait(10) + try: + SpiralDBConnector("p").get_arrow_schema("units") + except UnrecordedTableSchemaWarning: + return "raised" + return "passed" + + with warnings.catch_warnings(): + warnings.simplefilter("error", UnrecordedTableSchemaWarning) + with ThreadPoolExecutor(8) as pool: + assert list(pool.map(build, range(8))) == ["raised"] * 8 + + +@pytest.mark.parametrize("table", ["units", "swapped"]) +def test_a_warning_hook_may_wait_for_a_reader_in_another_thread( + project: Any, monkeypatch: pytest.MonkeyPatch, table: str +) -> None: + """CodeRabbit on PR 550: no lock is held while warning.""" + finished: list[bool] = [] + readers: list[threading.Thread] = [] + + def hook(*given: Any, **options: Any) -> None: + if readers: + return + reader = threading.Thread( + target=lambda: SpiralDBConnector("p").get_arrow_schema(table), daemon=True + ) + readers.append(reader) + reader.start() + reader.join(5) + finished.append(not reader.is_alive()) + + with warnings.catch_warnings(): + warnings.simplefilter("always", UnrecordedTableSchemaWarning) + monkeypatch.setattr(warnings, "showwarning", hook) + SpiralDBConnector("p").get_arrow_schema("units") + assert finished == [True] + + +def test_a_warning_hook_may_read_the_table_itself( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + calls: list[int] = [] + + def hook(*given: Any, **options: Any) -> None: + calls.append(1) + SpiralDBConnector("p").get_arrow_schema("units") + + with warnings.catch_warnings(): + warnings.simplefilter("always", UnrecordedTableSchemaWarning) + monkeypatch.setattr(warnings, "showwarning", hook) + SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBConnector("p").get_arrow_schema("units") + assert calls == [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 "
" 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_docs/test_doc_samples.py b/tests/test_docs/test_doc_samples.py index 8f89d728e..e9925bdf0 100644 --- a/tests/test_docs/test_doc_samples.py +++ b/tests/test_docs/test_doc_samples.py @@ -267,10 +267,12 @@ def test_doc_pages_are_discovered(): "docs/tutorial/04-many-rows-into-one.md", "docs/tutorial/05-pipeline-job.md", "docs/tutorial/06-reruns-and-caching.md", - "docs/tutorial/07-files.md", - "docs/tutorial/08-inspecting-and-tracing.md", - "docs/tutorial/09-when-things-go-wrong.md", - "docs/tutorial/10-where-next.md", + "docs/tutorial/files.md", + "docs/tutorial/inspecting-results.md", + "docs/tutorial/tracing-a-value.md", + "docs/tutorial/chaining-pipelines.md", + "docs/tutorial/handling-errors.md", + "docs/tutorial/where-next.md", ): assert expected in DOC_PAGES diff --git a/tests/test_docs/test_provenance_diagrams.py b/tests/test_docs/test_provenance_diagrams.py index ab6150ea1..1c2feaa27 100644 --- a/tests/test_docs/test_provenance_diagrams.py +++ b/tests/test_docs/test_provenance_diagrams.py @@ -57,7 +57,7 @@ def test_a_picture_is_self_contained_and_on_its_own_background(name: str) -> Non @pytest.mark.parametrize( "page", - ["docs/tutorial/08-inspecting-and-tracing.md", "docs/concepts/provenance.md"], + ["docs/tutorial/tracing-a-value.md", "docs/concepts/provenance.md"], ) def test_the_pages_show_the_pictures(page: str) -> None: text = (REPOSITORY / page).read_text(encoding="utf-8") diff --git a/tests/test_docs/test_site_content.py b/tests/test_docs/test_site_content.py index 04f519435..a8fd281f6 100644 --- a/tests/test_docs/test_site_content.py +++ b/tests/test_docs/test_site_content.py @@ -171,7 +171,7 @@ def test_the_home_page_gets_the_hero(tmp_path: Path): "icon": "right-arrow", }, { - "text": "Tutorial", + "text": "Tutorials", "link": "/orcapod-python/tutorial/", "variant": "secondary", }, diff --git a/tests/test_pipeline/diagram_harness.js b/tests/test_pipeline/diagram_harness.js index b3d12f171..2dec84d8f 100644 --- a/tests/test_pipeline/diagram_harness.js +++ b/tests/test_pipeline/diagram_harness.js @@ -172,6 +172,7 @@ function observe() { .filter((g) => g.classList.contains('op-dag-selected')) .map((g) => g.getAttribute('aria-label').split(', ')[0]) : [], panel: root.querySelector('.op-dag-panel').classList.contains('op-dag-open'), + panelText: root.querySelector('.op-dag-panel').textContent, count: root.querySelector('.op-dag-count').textContent, controls: Object.fromEntries(['direction', 'collapse'] .filter((name) => root.querySelector('.op-dag-' + name)) diff --git a/tests/test_pipeline/test_diagram_constraints.py b/tests/test_pipeline/test_diagram_constraints.py new file mode 100644 index 000000000..afb3099f2 --- /dev/null +++ b/tests/test_pipeline/test_diagram_constraints.py @@ -0,0 +1,441 @@ +"""The diagram draws an input that only constrains the others apart (ITL-1455).""" + +from __future__ import annotations + +import re +import shutil +import warnings +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any, cast + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import SemiJoinIgnoredColumnWarning +from orcapod.operators import Join, MergeJoin, SemiJoin +from orcapod.pipeline import PipelineDiagram +from orcapod.pipeline.diagram import _Edge, _layout, _Node +from orcapod.sources import DictSource +from orcapod.types.provenance import Highlight + +from ..test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) +from .test_diagram import _run_view + +CALLS: list[str] = [] + + +@function_pod(output_keys="rate") +def rate(x: int) -> float: + """Return the value as a float.""" + CALLS.append("rate") + return float(x) + + +def _source(name: str, tags: list[str], *data: str) -> DictSource: + return DictSource( + [{**dict.fromkeys(tags, f"t{i}"), **dict.fromkeys(data, i)} for i in range(3)], + tag_columns=tags, + tag_only_columns=True, + source_id=name, + ) + + +def _job(*, reverse: bool = False) -> PipelineJob: + """Nested semi joins, recorded in either order of the sources.""" + job = PipelineJob(name="nested", database=InMemoryArrowDatabase()) + made = { + name: _source(name, tags, *data) + for name, tags, data in ( + ("spikes", ["session", "unit"], ("x",)), + ("units", ["unit", "session"], ("snr", "depth")), + ("approved", ["session"], ("note",)), + )[:: -1 if reverse else 1] + } + with job: + kept = made["units"].semi_join(made["approved"], label="kept_units") + chosen = kept.select_data_columns(["snr"]) + rate.pod(made["spikes"].semi_join(chosen, label="kept"), label="rates") + return job + + +def _edges(diagram: PipelineDiagram) -> set[tuple[str, str, bool, tuple[str, ...]]]: + model = diagram.to_dict() + label = [node["label"] for node in model["nodes"]] + return { + ( + label[e["source"]], + label[e["target"]], + e.get("constrains", False), + tuple(e["folded"]), + ) + for e in model["edges"] + } + + +def _facts(diagram: PipelineDiagram, label: str) -> dict[str, str]: + (node,) = [n for n in diagram.to_dict()["nodes"] if n["label"] == label] + return dict(node["facts"]) + + +def test_only_semi_join_declares_a_constraining_input() -> None: + assert SemiJoin.CONSTRAINING_INPUTS == (1,) + assert Join.CONSTRAINING_INPUTS == MergeJoin.CONSTRAINING_INPUTS == () + + +@pytest.mark.parametrize("blueprint", [False, True]) +def test_the_right_input_constrains_in_model_text_and_details(blueprint: bool) -> None: + job = _job() + diagram = (job.pipeline if blueprint else job).diagram() + assert _edges(diagram) == { + ("units", "kept_units", False, ()), + ("approved", "kept_units", True, ()), + ("kept_units", "SelectDataColumns", False, ()), + ("spikes", "kept", False, ()), + ("SelectDataColumns", "kept", True, ()), + ("kept", "rates", False, ()), + } + # The key is in the model only where it applies. + assert {e.get("constrains", True) for e in diagram.to_dict()["edges"]} == {True} + text = diagram.to_text() + assert "<- units; constrained by approved" in text + assert "<- spikes; constrained by SelectDataColumns" in text + assert _facts(diagram, "kept_units")["keeps the rows that match on"] == "session" + assert _facts(diagram, "kept")["keeps the rows that match on"] == "session, unit" + + +def test_folding_keeps_the_constraint() -> None: + diagram = _job().diagram(collapse=True) + assert ("kept_units", "kept", True, ("SelectDataColumns",)) in _edges(diagram) + assert "<- spikes; constrained by kept_units" in diagram.to_text() + assert 'stroke-dasharray="8 3 2 3"' in diagram.to_svg() + + +def test_a_folded_join_beneath_a_constraint_constrains_from_each_of_its_inputs() -> ( + None +): + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + limits = _source("b", ["k"], "y").join(_source("c", ["k"], "z")) + rate.pod(_source("a", ["k"], "x").semi_join(limits, label="s"), label="r") + edges = _edges(job.diagram(collapse=True)) + assert {e for e in edges if e[1] == "s"} == { + ("a", "s", False, ()), + ("b", "s", True, ("Join",)), + ("c", "s", True, ("Join",)), + } + + +class _ConstrainedJoin(Join): + CONSTRAINING_INPUTS = (1,) + + +def test_a_foldable_step_with_a_constraining_input_is_not_folded() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + joined = _ConstrainedJoin(label="limited")( + _source("a", ["k"], "x"), _source("b", ["k"], "y") + ) + rate.pod(joined.select_data_columns(["x"]), label="r") + edges = _edges(job.diagram(collapse=True)) + assert {e for e in edges if e[1] == "limited"} == { + ("a", "limited", False, ()), + ("b", "limited", True, ()), + } + + +class _Tuple(tuple[int, ...]): + pass + + +class _Int(int): + pass + + +class _Raises: + def __get__(self, *args: Any) -> Any: + raise RuntimeError("read through a hook") + + +def _custom_job(operator: type[Join]) -> PipelineJob: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + operator(label="limited")(_source("a", ["k"], "x"), _source("b", ["k"], "y")) + return job + + +@pytest.mark.parametrize( + "declared", + [1, None, "1", [1], {1}, frozenset({1}), (True,), (1.0,), ("1",), (2,), (-1,)] + + [(1, 2), (1, None), _Tuple((1,)), (_Int(1),), _Raises()], + # Not the repr, which can hold an address: every xdist worker must collect one name. + ids=lambda value: type(value).__name__, +) +def test_a_malformed_declaration_counts_as_none(declared: Any) -> None: + class Custom(Join): + CONSTRAINING_INPUTS = declared + + class Plain(Join): + pass + + Plain.__name__ = "Custom" + for collapse in (False, True): + drawn, plain = ( + _custom_job(operator).diagram(collapse=collapse) + for operator in (Custom, Plain) + ) + assert drawn.to_dict() == plain.to_dict() + assert drawn.to_text() == plain.to_text() + assert drawn.to_svg() == plain.to_svg() + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +@pytest.mark.parametrize("positions", [(1, 2), (2, 1), (0, 2), (2, 0), (0, 1)], ids=str) +def test_several_constraining_positions_in_any_order( + arrangement: Arrangement, positions: tuple[int, ...] +) -> None: + class Custom(Join): + CONSTRAINING_INPUTS = positions + CONSTRAINT_MATCHES_SHARED_TAGS = True + + partners = [ + make_source(spec, Arrangement(spec.tags, arrangement.layout, arrangement.roles)) + for spec in (P, Q) + ] + sources = [make_source(MAIN, arrangement), *partners] + names = [MAIN.source_id, P.source_id, Q.source_id] + shared = sorted(set(MAIN.tags) & set(P.tags) & set(Q.tags)) + # The positions are argument positions, in either order of the arguments. + for order in ((0, 1, 2), (2, 1, 0)): + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + Custom(label="limited")(*(sources[i] for i in order)) + diagram = job.diagram() + assert _edges(diagram) == { + (names[i], "limited", position in positions, ()) + for position, i in enumerate(order) + } + facts = _facts(diagram, "limited") + if shared: + assert facts["keeps the rows that match on"] == ", ".join(shared) + else: + assert "keeps every row" in facts + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_a_semi_join_s_keys_are_listed_whatever_the_arrangement( + arrangement: Arrangement, +) -> None: + other = make_source(P, Arrangement(P.tags, arrangement.layout, arrangement.roles)) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job, warnings.catch_warnings(): + warnings.simplefilter("ignore", SemiJoinIgnoredColumnWarning) + SemiJoin(label="limited")(make_source(MAIN, arrangement), other) + shared = ", ".join(sorted(set(MAIN.tags) & set(P.tags))) + assert _facts(job.diagram(), "limited")["keeps the rows that match on"] == shared + + +def test_drawing_calls_nothing_of_a_users_operator() -> None: + class Meta(type(Join)): + drawing = False + + def __getattribute__(cls, name: str) -> Any: + if name.startswith("CONSTRAIN") and Meta.drawing: + raise RuntimeError("metaclass hook ran") + return super().__getattribute__(name) + + class Custom(Join, metaclass=Meta): + CONSTRAINING_INPUTS = (1,) + CONSTRAINT_MATCHES_SHARED_TAGS = cast(Any, _Raises()) + + def __getattribute__(self, name: str) -> Any: + if name.startswith("CONSTRAIN"): + raise RuntimeError("instance hook ran") + return super().__getattribute__(name) + + def constraint_fact(self, tag_keys: Any) -> Any: + raise RuntimeError("user callback ran") + + job = _custom_job(Custom) + Meta.drawing = True + diagram = job.diagram() + assert "constrained by b" in diagram.to_text() + assert not any("keeps" in name for name in _facts(diagram, "limited")) + + +def test_a_users_operator_may_declare_that_it_matches_on_the_shared_tags() -> None: + class Custom(Join): + CONSTRAINING_INPUTS = (1,) + CONSTRAINT_MATCHES_SHARED_TAGS = True + + facts = _facts(_custom_job(Custom).diagram(), "limited") + assert facts["keeps the rows that match on"] == "k" + + +def test_one_stream_as_both_inputs_has_two_edges() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + a = _source("a", ["k"], "x") + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SemiJoinIgnoredColumnWarning) + rate.pod(a.semi_join(a, label="s"), label="r") + diagram = job.diagram() + assert {e for e in _edges(diagram) if e[1] == "s"} == { + ("a", "s", False, ()), + ("a", "s", True, ()), + } + assert "s (operator · SemiJoin · not run) <- a; constrained by a" in ( + diagram.to_text() + ) + + +def test_no_shared_tag_column_is_stated() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + s = _source("a", ["k"], "x").semi_join(_source("b", ["m"], "y"), label="s") + rate.pod(s, label="r") + facts = _facts(job.diagram(), "s") + assert facts["keeps every row"] == "the inputs share no tag column" + + +def test_a_diagram_without_a_constraint_has_no_new_key_or_drawing() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + joined = _source("a", ["k"], "x").join(_source("b", ["k"], "y")) + rate.pod(joined, label="r") + diagram = job.diagram() + assert all( + set(e) == {"source", "target", "folded"} for e in diagram.to_dict()["edges"] + ) + assert "constrain" not in diagram.to_svg() + diagram.to_text() + + +def test_making_the_diagram_calls_no_function_and_moves_no_identity() -> None: + job = _job() + before = {label: node.content_hash() for label, node in job.nodes.items()} + CALLS.clear() + for collapse in (False, True): + job.diagram(collapse=collapse).to_html() + assert CALLS == [] + assert {label: n.content_hash() for label, n in job.nodes.items()} == before + + +def test_a_loaded_job_keeps_the_roles(tmp_path: Any) -> None: + job = _job() + job.run() + path = tmp_path / "job.json" + job.save(str(path)) + loaded = PipelineJob.load(str(path)) + assert _edges(loaded.diagram()) == _edges(job.diagram()) + + +@pytest.mark.parametrize("direction", ["LR", "TB"]) +def test_the_drawing_does_not_depend_on_the_recording_order(direction: Any) -> None: + pictures = { + _job(reverse=reverse).diagram(direction=direction).to_svg() + for reverse in (False, True) + } + assert len(pictures) == 1 + + +def test_a_highlight_lights_a_constraining_edge_by_its_own_path() -> None: + highlight = Highlight( + nodes=frozenset({"approved", "kept_units"}), + edges=frozenset({("approved", "kept_units")}), + ) + svg = _job().diagram(highlight=highlight).to_svg() + lit = [g for g in _edge_groups(svg) if "op-dag-highlight" in g] + assert len(lit) == 1 and "op-dag-constraint" in lit[0] + + +def test_a_folded_constraint_is_not_lit_by_the_data_edge_beside_it() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + a = _source("a", ["k"], "x") + rate.pod(a.semi_join(a.map_data({"x": "z"}), label="s"), label="r") + highlight = Highlight(nodes=frozenset({"a", "s"}), edges=frozenset({("a", "s")})) + svg = job.diagram(collapse=True, highlight=highlight).to_svg() + lit = [g for g in _edge_groups(svg) if "op-dag-highlight" in g] + assert len(lit) == 1 and "op-dag-constraint" not in lit[0] + + +def _edge_groups(svg: str) -> list[str]: + return re.findall(r"", svg, re.DOTALL) + + +def test_the_edge_tooltip_says_what_is_kept_and_labels_are_escaped() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + b = rate.pod(_source("b", ["k"], "x"), label="" + "long" * 40) + rate.pod(_source("a", ["k"], "x").semi_join(b, label="s"), label="r") + root = ET.fromstring(job.diagram().to_svg()) + titles = [t.text or "" for t in root.iter("{http://www.w3.org/2000/svg}title")] + assert any( + t.startswith("long") + and t.endswith("only decides which rows pass\nkeeps the rows that match on: k") + for t in titles + ) + + +# --------------------------------------------------------------------------- +# The layout +# --------------------------------------------------------------------------- + + +def _node(index: int, label: str) -> _Node: + return _Node(index, label, "operator", "", (), (), "", ()) + + +@pytest.mark.parametrize("direction", ["LR", "TB"]) +def test_a_constraint_enters_from_the_side_and_crosses_no_box_of_its_layer( + direction: Any, +) -> None: + labels = ["a", "b" * 30, "c", "s" * 20, "t", "u"] + nodes = [_node(i, label) for i, label in enumerate(labels)] + for flags in range(2**6): + pairs = [(0, 3), (1, 3), (1, 4), (2, 4), (2, 5), (0, 5)] + edges = [ + _Edge(s, t, constrains=bool(flags >> n & 1)) + for n, (s, t) in enumerate(pairs) + ] + layout = _layout(nodes, sorted(edges, key=lambda e: e.key), direction) + for edge, points in layout.edges: + if not edge.constrains: + continue + x, y, w, h = layout.boxes[edge.target] + (cx, cy), (ex, ey) = points[-2:] + if direction == "TB": + assert ey == cy == pytest.approx(y + h / 2) + assert any(ex == pytest.approx(side) for side in (x, x + w)) + assert not x <= cx <= x + w + else: + assert ex == cx == pytest.approx(x + w / 2) + assert any(ey == pytest.approx(side) for side in (y, y + h)) + assert not y <= cy <= y + h + for px, py in points[-3:-1]: + assert 0 <= px <= layout.width and 0 <= py <= layout.height + for bx, by, bw, bh in layout.boxes.values(): + assert not (bx <= px <= bx + bw and by <= py <= by + bh) + + +@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is not on PATH") +def test_the_details_panel_lists_constraining_inputs_apart(tmp_path: Path) -> None: + (seen,) = _run_view( + _job().diagram().to_html(), + [ + {"op": "run", "width": 400}, + {"op": "select", "label": "kept"}, + {"op": "observe"}, + ], + tmp_path, + ) + assert "inputsspikesconstrained bySelectDataColumns" in seen["panelText"] + assert "keeps the rows that match onsession, unit" in seen["panelText"] 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/tests/test_pipeline/test_source_display_names.py b/tests/test_pipeline/test_source_display_names.py new file mode 100644 index 000000000..9270673a8 --- /dev/null +++ b/tests/test_pipeline/test_source_display_names.py @@ -0,0 +1,499 @@ +"""A pipeline shows a source by its assigned label, display only (ITL-1454).""" + +from __future__ import annotations + +import asyncio +import itertools +import warnings +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.sources.display_names import ( + LabelledSource, + display_names, + labelled_source, +) +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import RestrictedAggregationWarning +from orcapod.sources import DictSource, SpiralDBTableSource +from tests.test_databases import fake_spiral_sdk + + +@function_pod(output_keys="z") +def add(x: int, y: int) -> int: + """Return ``x + y``.""" + return x + y + + +def _left(label: str | None = "units", source_id: str = "left") -> DictSource: + return DictSource( + [{"g": i % 2, "k": i, "x": i, "x2": -i} for i in range(4)], + tag_columns=["g", "k"], + tag_only_columns=True, + source_id=source_id, + label=label, + ) + + +def _right(label: str | None = "scales", source_id: str = "right") -> DictSource: + return DictSource( + [{"k": i, "g": i % 2, "y": 10 * i, "y2": -i} for i in range(4)], + tag_columns=["k", "g"], + tag_only_columns=True, + source_id=source_id, + label=label, + ) + + +def _job( + left: Any, + right: Any, + pod_label: str = "sum", + database: Any = None, + swap: bool = False, +) -> PipelineJob: + job = PipelineJob(name="j", database=database or InMemoryArrowDatabase()) + with job: + first, second = (right, left) if swap else (left, right) + add.pod(first, second, label=pod_label) + return job + + +def _texts(job: PipelineJob) -> dict[str, str]: + nodes = job.diagram().to_dict()["nodes"] + return {n["label"]: n.get("text", n["label"]) for n in nodes} + + +def test_the_diagram_draws_the_label_and_gives_the_id_in_the_details() -> None: + job = _job(_left(), _right()) + diagram = job.diagram() + assert str(diagram).splitlines()[1:3] == [ + " units (source · DictSource · bound)", + " scales (source · DictSource · bound)", + ] + assert "<- scales, units" in str(diagram) or "<- units, scales" in str(diagram) + by_label = {n["label"]: n for n in diagram.to_dict()["nodes"]} + assert by_label["left"]["facts"] == [["source id", "dict_v1:left"]] + assert by_label["right"]["facts"] == [["source id", "dict_v1:right"]] + for picture in (diagram.to_svg(), diagram.to_html()): + assert ">unitsleft None: + job = _job(_left(), _right(label=None)) + job_html: Any = job.nodes["left"]._repr_html_() + assert "units" in job_html + plain: Any = _job(_left(None), _right(None)).nodes["left"]._repr_html_() + assert "units" not in plain and "left" in plain + + +def test_explain_and_trace_values_are_those_without_a_label() -> None: + jobs = [_job(_left(), _right()), _job(_left(None), _right(None))] + for job in jobs: + job.run() + labelled, plain = (job.nodes["sum"] for job in jobs) + assert labelled.explain() == plain.explain() + assert labelled.explain().text() == plain.explain().text() + ours, theirs = (n.trace({"k": 1}, "z") for n in (labelled, plain)) + assert ours.source_cells() == theirs.source_cells() + assert [c.text() for c in ours.source_cells()] == [ + c.text() for c in theirs.source_cells() + ] + assert ours.highlight() == theirs.highlight() + + +def test_a_line_break_in_a_label_stays_on_one_line() -> None: + job = _job(_left("a\nb\u2028c"), _right()) + lines = str(job.diagram()).splitlines() + assert " a\\nb\\u2028c (source · DictSource · bound)" in lines + assert len(lines) == 1 + len(job.nodes) + + +@pytest.mark.parametrize("swap", [False, True]) +def test_only_the_shown_text_changes(swap: bool) -> None: + """Names, hashes, ids, stored paths, order and topology are those without labels.""" + labelled_db, plain_db = InMemoryArrowDatabase(), InMemoryArrowDatabase() + labelled = _job(_left(), _right(), database=labelled_db, swap=swap) + plain = _job(_left(None), _right(None), database=plain_db, swap=swap) + assert list(labelled.nodes) == list(plain.nodes) + for name, node in plain.nodes.items(): + other: Any = labelled.nodes[name] + assert other.label == node.label + assert other.content_hash() == node.content_hash() + assert other.pipeline_hash() == node.pipeline_hash() + assert other.node_uri == node.node_uri + assert other.output_schema(all_info=True) == node.output_schema(all_info=True) + labelled.run(), plain.run() + for name, node in plain.nodes.items(): + # A function's source info holds a random result id, so it is not compared. + info = {"system_tags": True, "source": node.node_type != "function"} + want = node.as_table(columns=info) + got = labelled.nodes[name].as_table(columns=info) + assert got.equals(want) + assert sorted(labelled_db.list_table_paths(())) == sorted( + plain_db.list_table_paths(()) + ) + ours, theirs = labelled.diagram().to_dict(), plain.diagram().to_dict() + assert ours["edges"] == theirs["edges"] + for a, b in zip(ours["nodes"], theirs["nodes"], strict=True): + a.pop("text", None) + a["facts"] = [f for f in a["facts"] if f[0] != "source id"] + assert a == b + assert labelled.left is labelled.nodes["left"] + labelled.bind(sources={"left": _left("renamed")}) + assert _texts(labelled)["left"] == "renamed" + + +@pytest.mark.parametrize("order", [("left", "right"), ("right", "left")]) +def test_binding_two_sources_in_either_order_changes_the_texts_only( + order: tuple[str, str], +) -> None: + job = _job(_left(), _right()) + before = { + name: (node.label, node.content_hash(), node.pipeline_hash()) + for name, node in job.nodes.items() + } + sources = {"left": _left("new"), "right": _right("new")} + job.bind(sources={name: sources[name] for name in order}) + texts = _texts(job) + assert (texts["left"], texts["right"]) == ("new (left)", "new (right)") + assert before == { + name: (node.label, node.content_hash(), node.pipeline_hash()) + for name, node in job.nodes.items() + } + + +def test_without_a_label_the_texts_are_unchanged() -> None: + job = _job(_left(None), _right(None)) + job.run() + assert job.diagram().to_text().splitlines()[1] == ( + " left (source · DictSource · bound)" + ) + assert all("text" not in n for n in job.diagram().to_dict()["nodes"]) + assert "source id" not in job.diagram().to_html().split("