diff --git a/.zed/rules b/.zed/rules index 0131133c6..de6e0dad5 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1486,11 +1486,15 @@ data. The rules: not; never Python's ==, which ignores fold within one tzinfo), with a consistent hash. That equality decides whether two restrictions are one, never which rows a source returns: a condition is pushed down as column == value and the table system's equality decides - (developer, November 19, 2026: a NaN, an infinity or a signed zero is accepted, pushed down - and documented, never filtered on the client or refused; a NaN or infinite value is saved - as {"float": "nan" | "inf" | "-inf"}); text()/str, and + (developer, November 19, 2026: an infinity or a zero is accepted, pushed down and + documented, never filtered on the client; a NaN or infinite value is saved as + {"float": "nan" | "inf" | "-inf"}). For now, SpiralDB where refuses equality to -0.0 or a NaN + (developer, November 27, 2026), checked on the arguments as given, before merging. SpiralDB + matches them by their bits, so the rows read would depend on which of two equal values was + kept. Float ranges are also refused for now (ITL-1477). Revisit the float refusals in + ITL-1480. The condition has text()/str and to_config/from_config (the saved where mapping). Internally terms (column, operator, - value), equality only today; the public surface names no operator. Never add a second + value), including equalities and supported ranges. Never add a second restriction class: a limit stays the source's own (limit=). Today only SpiralDBTableSource.where(mapping=None, /, **columns) exists: Condition.of, then the source checks it against its table (unknown column, the column's exact Python type and diff --git a/CLAUDE.md b/CLAUDE.md index 053e2539b..164a9b196 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1534,11 +1534,15 @@ data. The rules: not; never Python's `==`, which ignores `fold` within one tzinfo), with a consistent hash. That equality decides whether two restrictions are one, never which rows a source returns: a condition is pushed down as `column == value` and the table system's equality decides - (developer, November 19, 2026: a NaN, an infinity or a signed zero is accepted, pushed down - and documented, never filtered on the client or refused; a NaN or infinite value is saved - as `{"float": "nan" | "inf" | "-inf"}`); `text()`/`str`, and + (developer, November 19, 2026: an infinity or a zero is accepted, pushed down and + documented, never filtered on the client; a NaN or infinite value is saved as + `{"float": "nan" | "inf" | "-inf"}`). For now, SpiralDB where refuses equality to -0.0 or a NaN + (developer, November 27, 2026), checked on the arguments as given, before merging. SpiralDB + matches them by their bits, so the rows read would depend on which of two equal values was + kept. Float ranges are also refused for now (ITL-1477). Revisit the float refusals in + ITL-1480. The condition has `text()`/`str` and `to_config`/`from_config` (the saved `where` mapping). Internally terms (column, operator, - value), equality only today; the public surface names no operator. Never add a second + value), including equalities and supported ranges. Never add a second restriction class: a limit stays the source's own (`limit=`). Today only `SpiralDBTableSource.where(mapping=None, /, **columns)` exists: `Condition.of`, then the source checks it against its table (unknown column, the column's exact Python type and diff --git a/changelog.d/ITL-998.md b/changelog.d/ITL-998.md new file mode 100644 index 000000000..be1ad55a4 --- /dev/null +++ b/changelog.d/ITL-998.md @@ -0,0 +1,29 @@ +### Added + +- `SpiralDBTableSource.where(...)` and `where=` take ranges of integer, timestamp and date + columns, written with `col` as in `filter`: `events.where(col("timestamp") >= start, + col("timestamp") < stop)`, and `col(c).between(a, b)` (both ends included). SpiralDB + applies them in the scan, with any equalities; all must hold. A range is a restriction: + no hash, source id, schema or record id changes. Bounds are checked like equality values + and never converted, rounded or clamped. Ranges of string, binary and boolean columns + are refused. Float ranges are refused for now (ITL-1477). Use `filter` for these ranges. + Source range restrictions are available only on `SpiralDBTableSource` (ITL-1219). +- `SpiralDBTableSource.where` takes several conditions as positional arguments, as `filter` + and `Condition.of` do: mappings and conditions, plus keywords. + +### Changed + +- A condition made only of equalities (a source's `where`, a `Filter`) is saved with its + columns in canonical order, as a condition with other terms already was: `where(b=1, + a=2)` and `where(a=2, b=1)` save the same bytes. Saved jobs and configs written before + load to the same condition; their bytes change only when two or more columns had been + given out of that order. No hash, stored path or identity reads a saved condition. +- The `where` parameter of `SpiralDBConnector.scan_batches` is PROVISIONAL and takes a + `Condition` (equalities and ranges). To pass a mapping, wrap it in `Condition.of(...)`. +- For now, `SpiralDBTableSource.where(...)` and `where=` refuse an equality of a float + column to `-0.0` or a NaN (`TypeError`, pointing to `filter`). SpiralDB matches them by their bits, + while Orcapod counts `-0.0` equal to `0.0` and NaN equal to NaN, so the rows read could + depend on which of two equal values a condition kept. ITL-1480 tracks revisiting the float + refusals. +- A condition that requires two different values of one column in `where` now raises + `ValueError` ("already restricted"), as across chained calls, rather than `TypeError`. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 024c09153..58beec3fa 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -880,15 +880,9 @@ print(recorded.filter(col("t") >= 1.0).head(3).as_table().num_rows) # 2 ``` -**`where` and `filter`.** A source that can restrict what it reads (`where`, see -[Restricting a source](sources.md#restricting-a-source-versus-filtering-in-the-pipeline)) takes the same equalities. The two give the -same rows, except on a float column for a NaN or a signed zero (`where` uses the table -system's equality, `filter` Orcapod's: a NaN may match no row under `where` and matches the -NaN rows under `filter`) and on a source with a `limit` (the limit then counts the matching -rows). `where` is not a step of the pipeline: it changes no hash, while `filter` is a -node whose condition enters the identity of every step after it. Explore with `where`; keep -the selection with `filter` when it becomes part of what the pipeline computes. `where` -takes only equalities today and refuses any other condition, pointing to `filter`. +**`where` and `filter`.** `SpiralDBTableSource.where` restricts the rows read from the source. +`filter` adds a pipeline node whose condition enters the identity of every step after it. +For supported equalities and ranges, see [Restricting a source](sources.md#restricting-a-source-versus-filtering-in-the-pipeline). **What is read, and what is applied after reading.** `stream.explain()` (new in this release) says, for every source a stream reads, what the source applies itself (its `where` diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4f6b04177..7d0e5c5a9 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -393,7 +393,8 @@ print(first.row_count_estimate) # rows in the whole table; reads every key to c - `limit=n` reads the first `n` rows in key order. - `where={column: value, ...}` reads the rows in which every named column equals its value - (`source.where(...)` adds conditions to a built source; see + (`source.where(...)` adds conditions to a built source, and also takes ranges of integer, + timestamp and date columns, such as a window of time; see [Restricting a source versus filtering in the pipeline](#restricting-a-source-versus-filtering-in-the-pipeline)). - `asof=` reads the table as of an earlier version, and keeps reading it. Without it, a source reads the version the table had when the source was built, in every read, until a @@ -444,8 +445,41 @@ same rows. The conditions are a `Condition` (`orcapod.types`): `where(...)` buil given instead (`events.where(Condition.of(unit_id=106, session_index=2))`). A source restricted by a condition, a `limit=`, or both is **restricted**. Every source states its restriction through two read-only properties: `condition` (the empty `Condition` when it -reads every row) and `row_limit` (`None` without a limit). A restriction is not an -operator: +reads every row) and `row_limit` (`None` without a limit). + +**Ranges.** Source range restrictions are available only on `SpiralDBTableSource` (other +sources are tracked in ITL-1219). `where` takes a range of an integer, timestamp or date +column, written with `col` as in `filter`. A half-open window, `>= start` and `< stop`, lets +adjacent windows meet without gaps or overlaps. `col(c).between(a, b)` includes both ends. + + +```python +from orcapod import col + +hour = 3_600_000_000 # the timestamp column counts microseconds +first_hour = events.where(col("timestamp") >= 0, col("timestamp") < hour) +second_hour = events.where(col("timestamp") >= hour, col("timestamp") < 2 * hour) +one_unit = first_hour.where(unit_id=106) # a range and an equality +``` + +Ranges and equalities all must hold, on one column or several, given in one call or across +chained calls in any order: the order never changes the rows, the condition or how it is +saved. Ranges that cannot all hold are kept and read no row. A null meets no range. SpiralDB +applies a range in the scan, so only the window's rows are transferred, and the row cap +counts them. A bound is checked as an equality value is: exactly of the column's Python type +(`int`, `datetime`, `date`), held exactly by its Arrow type (`-1` is refused for an unsigned +column, a microsecond for `timestamp[s]`, a naive `datetime` for a zoned column), never +converted, rounded or clamped. Ranges of strings, binary values, booleans and other +unsupported types are refused, as are conditions such as `is_in`, null tests, `!=`, +comparisons between columns, `|`, and `~`. + +Use `filter` for float ranges. Orcapod evaluates `filter` after the read, treating `0.0` and +`-0.0` as equal and all NaNs as one value ordered after every number. `where` pushes the +condition into SpiralDB, whose IEEE 754 total order puts `-0.0` below `0.0`. For example, +`filter(col("x") >= 0.0)` keeps rows with `-0.0`. SpiralDB would drop those rows if it +applied the same condition. `where` refuses float ranges for now (ITL-1477). + +A restriction is not an operator: - An operator (`Filter`, `SemiJoin`, `PolarsFilter`) is a step of the pipeline. It is a node of the graph and part of the pipeline's identity: a pipeline with a filter computes something @@ -466,8 +500,9 @@ the pipeline computes. Restrict on tag (key) columns where you can; a condition column is allowed. `where` and `stream.filter` take the same equalities, written the same way, and keep the same -rows (for a float column, `where` uses the table system's own equality for NaN and `-0.0`, -`filter` Orcapod's: see [Filter](operators.md#filter)). One spelling differs: `filter` takes +rows (for a float column, `where` uses the table system's own equality, `filter` Orcapod's: +see [Filter](operators.md#filter). SpiralDB's equality tells the two zeros apart and a NaN by +its bits, so `where(x=0.0)` does not read a row holding `-0.0`). One spelling differs: `filter` takes `label=` (the step's label, as every stream method does), so a column named `label` is written `filter({"label": "x"})` or `filter(col("label") == "x")`, while `where(label="x")` restricts that column. Neither takes `None` as a value: both raise `ValueError` and point to @@ -484,7 +519,7 @@ explore = events.where(unit_id=106, session_index=2) # The pipeline: the same selection as a step, part of every downstream identity. kept = events.filter(unit_id=106, session_index=2) -# Anything but equality is a filter; where refuses it and points to filter. +# Use a filter for conditions such as is_in that where cannot apply. late = events.filter(col("spike_time_us") >= 1_000_000, col("unit_id").is_in([106, 107])) ``` @@ -497,10 +532,9 @@ timestamp columns, on a source without a `limit`. With a `limit` it does not: th reads the first rows that match the `where`, so the `filter` sees other rows than it would over the source alone (with `limit=2` and unit ids `[1, 2, 2]`, `filter(unit_id=2)` alone keeps one row, the `where` and the `filter` together keep two). On a float column it does -not either when the value is a NaN or a signed zero: -`where` matches by the table system's equality (a NaN may match no row), `filter` by -Orcapod's (a NaN matches the NaN rows), so `where` can drop rows the `filter` alone would -keep. For such a value, filter without the `where`. +not either when the value is `0.0`: `where` matches by the table system's equality (`0.0` +does not match `-0.0`), `filter` by Orcapod's (it does), so `where` can drop rows the `filter` +alone would keep. For such a value, use `filter` on its own. ```python @@ -561,8 +595,10 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **One mechanism.** `where()` adds to the conditions given with `where=` (a mapping or a `Condition`) when the source was built (`Condition.combined`), and SpiralDB applies them - in the scan. A column already restricted to another value - is refused, as is a column the table does not have, `None` (a null equals nothing) and + in the scan. If you call `SpiralDBConnector.scan_batches` directly, its PROVISIONAL + `where` parameter takes a `Condition`. Use `Condition.of(...)` to wrap a mapping. + A column already restricted to another value is refused, as is a column the table + does not have, `None` (a null equals nothing) and `where()` with no condition. Everything else of the source is carried over: the pinned table version, `limit`, `max_rows`, the tags and data-tags, `tags_as_data`, the key columns, the source id and the label. The original source is not changed. @@ -574,27 +610,29 @@ 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, 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 + and which rows it selects is SpiralDB's own equality, not Orcapod's. For a float column, + `0.0` does not select the `-0.0` rows (seen on the service, not documented by it). An + equality to `-0.0` or a NaN raises `TypeError` for now and points to `filter`. SpiralDB matches + them by their bits, while Orcapod counts `-0.0` equal to `0.0` and NaN equal to NaN, so + the rows read would depend on which of two equal values a condition kept. ITL-1480 tracks + revisiting the float refusals. 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 - source's identity, so a pipeline holds one restriction (or none) per source: building a - pipeline in which one table is read with two different restrictions (or with and without - one) raises `ValueError` instead of silently reading one of them, whatever streams lead to - the table: different column selections or operator chains, streams built before the - pipeline, a `CachedSource` or a `SourceProxy` bound to it. It is checked from what each - stream reads at that moment: when the pipeline is built, when it is compiled, by `bind` - before it binds (a slot bound to a stream over a table another slot reads) and when a run - starts. Use one restriction per pipeline, or build separate pipelines. + inside the pipeline (`PolarsFilter`). An infinite value is saved as `{"float": "inf"}` or + `{"float": "-inf"}`, since JSON has no such number. +- **One restriction per source identity in a pipeline.** Restrictions are equal by statement. + On an integer column, `t >= 3` and `t > 2` select the same rows but count as two + restrictions. A restriction leaves the `source_id` and `content_hash` unchanged, so reading + one table under two windows with the same source identity in one pipeline raises + `ValueError`. Give each window its own `source_id` to use both in the same pipeline. The + same check covers restricted and unrestricted reads of one source identity, including + reads through projections, operator chains, and source wrappers. It runs at pipeline + construction, compilation, binding, and the start of each run. - **With `limit=`.** A source built with `limit=n` reads the first `n` rows that match, in key order: the conditions are applied first. -- **Conditions as values.** Two conditions are equal when they require the same columns to - equal the same values, in any order. Values of different types differ (`1`, `True` and +- **Conditions as values.** Equality compares the columns, operators and values in any + order. Values of different types differ (`1`, `True` and `1.0`); floats compare as Orcapod matches them (`0.0` equals `-0.0`, NaN equals NaN); an aware `datetime` is its instant, so one instant written in two zones is one value, and the two 01:30 of a daylight-saving overlap (`fold`) are two. This equality decides whether two @@ -637,8 +675,8 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **Stored rows stay.** A run over a restricted source deletes nothing: a job node shows the rows of its current run, and `node.as_source()` shows everything stored for it. -`where()` is a copy of the source with the restriction applied to the copy; a later version -offers the two steps on their own, and restrictions on other kinds of source. +`where()` copies the source and applies the restriction to the copy. ITL-1219 tracks exposing +the two steps separately and extending restrictions to other source types. **Running again.** A run first checks the source: when the table has a newer version (rows added since the source was built or last checked), the source reads that version from then diff --git a/docs/dev/plans/itl-998-plan.md b/docs/dev/plans/itl-998-plan.md new file mode 100644 index 000000000..29c386006 --- /dev/null +++ b/docs/dev/plans/itl-998-plan.md @@ -0,0 +1,173 @@ +# ITL-998 implementation plan: range restriction for `SpiralDBTableSource` + +The design is `docs/dev/specs/itl-998-range-restriction.md`; its decisions are section 8. This plan implements +D1 to D14: a float range is refused for now (D14, option A). ITL-1480 tracks revisiting the float refusals. +The follow-up that pushes down a rewritten float range, +ITL-1477, stays an isolated addition: one gate, one function and their tests, listed at the end. + +## Branch and dependencies + +- Work continues on the branch of PR 574 (`eywalker/itl-998-spiraldbtablesource-restrict-a-read-to-a`), + which holds the spec and this plan. `main` is merged in when it moves; no rebase, no force-push. +- **ITL-1465 (PR 576).** Merged into `main`, and `main` merged in here (2026-11-26). ITL-998 needs none of its + code: a range is built with `col`; ITL-1465 turns `start <= col(c) < stop` (and `c1 and c2`) into an error + instead of a silently dropped bound. Until it was on `main` its branch was not merged into this one, and + PR 574 stayed a draft (D11). The test that depends on it is in place (`where(start <= col("t") < stop)` + raises). +- The sketch in the worktree (uncommitted, from the coordinator's handoff) is the starting point; section 7 of + the spec says what of it is kept and what changes. + +## Code + +### `src/orcapod/types/condition.py` + +- `is_range_type(arrow_type)`: integers of every width, timestamps of every unit and zone, `date32`, `date64`. + Floats are excluded here, and only here (D14). +- `check_restriction(condition, schema)`: the one check of a source's restriction, run on the condition given + and again on the combined one. Each top-level child must be a term on a plain column (no field, no other + column as operand) with `==` or one of `<`, `<=`, `>`, `>=`; otherwise `TypeError` pointing to + `source.filter(...)`. The column must exist (`ValueError`, today's wording). Every value passes + `check_value_for_column` (exact type, exact fit: D6). A comparison on a column that is not + `is_range_type` raises `TypeError` naming the column and its type, pointing to `filter`. Two different + equalities on one column stay refused (`ValueError`, today's wording); comparisons are kept as given (D3, D7). + The sketch's call of `check_equality_conditions` per term is replaced by the column check and + `check_value_for_column`; `_checked_conditions` in the source becomes unused and is deleted. +- `Condition.to_config` (D8): an equality-only condition is written as today's mapping, its keys in canonical + order (the order `canonical_form` sorts the terms). A condition with any other term is already saved in + canonical order. `Filter`'s saved config uses the same method, so it follows too; no identity reads it + (`Filter`'s identity is `canonical_form()`), and no golden value moves. +- Docstrings: `EQUALS`, `only_equalities`, the class docstring (the sketch's wording). + +### `src/orcapod/core/sources/spiraldb_table_source.py` + +- `where(*conditions, **columns)`, as `filter` and `Condition.of` take them (today `where(mapping=None, /, + **columns)`; a single positional mapping or condition still works). `Condition.of`, then + `_apply_restriction` calls `check_restriction` on the new condition and on the combined one. +- The constructor's `where=` goes through the same check. +- The scan is described by one list of terms, `(column, operator, value)` with equality included, passed to + the connector (spec section 7), built from `condition.terms()`. +- The cap message names the condition and says how to narrow it or raise `max_rows` (D9). `head()` and the + preview note use `condition.text()` (order given) and label the size as the table's (D10). +- Docstrings and the module example: the half-open window; the types; floats, strings and the rest go to + `filter` (the docstring names ITL-1477 for floats; the error text does not). The sentence calling a range of the first key columns "the cheapest to read" is removed (not + measured). + +### `src/orcapod/databases/spiraldb_connector.py` + +- The `where` parameter of `SpiralDBConnector.scan_batches` is PROVISIONAL and takes the source's + `Condition` (its terms are the one list of `(column, operator, + value)`) instead of a mapping; done this way rather than a new `terms=` argument, since `Condition` is the one + restriction class. One loop builds the predicate: an equality as today (`_literal`; a `float16` equality still + compared locally, an inexact `float32` one still reads no row, as today); a comparison through one new + function, `_range_predicate(column, operator, value, stored_type)`, which builds `sp.lt`/`lte`/`gt`/`gte` on + `_literal(value, stored_type)` and refuses (`ValueError`) a stored type that is not `is_range_type`. It never + reads and filters a range locally. Callers that passed a mapping wrap it in `Condition.of(...)`. +- Every caller of `scan_batches` and `_read_batches` passes the terms; `limit` counts matching rows, as today. + +## Tests (offline, on the fake) + +`tests/test_databases/fake_spiral_sdk.py`: `lt`, `lte`, `gt`, `gte` with the service's rules as observed live: +a literal of another type is refused, a null meets nothing, and floats compare by IEEE total order (as the +service does; unused while floats are refused, ready for ITL-1477). + +`tests/test_core/sources/test_spiraldb_table_source_where.py`, on tables with two or more key columns and two or +more data columns (CLAUDE.md, "Testing conventions"; the shared several-item family where it fits): + +1. **Rows.** Each operator, `between` (closed; also of one value), one-sided, `start == stop`, a reversed window + (zero rows, full schema), both ends of each integer width; each against the rows pyarrow selects from the + whole table. +2. **Several items, several orders.** Two ranges on one column; ranges on two columns; a range with one and + with two equalities; an equality and a range on one column. Every permutation of the arguments, of `&` + operands, of keywords against positional mappings, and of chained `where` calls gives the same rows, + condition, `canonical_form`, saved config bytes, and loaded condition; `text()` keeps the order given. +3. **Roles.** A range of a key column (first and last), of a data column with nulls, of a data-tag, and with + `tags_as_data`; `tag_only_columns=True` except where the default is the subject. +4. **Types.** Eight integer widths, four timestamp units naive and zoned (both 01:30 of a daylight-saving + overlap), `date32`, `date64` (also not midnight). Every refusal of the spec's section 2 table (wrong Python + type, out of range, inexact, wrong zone kind, `bool` for `int`), a range of `float16`, `float32`, + `float64`, string, binary, boolean and the unsupported types, each asserting that no scan ran; float + equalities unchanged. +5. **Refused trees.** `|`, `~`, `!=`, `is_in`, null tests, a field, a column against a column: the whole + condition refused, nothing applied. Two different equalities refused; contradictory ranges kept. +6. **Identity.** Content hash, pipeline hash, source id, schema, system-tag names and every record id equal the + unrestricted source's; the constructor and chained `where` are one mechanism; the original source is + unchanged. `generate_golden_hashes.py --check` reports no drift. +7. **Reads.** Row cap (a window under the cap on a larger table; over it raises naming the window), `limit` + (also with a local `float16` equality), `head()` and the preview note, zero rows, `check_for_new_data`, + a rebound slot with a moved window is stale, overlapping windows compute each shared row once. +8. **Sync and async.** Source reads and whole jobs give the same rows on both paths; the one-restriction + refusal, the `CachedSource` and caching-operator refusals, the aggregation warning and + `RunSummary.conditions` with a range. +9. **Saved.** Source config and a saved and loaded job, with datetimes and dates tagged; an equality-only + `where` with two columns given out of order saves in canonical order; a config saved before (keys in the + order given) loads to the same condition; one-column configs unchanged byte for byte. +10. `where(start <= col("t") < stop)` raises (ITL-1465, on `main`). + +`tests/test_types_condition*.py`: `to_config` key order of an equality-only condition (the existing tests compare +dicts, which ignore order, so they keep passing; one new test compares the JSON text). + +## Tests (opt-in, live) + +- `tests/test_core/sources/test_spiraldb_table_source_live.py` (`ORCAPOD_SPIRAL_LIVE_PROJECT`, read-only): a + window, and a window with an equality, equal the local selection of the full read; record ids a subset; + arguments reversed; `limit`; `head`; an empty window. +- `tests/test_databases/test_spiraldb_connector_integration.py` (`SPIRAL_INTEGRATION_TESTS`, writes its own + tables and drops them): the kept form of the conformance probe for every type of section 2, against pyarrow, + plus the float order the service uses (so a change in it shows, and ITL-1477 starts from it), run on the + final code before ready (D12). The fake runs the same cases. + +Run locally: the touched test files only, one pytest process; ruff, ruff format, basedpyright with its exit code; +`scripts/design_issues.py --check` and `scripts/assemble_changelog.py --check`. + +## Documentation + +- `docs/concepts/sources.md`, SpiralDB section: ranges in `where` (the half-open window, `between` closed, + several ranges, ranges with equalities), the types, why floats (the service's float order; ITL-1477), + strings and the rest go to `filter`, the cap + and `head()` with a window. The existing note on float equality (the table system's own) gains the finding: + `0.0` does not match `-0.0`, and NaN matches by bit pattern. Samples that need SpiralDB stay marked + `docs-test: skip`. +- The `where` docstrings; the API reference is generated from them. + +## Changelog + +`changelog.d/ITL-998.md`: + +- `### Added`: `SpiralDBTableSource.where` and `where=` take ranges of integer, timestamp and date columns + (`col("t") >= start, col("t") < stop`, `between`), applied by SpiralDB in the scan; `where` takes several + conditions, as `filter` does. +- `### Changed`: a saved equality-only condition (a source's `where`, a `Filter`) lists its columns in canonical + order; earlier saved files load unchanged. + +## Conflicts with open PRs + +- 555 (ITL-1457), 558 and the ITL-1464 stack (559, 560, 562, 563, 565, 566, 567, 569, 570, 571): no text + conflict with the prototype (`git merge-tree`, 2026-11-26). What each could change in behaviour is the spec's + section 5 table; the tests above cover each point (a restricted copy given a connector, tokens of a window, + bounded views, async rows, spool staleness, certificates, repeated keys inside a window). Whichever lands + after ITL-998 runs those tests on its own head. +- 553 and 554 (other drafts of ITL-1457) conflict in `spiraldb_connector.py`, in the scan's predicate lines; the + one that lands second resolves it. +- 576 (ITL-1465): no text conflict; merged in only through `main`. + +## Order of work + +1. Merge `main` in. Commit the sketch's kept parts with the changes of spec section 7 (condition, connector, + source), then the fake. +2. Tests 1 to 9, then the condition tests; ruff, basedpyright, the golden check. +3. Docs, changelog fragment. +4. Live tests written; the conformance test run on throwaway tables before ready. +5. After 576 merged: merge `main`, add test 10 (done). Then the PR readiness pipeline. + +## ITL-1477, later (isolated) + +Not part of ITL-998. What the follow-up changes, so that nothing here is restructured for it: + +1. `is_range_type` accepts `float32` and `float64` (not `float16`: the SDK has no `float16` literal). +2. `check_restriction` refuses a NaN bound, and a float bound the column type cannot hold exactly (D6: `0.1` on + `float32`), for comparisons only (equalities keep today's rule). +3. `_range_predicate`, for a float column only: adds `col >= -inf` and `col <= +inf` (excludes every NaN, which + the service orders beyond the infinities) and sends a zero bound as `+0.0` for `>` and `<=`, `-0.0` for `<` + and `>=` (so `-0.0` equals `0.0`). +4. Tests: the fake's total order makes the rewrite testable offline (every operator with each special value as + row and bound, against the stance); the live conformance test checks it against the service. diff --git a/docs/dev/specs/itl-998-range-restriction.md b/docs/dev/specs/itl-998-range-restriction.md new file mode 100644 index 000000000..8c3e99b78 --- /dev/null +++ b/docs/dev/specs/itl-998-range-restriction.md @@ -0,0 +1,372 @@ +# ITL-998: restrict a SpiralDB read to a range of a column + +The design is implemented on this branch. The developer reviewed D1 through D15 on 2026-11-27 +(section 8). The plan is `docs/dev/plans/itl-998-plan.md`. This work depends on +ITL-1465 (D2). + +`SpiralDBTableSource` restricts a read by equality (`where`) and `limit=`. A long table needs a window too, +applied by SpiralDB before rows are transferred. A range is a restriction: it chooses rows of the same data and +enters no identity. + +Evidence marks: **[live]** read-only against the installed spiral-sdk 0.16.74 on a real keyed table; **[sdk]** +the SDK's source or a local call; **[fake]** the test fake with a prototype applied; **[code]** read on `main` +(0d1e017c). + +## 1. The form: comparisons in `where()` + +```python +from orcapod import col + +source.where(col("timestamp") >= start, col("timestamp") < stop) # a window +source.where(col("timestamp") >= start, col("timestamp") < stop, unit_id=106) # and an equality +source.where(window, col("unit_id") < 20) # two columns +SpiralDBTableSource(project, "events", where=window & Condition.of(unit_id=106)) +``` + +`where(*conditions, **columns)` takes what `filter(...)` takes: mappings, `Condition`s built with `col`, and +keywords, all of which must hold. The alternative, `window=("col", a, b)`: + +| | Comparisons in `where` | `window=` | +|---|---|---| +| Two ranges; a range and an equality | another argument | a list of tuples, beside `where` | +| One-sided, or both ends open | written as it reads | `None` for an end, plus a flag | +| Half-open or closed | visible in the operator | a convention to remember | +| Config, equality, hash, run summary | `Condition` has them | a second restriction form to add everywhere | +| Moving a step between source and pipeline | the same `Condition` in `filter(...)` | another spelling | +| Mistakes | the Python pitfall of D2 | swapped ends | + +The project rule is one restriction class, `Condition` (ITL-1218), and `Condition` already holds comparisons +(ITL-1374): `window=` would be a second one. **D1: comparisons.** + +Cases (each is a test): + +- **Two ranges on one column** add up (their intersection). `where(...).where(...)` too. +- **A range and an equality**, on the same or another column: both are sent. +- **Ranges on two columns**: both are sent. [live] a window on each of two columns returned the expected number + of rows. +- **Order**: `where(a, b)`, `where(b, a)`, `where(b & a)` and `.where(b).where(a)` are equal conditions with one + hash and one canonical form [code]. [live] the two bounds sent in either order returned identical tables. The + saved form lists terms in canonical order, the text in the order given (section 3). +- **Refused, with a pointer to `filter`**: `|`, `~`, `!=`, `is_in`, null tests, struct fields, a column against + a column. Any of these in the tree refuses the whole condition; nothing is applied in part. +- **Contradictions**: two equalities with different values stay refused (as today). Ranges that cannot hold + together, or a range that excludes an equality, are kept and read zero rows; the source does not reason about + satisfiability. **D3, approved.** + +**D2: the chained comparison.** `where(start <= col("t") < stop)` is how a window is written in mathematics. +Python evaluates it as `(start <= col("t")) and (col("t") < stop)`, and a non-empty `Condition` is true, so the +result is `t < stop` and the lower bound is **silently lost** (confirmed by running it; `c1 and c2` likewise). +`ColumnRef` refuses a truth value, `Condition` does not. For a window it is the likely mistake, and it reads the +wrong rows with no error. Approved, and a separate change: **ITL-1465** makes a `Condition`'s truth value an +error. ITL-998 depends on it and does not contain it: ranges ship after it. + +## 2. Bounds, column types and literals + +**Operators.** `<`, `<=`, `>`, `>=` exactly as written. The documented way to write a window is half-open, `>= +start` and `< stop`: adjacent windows neither overlap nor leave a gap. `col(c).between(a, b)` keeps the meaning +`Condition` gave it (ITL-1374): both ends included, equal to `>= a` and `<= b`; `a > b` is refused. A half-open +`between` would give one name two meanings. **D4, approved.** A null meets no comparison, as in SQL and in +`filter`. + +**Column types (D5, approved).** Unsigned and signed integers of every width; timestamps of every unit, with or +without a zone; `date32` and `date64`. Refused in a source's range: strings and binary (collation is the +service's), booleans, and every type a value condition does not support (decimals, times, durations, lists, +structs, logical types), and floats (**D14**): they were to be allowed (`float32`, `float64`) under +Orcapod's stance (ITL-1251: every NaN is one value and unordered, so a NaN meets no range comparison and a NaN +bound is refused; `-0.0` equals `0.0`), but the service orders floats otherwise ("Floats", below), so a float +range is refused for now. Pushing down a rewritten float range that matches Orcapod's comparison rules is +tracked in ITL-1477. The float refusals will be revisited in ITL-1480. A refused range points to `filter`. + +The check is on the column as Orcapod reads it (`_table_schema`), so a logical type stored as an integer is +refused. The literal takes the type SpiralDB stores (`reading.found`); the connector refuses a comparison on a +stored type with no literal, and never reads and filters locally. + +**No conversion.** A bound passes the rule every condition value passes (`check_value_for_column`), when the +condition meets the source, before any scan: + +| Column | Takes | Refused (`TypeError` naming the column, its type and the value) | +|---|---|---| +| `uint64` | `int` | `-1`, `2**64`, `2.0`, `True`, `"2"`, a `datetime`, a NumPy scalar | +| `int8` | `int` | `300` | +| `timestamp[us]` | naive `datetime` | an aware one, a `date`, an `int` | +| `timestamp[us, tz]` | aware `datetime`, compared as an instant | a naive one | +| `timestamp[ms]` | a whole number of ms | `...000001` (never rounded, though a bound could be) | +| `timestamp[ns]` | microsecond precision (Python's) | outside the years ns can hold | +| `date32`, `date64` | `date` | a `datetime` | + +A bound outside the type's range is refused, not read as "always" or "never" (**D6, approved**): `col("t") < +2**64` is more likely a unit mistake. `date64` values that are not midnight compare as stored; a bound is midnight. Error +wording: `SpiralDB table '/.': column 't' holds uint64, which cannot hold -1 ...`. + +**The SDK still needs a literal of the column's own type.** [live] An untyped Python `int` and an `int64` +literal against a `uint64` column are both refused: `Comparison requires equal dtypes ignoring nullability, got +u64? and i64`. A `uint64` literal works. [sdk] `literal` takes an explicit Arrow type; both ends of all eight +integer types are accepted and one past either end is refused; every timestamp unit, with and without a zone, +and both date types are accepted; time, duration and decimal types are not. "Scans compare without coercion, so +the unit and timezone must equal the column's" (its docstring). The connector's `_literal` already builds these +for equality, so ranges add only `sp.lt`, `sp.lte`, `sp.gt` and `sp.gte`. + +[live] with the prototype: a `uint64` window returned exactly the rows computed locally from the whole table; +with an equality, and with a range of a `uint32` column, the expected number of rows; a range with no match gave zero +rows with the full schema. + +[live] A conformance probe on throwaway tables, one per type, dropped afterwards: 23 of 23 stored and read back +unchanged, 2,530 checks, all equal to the answer pyarrow gives on the same rows. It covered: + +- `uint8` to `uint64` and `int8` to `int64` at both ends and one inside; `s`, `ms`, `us` and `ns` timestamps, each + naive, in UTC and in a daylight-saving zone, before and after 1970; `date32`, `date64` and a `date64` holding + values that are not midnight; a null in the compared column (it met no comparison, whatever the operator). +- The SDK alone: all four operators with each stored value as the bound. A + literal of another unit or zone was refused for every timestamp type. +- Through the prototype: all four operators, equality, `between` (also of one value), `start == stop` and a + reversed window (no row), a range with one and with two equalities, an equality and a range on one column, two + ranges on one column, ranges on two columns in all 24 argument orders and chained, a range of two key columns, + four limits, an async read, and the identity. Both 01:30 of a daylight-saving overlap are two instants. + +**Not shown live:** a date key column, or more than a weak check of a timestamp one: all four operators on an existing +naive `timestamp[us]` key gave the expected counts, but it held one value (SpiralDB creates no such key today, +so the probe's were data columns), a `ns` bound between two microseconds through Orcapod (Python +has none), and how much the service scans. Nothing differed from D5 or D6, so neither changes. + +**Floats (D14).** [live] A second probe, on throwaway tables dropped afterwards, stored one keyed table per +float type with: a quiet NaN, two signalling NaNs, a negative NaN, `+0.0` and `-0.0`, both infinities, the +smallest subnormal of each sign, the smallest normal, the largest and smallest finite values, ordinary values, +repeats, and a null. Every type stored and read back bit for bit, NaN payloads included. Then the SDK alone, with +each stored value as the bound: `<`, `<=`, `>`, `>=`, `==`, and `between` (as `>=` and `<=`) of every pair of +non-NaN bounds, each answer compared with pyarrow's on the same rows and with the stance. + +The service orders floats by IEEE 754 total order, as stored bits: `-NaN < -inf < ... < -0.0 < +0.0 < ... < ++inf < signalling NaN < quiet NaN` (NaNs ordered by payload). `float64`: + +| Case | The service returns | The stance (and pyarrow, except for NaN bounds) | +|---|---|---| +| `col > x`, `col >= x`, any non-NaN `x` (also `x = +inf`) | also every positive NaN | no NaN | +| `col < x`, `col <= x`, any non-NaN `x` (also `x = -inf`) | also the negative NaN | no NaN | +| `col < 0.0`, `col >= -0.0` | `-0.0` below `0.0`: `col < 0.0` holds `-0.0`, `col <= -0.0` lacks `0.0` | `-0.0` equals `0.0` | +| `between(a, b)` with `a = +0.0` or `b = -0.0` | misses the other zero (14 of 169 pairs) | both zeros | +| `between(a, b)`, other non-NaN bounds | the same rows (155 of 169) | | +| `col == 0.0`, `col == -0.0` | the zero of that sign only | both zeros | +| a NaN bound | ordered: `col == NaN` holds that bit pattern only; `col < quiet NaN` holds every number and the lower NaNs | refused (stance); pyarrow: no row | +| a null | meets nothing | meets nothing | + +Of 254 answers, 86 differ from pyarrow's; of the 234 with a bound the stance accepts, 68 differ from it, all of +them cases of this table. `float32`, the same rows and bounds: the same order and the same cases, 80 of 254 answers differ from pyarrow's +and 68 of 234 from the stance (every comparison with a non-NaN bound returns a NaN row, as for `float64`). The +SDK takes a `float32` literal only as a Python float, so a signalling NaN bound arrives quieted (it then sorts +above the stored quiet NaN); a bound the stance accepts is not affected. The rewrite of option C (below) was also +sent for every non-NaN bound and the four operators: 52 of 52 equal the stance. `float16`: stored, but the SDK has no `float16` literal, so +no comparison can be sent at all. + +So a float range is refused for now (D14, option A), with the pointer to `filter`. Reading +and comparing locally (B) gives up what a range is for, bounding the read. Pushing down a rewritten range that +equals the stance (C: add `col >= -inf` and `col <= +inf`, which excludes every NaN, and send a zero bound as +`+0.0` for `>` and `<=`, `-0.0` for `<` and `>=`) depends on the service's order staying as observed; it is the +follow-up ITL-1477. D6 would apply to such a bound (`0.1` is refused on a `float32` column). + +**Float equality findings:** + +- *A float equality value a narrower column cannot hold is accepted, not refused.* `check_value_for_column` takes + `0.1` for a `float32` column (it refuses only a finite value beyond the type's range), and the connector then + reads no row, since no `float32` equals `0.1` exactly: `where(f=0.1)` returns nothing, silently. This is the + one exception case to D6 found so far: a float range under ITL-1477 would refuse the value that an equality + on the same column accepts. +- *Float equality in `where` follows the service* (documented as "the table system's own equality"). The scan's + equality ([live] on `float64`, through the SDK) does not match `-0.0` to `0.0`, and matches a NaN to the same + bit pattern only. Before the refusal in D15, `where(x=nan)` read only the NaNs with the bits of Python's + `nan` (the quiet NaN). `where(x=0.0)` skips rows holding `-0.0`. `filter` follows Orcapod's rule (`-0.0` equals `0.0`, every + NaN equals NaN). +- *Changed here after review (D15):* an independent review of `d4115197` found that a `where` call that gives + one column both `-0.0` and `0.0` (or two NaNs) reads rows that depend on the order of the arguments: + `Condition.of` keeps one of two values Orcapod counts equal, and SpiralDB matches the one kept by its bits. + With a `float64` column holding `[-0.0, +0.0]`, `where(col("id") >= 0, {"v": -0.0}, v=0.0)` read id 1 and the + signs reversed id 0, under identical conditions, canonical forms and saved JSON. On 2026-11-27 the developer + decided, "for now let's error out for equality comparison to -0.0 and NaN". SpiralDB `where` raises `TypeError` + pointing to `filter` and ITL-1480, which tracks revisiting the float refusals. The check applies to the + arguments as given before merging and to every restriction a source applies. + One form stays out of reach: a condition the user combines beforehand with `&` + (`(col("v") == 0.0) & (col("v") == -0.0)`) has already kept `0.0`, which is pushed down as before. +- *The test fake's `float-eq` rule says NaN equals NaN*, any NaN; the probe saw the service match a NaN by bit + pattern only. The fake's comparison reads Python floats, so it cannot tell NaN payloads apart. + +**How it is pushed down.** The scan's `filter`, not `key_ranges=`: a filter works on any column and combines +with equalities. [live] the scan returned only the window's rows. How much the service scans to find them could +not be measured: this keyed scan reported no splits and no counters. The docs promise only which rows are +returned. + +## 3. Identity, where it is held, saved form + +- **Identity.** In no content hash, pipeline hash, source id, schema or system-tag name; + `_restriction_identity()` stays `None`. [live] the hashes and source id equal the unrestricted source's and + every record id read is one of its record ids. No golden value moves. +- **Held** in the source's one `Condition` (`source.condition`). Every rule that reads it needs no change: + `pipeline/restrictions.py` (one restriction per table in a pipeline, no `CachedSource` and no caching operator + node over a restriction), the aggregation warning, `RunSummary.conditions`. +- **Canonical form.** `Condition` equality, hash and `canonical_form()` are order-free and unchanged. They + compare statements, not row sets: `t >= 3` and `t > 2` are two restrictions on an integer column, so one table + read under both in a pipeline is refused. Redundant bounds are kept, never simplified. **D7, approved.** +- **Commutative.** Every form a source accepts is a conjunction of terms (equalities and the four comparisons; + `between` is two of them), so the condition is the set of its terms. `canonical_form()` flattens every `all` + and sorts its children, so the order of arguments, keywords, `&` operands, `combined` and chained `where` + calls never counts [code]. Checked: the 120 orders of five parts (two bounds of a datetime column, a + `between` of an integer column, an equality, a float comparison), each built with `&` and with `combined`, + give one canonical form, one saved form, and load back equal. `|` and `~`, which a source refuses, are + order-free in `canonical_form()` too (`any` sorted like `all`, `not` unary). +- **Saved, in canonical order (D8, approved as changed).** `to_config` writes `{":condition": {"all": [...]}}` + for a condition that is not only equalities, with tagged values for datetimes and dates, and `from_config` + rebuilds it through the public builders and the source's checks [code]. The earlier draft of this section + said the saved list follows the order given; it does not: since ITL-1374 `_node_to_config` writes the + children of `all` and `any`, and `is_in` values, in canonical order. So a condition with a range already saves + canonically, and needs no change. An equality-only condition is saved as a mapping, column to value, in the + order given: `where(b=1, a=2)` and `where(a=2, b=1)` save `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}`. To be + canonical it is written in canonical order (the order `canonical_form` sorts the terms, by the JSON text of + each term; for column names without spaces or punctuation, name order). That changes the bytes of a saved equality-only `where` only when it has two or + more columns given out of that order; one column, or columns given in order, stay byte for byte. Both forms + load to equal conditions, and no hash reads a source config (the saved job writes it as JSON; only database + configs are hashed, with sorted keys). Saved jobs from before load unchanged. +- **Printed.** `head()` and the run summary use `condition.text()`, in the order given; display only. + +## 4. Reads + +- **Row cap.** The pre-check counts the whole table, so it runs only when nothing but `limit` bounds the read; + with any condition it is skipped and the cap is applied while reading, to the matching rows [code]. A range + follows that rule: a window under the cap on a table far over it is read; a window over it raises + `SourceTooLargeError` after up to `max_rows` rows were handed on, so an async job can compute some rows first, + as with an equality today. The alternative is to count the matching keys up to `max_rows + 1` first: the SDK + has no filtered count (`Scan.count_rows` wants splits; a keyed scan has none [live]), so that is a second scan + on every read. **D9:** today's rule. The error names the window (`source.condition`) and the cap, and says how to + narrow it or raise `max_rows`. +- **`limit`** counts matching rows, in key order. [live] the limited range equals the first rows of the full + read that match. A `float16` equality in the same condition is compared locally, and then the limit too (as + today); the range is still sent. +- **`row_count_estimate`** stays the whole table's count and says so. +- **`head()` and the preview** read the first `n` matching rows in one bounded scan, without `max_rows`. The + note reads `first 2 matching rows (where timestamp >= ..., timestamp < ...); the table has about N rows`: the + count is named as the table's. When fewer than `n` match, the total is exact and the note says `all k rows`. + **D10:** the table's size, labelled as such; no count of matching rows. +- **Zero rows.** `all 0 rows`, no error, with a table of the same schema as any read [live]. Asking for the + schema, keys or hashes reads no row. +- **`check_for_new_data`** compares table versions (metadata only), so a commit outside the window moves the + pinned version and the modified time, and the nodes below run again and reuse every stored result. It does not + look inside the window, as for an equality. +- **Staleness.** `where()` returns a new source modified now; rebinding a slot to a moved window makes its nodes + stale. Rows of earlier windows stay stored; record ids do not depend on the window, so overlapping windows + compute each row once. +- **Uniqueness certificates** (PR 567): a source certifies its key columns because every read refuses a repeated + key. A subset of rows with unique keys has unique keys, so a range keeps the certificate and adds none (an + equality or one-value range does not make a shorter key unique here). The key check sees only the rows read: a + repeat outside the window is not found, as with `where` today. + +## 5. Overlap with open PRs + +Text conflicts were tested with `git merge-tree` against a commit holding the prototype (which changes the files +the implementation will). A clean merge does not prove the behaviour; the last column is what to test. + +| PR | Touches in SpiralDB reads | Text | To check | +|---|---|---|---| +| 555 (ITL-1457) | constructor `connector=`, `_for_source`, `_counts` per source; the read path is unchanged | clean | a restricted copy of a source given a connector | +| 558 | `with_source_info` through `_read_batches` and `_whole_table` | clean | a window's tokens equal the full read's | +| 559 | nothing (a new module, `row_spool`) | clean | - | +| 560 | `run()` reads in batches (`_batch_streams_of_rows`) | clean | a window's bounded view; zero rows | +| 571 (on 560) | `_preview_batches` calls `_read_batches` with a limit | clean | `preview(n)` over a window | +| 562 | only 558's commits in this file; async rows as Arrow chunks | clean | async rows of a window | +| 566 | 558's commits in this file; node rows on disk | clean | a moved window is stale, not read from the spool | +| 567 | `_whole_table` becomes `_whole_stream`; certificates in `sources/base.py` | clean | the certificate under a range | +| 570 | `identifiers` becomes `SeenKeys`, next to the scan call | clean | repeated keys inside a window | + +562, 566 and 570 contain 558; 566 also contains 559 and 562. Pairwise, 567 conflicts in +`spiraldb_table_source.py` with 558, 560, 562, 566, 570 and 571; these are between those PRs and do not involve +ITL-998. The prototype also merges cleanly with the integration branch (569), and its `where` tests give the +same 488 passes and 2 failures there as on `main`. Two other drafts of ITL-1457, 553 and 554, do conflict with +it in `spiraldb_connector.py`; the conflict is with the prototype's scan lines, so whichever lands second is +rebased. + +**D11, merge order (approved).** ITL-1465 (PR 576) first: ITL-998 depends on it. ITL-998 may then merge before +555 and 558; it is independent of the ITL-1464 stack and need not wait for it. The stack follows, with 567 last, +rebuilt on the rest (it rewrites `_whole_table`). If 553 or 554 is chosen over 555, the one that lands second +resolves the conflict in `spiraldb_connector.py`. Checked again on 2026-11-26 against the current heads: the +prototype merges cleanly with 576, 555, 558, 559, 560, 562, 563, 565, 566, 567, 569, 570 and 571, and +conflicts with 553 and 554 as before. + +## 6. Test plan + +Offline, on the fake. The fake gets the four comparisons and must keep refusing a literal of another type and +treating a null as no match. Extend `test_spiraldb_table_source_where.py` (tables there have several key and +several data columns): + +1. Rows: four operators, `between`, one-sided, `start == stop`, empty, both ends of each integer type. +2. Several items: two ranges on one column, ranges on two columns, range and one or two equalities, range and + equality on one column; every permutation of the arguments and of the chained calls gives the same rows, + condition, hash and saved-and-loaded condition. In each role: key column (tag and data-tag, `tags_as_data`), + non-key data column with nulls, first and last key column. +3. Types: eight integer widths, four timestamp units naive and zoned (both 01:30 of a daylight-saving overlap), + `date32`, `date64`; each refusal of section 2, asserting that no scan ran; a range of a `float16`, + `float32` and `float64` column refused (D14), while their equalities behave as today. +4. Refused trees: each form of section 1; `start <= col(c) < stop` given to `where` raises (from ITL-1465). +5. Identity: hashes, source id, record ids; chained `where` and the constructor are one mechanism; the original + source is unchanged. +6. Cap, limit (with a local `float16` equality too), head, preview note, zero rows, `check_for_new_data`, stale + after rebind, overlapping windows compute each shared row once. +7. Sync and async: source reads and whole jobs give the same rows. One-restriction refusal, caching refusals, + aggregation warning and `RunSummary.conditions` with a range. +8. Round trip: source config, saved and loaded job, tagged datetimes and dates; an equality-only config is + unchanged. + +Opt-in: + +- **Read-only**, in `test_spiraldb_table_source_live.py` (`ORCAPOD_SPIRAL_LIVE_PROJECT`): a window and a window + with an equality equal the local filter of the full read; record ids a subset; reversed arguments; `limit`; + `head`; an empty window. +- **Conformance** (`SPIRAL_INTEGRATION_TESTS`, which writes to its own dataset): every type of section 2 and + nulls, against the answer pyarrow gives, as a kept form of the probe (section 2), run on the final code before + ready. The fake runs the same cases, so a difference between fake and service shows. **D12.** + +## 7. What of the sketch to keep + +It applies cleanly to 0d1e017c; `test_spiraldb_table_source_where.py` gives 488 passed, 2 failed. Both failures +are in its tests: one indexes a scan log that holds one entry, the other feeds a nullable column to a `str` +parameter (and its last assertion, `... or loaded is not None`, is always true, so it checks nothing). + +Keep: + +- `where(*conditions, **columns)` and `check_restriction` (checked alone, then combined with the one in force), + and `is_range_type`. +- The scan pushing typed literals, and refusing rather than filtering locally. +- The fake's comparisons, and most tests. + +Change: + +- **One list of terms** to `scan_batches` (`(column, operator, value)`, equality included) instead of `where=` + plus `comparisons=`: one loop, and `Condition.equalities` (one value per column) is no longer how a scan is + described. The implemented `SpiralDBConnector.scan_batches` has a PROVISIONAL `where` + parameter that takes the `Condition` holding those terms. +- `check_restriction` calls `check_equality_conditions` for a range bound: call the value check + (`check_value_for_column`) under a neutral name; its "where names columns..." text stays. +- `_checked_conditions` is then unused: delete it and its test import. +- The sentence "a range of the first key columns ... is the cheapest to read" was not measured (section 2): + remove it. +- Add docs (`docs/concepts/sources.md`: the form, half-open, the types), the changelog fragment and the + tests of section 6 it lacks (permutations, several columns, roles, jobs, staleness). + +## 8. Decisions + +The developer reviewed all decisions on 2026-11-27. + +| # | Question | Decision | State | +|---|---|---|---| +| D1 | Form | Comparisons in `where()`, as in `filter`; no `window=` | Approved | +| D2 | `a <= col(c) < b` silently drops `a` | A `Condition`'s truth value is an error; not in this change, which depends on it | Approved, as ITL-1465 | +| D3 | Ranges that cannot hold together | Kept, zero rows; two different equalities stay refused | Approved | +| D4 | Ends | Operators as written; half-open is the documented window; `between` includes both ends | Approved | +| D5 | Column types | Integers, timestamps, dates; floats, strings, binary, booleans and the rest refused | Approved (floats: D14) | +| D6 | A bound the type cannot hold exactly | Refuse with `TypeError`; never round or clamp; for floats too (`0.1` on a `float32` column) | Approved; to be reconsidered if an exception case turns up (section 2, "Floats") | +| D7 | Equality of restrictions | By statement; no simplification, so `t >= 3` and `t > 2` differ | Approved | +| D8 | Order inside the saved config | Canonical order (ITL-1271); `head()` and the run summary keep the order given | Approved as changed; a range already saves canonically, an equality-only mapping changes (section 3) | +| D9 | Row cap with a range | Today's rule, no pre-count; a clear error naming the window and how to narrow it or raise the cap | Approved | +| D10 | Size shown by `head` | The table's size, labelled; no count of matches | Approved | +| D11 | Merge order | ITL-1465 (PR 576) first; ITL-998 may merge before 555 and 558; then the rest of the stack with 567 last | Approved | +| D12 | Live proof of the types | Throwaway tables now; the kept conformance test on the final code before ready | Approved; probes run, section 2 | +| D13 | Scope | `SpiralDBTableSource` only; other sources stay with ITL-1219 | Approved | +| D14 | Float ranges, given the service's float order | Refused for now, pointing to `filter`. Pushdown is tracked in ITL-1477. | Approved by the developer on 2026-11-27. Revisit the refusal in ITL-1480. | +| D15 | Float equality to `-0.0` or NaN in `where` (review of `d4115197`) | Refused for now with `TypeError` pointing to `filter`. | Decided by the developer on 2026-11-27. Revisit the refusal in ITL-1480. | + +One restriction per table in a pipeline stays in force; lifting it is ITL-1472, not this change. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 8d534e5a3..c5d46a80d 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -25,6 +25,11 @@ # The same restriction added to a built source: a new source, same identity source = SpiralDBTableSource("my-project-123456", "spike_event").where(unit_id=106) + # Only a window of a column, half-open: col("timestamp") >= start and < stop + source = SpiralDBTableSource("my-project-123456", "spike_event").where( + col("timestamp") >= start, col("timestamp") < stop + ) + # The spike time is a key column (a tag); also offer it as data source = SpiralDBTableSource( "my-project-123456", "spike_event", tags_as_data={"timestamp": "spike_time_us"} @@ -72,7 +77,7 @@ ) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError from orcapod.types import ColumnConfig, Condition -from orcapod.types.condition import check_equality_conditions +from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -133,30 +138,6 @@ def _schema_difference(found: "pa.Schema", expected: "pa.Schema") -> str: ) -def _checked_conditions( - conditions: Mapping[str, object], schema: "pa.Schema" -) -> dict[str, object]: - """Check ``where`` conditions against the table's columns; convert nothing. - - The one rule for condition values, ``check_equality_conditions`` - (``orcapod.types.condition``), which ``Filter`` shares: a value is exactly of its - column's Python type and fits the column's Arrow type. - - Args: - conditions: Column name to value. - schema: The table's columns (system columns removed). - - Returns: - The conditions, in the given order. - - Raises: - ValueError: If a column is not in the table. - TypeError: If a value is not of its column's type, does not fit it, or the - column's type has no equality condition. - """ - return check_equality_conditions(conditions, schema) - - SPIRALDB_SOURCE_ID_HAS_TABLE_ID = True """Whether a SpiralDB default source id ends in ``@
`` (ITL-1154). @@ -247,9 +228,9 @@ class SpiralDBTableSource(RootSource): single column name. If ``None`` (default), the table's primary-key (key-schema) columns are used. system_tag_columns: Additional system-level tag columns. - where: Column name to value, or a ``Condition`` (``orcapod.types``). Only - rows in which every named column equals its value are read; SpiralDB - applies this before any row is transferred. Each value must be exactly of + where: Column name to value, or a ``Condition`` (``orcapod.types``) of + equalities and ranges. Only the rows that meet it are read; SpiralDB + applies it before any row is transferred. Each value must be exactly of its column's Python type (see ``where()``, the same mechanism). limit: Read at most this many rows: the first in key order (after ``where``). asof: Read the table as of this version (microseconds, as SpiralDB's @@ -281,7 +262,8 @@ class SpiralDBTableSource(RootSource): ``where`` column is not in the table, a ``where`` value is ``None``, or ``limit``, ``max_rows`` or ``batch_rows`` is not a positive integer. TypeError: If a ``where`` value is not exactly of its column's Python type or - does not fit its Arrow type. + does not fit its Arrow type, or ``where`` holds anything but equalities and + ranges of integer, timestamp and date columns. InputValidationError: If ``tags_as_data`` names a column that is not a tag column or not a key column, or a new name that is already a column, is given twice, or is reserved for system columns. @@ -519,8 +501,8 @@ def table_id(self) -> str: def where( self, - mapping: "Mapping[str, object] | Condition | None" = None, /, + *conditions: "Mapping[str, object] | Condition | None", **columns: object, ) -> "SpiralDBTableSource": """Return a new source on the same table that reads only the matching rows. @@ -537,12 +519,23 @@ def where( ``tags_as_data``, key columns, source id, label, data context). With a ``limit``, the new source reads the first ``limit`` rows that match. - 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 that - means: 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 inside the pipeline. + Two kinds of condition are taken, all of which must hold: a column equal to a + value (a keyword, a mapping, ``col(c) == v``), and a range of an integer, + timestamp or date column (``col("t") >= start``, ``col("t") < stop``, + ``col("t").between(a, b)``, which includes both ends). Write a window half-open, + ``>= start`` and ``< stop``: adjacent windows then neither overlap nor leave a + gap. Ranges of one column add up, and may select no row; a null meets no + condition. Float ranges are refused for now (ITL-1477). Use ``filter`` for + ranges of unsupported types such as floats and strings. Anything else + (``is_in``, a null test, ``!=``, two columns, ``|``, ``~``) is refused too. + + An equality is sent to SpiralDB as ``column == value``, and which rows it + selects is SpiralDB's own equality, not Orcapod's. For a float column, + ``0.0`` does not select the ``-0.0`` rows. An equality to ``-0.0`` or a NaN is + refused for now (``TypeError``). SpiralDB matches them by their bits, while Orcapod + counts ``-0.0`` equal to ``0.0`` and NaN equal to NaN, so the rows read would + depend on which of two equal values a condition kept. ITL-1480 tracks revisiting + the float refusals. Use ``filter`` to compare these values by Orcapod's rules. A convenience: the arguments are given to ``Condition.of``, which builds the ``Condition`` (``orcapod.types``); the source checks it against its table and @@ -555,26 +548,32 @@ def where( steps (``copy()`` and ``apply_restriction``) on their own. Args: - mapping: Column name to value, or a ``Condition``. Positional only, so - every column name can also be given as a keyword. - **columns: Column name to value, added to ``mapping``. + *conditions: Mappings of column name to value, and conditions (built with + ``col`` or ``Condition.of``). Positional only, so every column name + can also be given as a keyword. + **columns: Column name to value, added to ``conditions``. Returns: The restricted source; its modified time is the moment it was made. Raises: ValueError: If no condition is given, a column is not in the table, a - value is ``None``, a column is given in the mapping and as a keyword - with different values, or a column is already restricted to another - value. + value is ``None``, or a column must equal two different values. TypeError: If a value is not exactly of its column's Python type or does - not fit the column's Arrow type: nothing is converted (a NumPy scalar, - a date given as a string), the column's type takes no equality - condition, or the condition holds anything but equalities (a - comparison, ``is_in``, a null test, ``|`` or ``~``: filter the stream - instead). + not fit the column's Arrow type: nothing is converted, rounded or + clamped (a NumPy scalar, a date given as a string, ``-1`` for an + unsigned column), the column's type takes no such condition, or the + condition holds anything but equalities and ranges (filter the stream + instead), or a column is to equal ``-0.0`` or a NaN (refused for now, + ITL-1480). """ - condition = Condition.of(mapping, **columns) + try: + # As given, before merging: merging may keep 0.0 of 0.0 and -0.0, or + # refuse -0.0 beside another value as two values (ITL-1480). + check_float_equalities(*conditions, **columns) + except TypeError as exc: + raise TypeError(f"SpiralDB table {self._qualified!r}: {exc}") from exc + condition = Condition.of(*conditions, **columns) restricted = self._copy() try: restricted._apply_restriction(condition) @@ -627,29 +626,18 @@ def _apply_restriction(self, condition: Condition) -> None: condition: The condition to add. Raises: - ValueError: If a column is not in the table, or a column is already - restricted to another value. - TypeError: If a value is not of its column's type or does not fit it. + ValueError: If a column is not in the table, or a column must equal two + different values. + TypeError: If the condition holds anything but equalities and ranges, a + range names a column of another type, or a value is not of its + column's type or does not fit it. """ - if not condition.only_equalities: - raise TypeError( - f"where takes equality conditions only today (column=value); " - f"{condition} has others. Filter the stream instead, as a step of " - f"the pipeline: source.filter(...) with the same condition" - ) - _checked_conditions(condition.equalities, self._table_schema) - # A condition keeps a contradiction (it holds for no row), but a restriction - # is pushed down as one value per column: a second value for a column already - # restricted is refused here, as it always was. - for column, value in condition.equalities.items(): - held = self._condition.equalities.get(column, value) - if not Condition.of({column: held}) == Condition.of({column: value}): - raise ValueError( - f"column {column!r} is already restricted to {held!r}; it cannot " - f"also equal {value!r} (a source reads one value per column; filter " - "the stream to state a condition that holds for no row)" - ) - self._condition = self._condition.combined(condition) + check_restriction(condition, self._table_schema) + combined = self._condition.combined(condition) + # Again with the one in force: a column equals one value (ranges add up, and + # a contradiction of ranges is kept: it reads no row). + check_restriction(combined, self._table_schema) + self._condition = combined self._update_modified_time() @property @@ -806,9 +794,18 @@ def _too_large(self, found: str) -> SourceTooLargeError: """Return the error for a read that goes over ``max_rows``.""" return SourceTooLargeError( f"SpiralDB table {self._qualified!r}: {found}, more than " - f"max_rows={self._max_rows}. Read fewer rows with limit= or " - "where={column: value}, or raise max_rows (max_rows=None removes the " - "cap; a pipeline job keeps every row in memory)." + f"max_rows={self._max_rows}{self._under_condition()}. Read fewer rows " + "with limit= or a narrower where= or where(...) (equalities, and ranges " + "such as col(c) >= start, col(c) < stop), or raise max_rows " + "(max_rows=None removes the cap; a pipeline job keeps every row in memory)." + ) + + def _under_condition(self) -> str: + """Return `` under where `` for a restricted source, else nothing.""" + return ( + f" under where {self._condition.text()}" + if not self._condition.is_empty + else "" ) def _key_tokens(self, table: "pa.Table") -> list[str]: @@ -887,7 +884,7 @@ def _read_batches( # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() for batch in table.scan_batches( - where=dict(self._condition.equalities) or None, + where=None if self._condition.is_empty else self._condition, limit=limit, asof=asof, ): diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index bd72e28fe..515dd8692 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -53,6 +53,14 @@ UnrecordedTableSchemaWarning, ) from orcapod.types import ColumnInfo +from orcapod.types.condition import ( + EQUALS, + ColumnOperand, + Condition, + Term, + is_range_type, + timestamp_count, +) from orcapod.utils import arrow_utils from orcapod.utils.warning_utils import outside_orcapod_stacklevel @@ -365,7 +373,7 @@ def _literal(value: Any, arrow_type: pa.DataType) -> Any: 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) + return sp.literal(timestamp_count(value, arrow_type), arrow_type) if ( pa.types.is_string(arrow_type) or pa.types.is_binary(arrow_type) @@ -377,6 +385,58 @@ def _literal(value: Any, arrow_type: pa.DataType) -> Any: return None +_COMPARE = {"<": "lt", "<=": "lte", ">": "gt", ">=": "gte"} +"""The SDK function of each order comparison.""" + + +def _range_predicate( + column: str, operator: str, value: object, arrow_type: pa.DataType +) -> Any: # pyright: ignore[reportExplicitAny] # an SDK expression, untyped + """Return the scan predicate ``column operator value``, applied by SpiralDB. + + Only a column whose values SpiralDB orders as Orcapod does (``is_range_type``: + integers, timestamps, dates); a range is never read and compared here, since it + exists to bound the read. + + Args: + column: The column's name. + operator: ``<``, ``<=``, ``>`` or ``>=``. + value: A bound checked against the column (``check_restriction``). + arrow_type: The column's type as SpiralDB stores it. + + Raises: + ValueError: If the column's type takes no range. + """ + literal = _literal(value, arrow_type) if is_range_type(arrow_type) else None + if literal is None: + raise ValueError( + f"column {column!r} holds {arrow_type}, which takes no range in a scan" + ) + return getattr(sp, _COMPARE[operator])(sp.column(column), literal) + + +def _scan_terms(where: Condition | None) -> list[Term]: + """Return the requirements of a scan's condition, refusing what a scan cannot apply. + + Raises: + ValueError: If a requirement is not a plain column equal to, or ordered against, + a value (``check_restriction`` refuses these before a source reads). + """ + terms: list[Term] = [] + for node in () if where is None else where.root.children: + if not ( + isinstance(node, Term) + and not node.path.fields + and not isinstance(node.value, ColumnOperand) + and (node.operator == EQUALS or node.operator in _COMPARE) + ): + raise ValueError( + f"a scan applies equalities and ranges of a column only; got {where}" + ) + terms.append(node) + return terms + + 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. @@ -465,25 +525,42 @@ def _at(self, asof: int | None) -> Any: def scan_batches( self, *, - where: Mapping[str, object] | None = None, + where: Condition | None = None, limit: int | None = None, asof: int | None = None, ) -> Iterator[pa.RecordBatch]: - """Yield prepared Arrow batches from this resolved table in key order.""" + """Yield prepared Arrow batches from this resolved table in key order. + + Args: + where: Equalities and ranges of columns, all of which must hold + (``SpiralDBConnector.scan_batches``). + limit: Read at most this many matching rows. + asof: Read this version. + + Raises: + ValueError: If ``where`` holds anything else, or a range of a column whose + type takes none. + """ connector = self._connector table = self._at(asof) reading = self._reading(table) predicate = None - local: dict[str, object] = {} - for column, value in (where or {}).items(): + # Every equality compared here, in the order given: two of one column both hold. + local: list[tuple[str, object]] = [] + for term in _scan_terms(where): + column, value = term.path.column, term.value column_type = reading.found.field(column).type + if term.operator != EQUALS: + bound = _range_predicate(column, term.operator, value, column_type) + predicate = bound if predicate is None else sp.and_(predicate, bound) + continue 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 + local.append((column, value)) continue equals = sp.eq(sp.column(column), literal) predicate = equals if predicate is None else sp.and_(predicate, equals) @@ -502,7 +579,7 @@ def scan_batches( if batch is None: return batch = reading.prepare(batch) - for column, value in local.items(): + for column, value in local: batch = batch.filter(_equals(batch.column(column), value)) if local and left is not None: batch = batch.slice(0, left) @@ -874,7 +951,7 @@ def scan_batches( self, table_name: str, *, - where: Mapping[str, object] | None = None, + where: Condition | None = None, limit: int | None = None, asof: int | None = None, ) -> Iterator[pa.RecordBatch]: @@ -888,8 +965,9 @@ def scan_batches( Args: table_name: Plain table name (no dataset prefix). - where: Column name to value. A row is read only if every named column - equals its value. + where: PROVISIONAL. Takes a ``Condition`` accepted by ``check_restriction``. + A row is read only if all equalities and ranges hold. SpiralDB applies + ranges of integer, timestamp or date columns. limit: Read at most this many rows, the first in key order. asof: Read the table as of this version (a ``get_table_version`` value). diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index 0f21f2906..c6c0b37ac 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -67,7 +67,7 @@ """The operator of a ``Term``.""" EQUALS: Operator = "==" -"""The operator of an equality term (``where`` takes only these).""" +"""The operator of an equality term.""" COMPARISONS: frozenset[str] = frozenset({"==", "!=", "<", "<=", ">", ">="}) """The operators that compare a column with a value or with another column.""" @@ -396,6 +396,47 @@ def is_ordered_type(arrow_type: pa.DataType) -> bool: return expected is not None and expected is not bool +_EPOCH_MICROSECONDS = instant_microseconds(datetime(1970, 1, 1, tzinfo=timezone.utc)) +_MICROSECONDS_PER_COUNT = {"s": 1_000_000, "ms": 1_000, "us": 1} + + +def timestamp_count(value: datetime, arrow_type: pa.TimestampType) -> int: + """Return the count of ``arrow_type``'s unit since the epoch that is ``value``. + + Computed from the value's instant (an aware value) or wall time (a naive one) in + integers, never through a ``datetime`` in the column's zone, so an instant with no + Python ``datetime`` in that zone (year 1 east of UTC, year 9999 west of it) is held + when the column's type holds it, and a fraction of a second in an offset counts. + + Args: + value: The value; its kind (aware or naive) is already checked against the + column's zone. + arrow_type: The column's timestamp type. + + Raises: + TypeError: If no count of the unit is the value exactly (a microsecond for + ``timestamp[s]``), or the count is beyond the type's 64-bit range + (``timestamp[ns]`` reaches years 1677 to 2262). + """ + micros = instant_microseconds(value) + if micros is None: + micros = instant_microseconds(value.replace(tzinfo=timezone.utc)) + assert micros is not None and _EPOCH_MICROSECONDS is not None + since_epoch = micros - _EPOCH_MICROSECONDS + if arrow_type.unit == "ns": + count, rest = since_epoch * 1_000, 0 + else: + count, rest = divmod(since_epoch, _MICROSECONDS_PER_COUNT[arrow_type.unit]) + if rest: + raise TypeError(f"holds {arrow_type}, which cannot hold {value!r} exactly") + if not -(2**63) <= count < 2**63: + raise TypeError( + f"holds {arrow_type}, which cannot hold {value!r}: the instant is beyond " + f"the range of a 64-bit count of {arrow_type.unit}" + ) + return count + + def check_value_for_column(value: object, arrow_type: pa.DataType) -> None: """Check one condition value against the Arrow type of its column; convert nothing. @@ -436,6 +477,10 @@ def check_value_for_column(value: object, arrow_type: pa.DataType) -> None: f"holds {arrow_type}, so the value must be " f"{'an aware' if zoned else 'a naive'} datetime; got {value!r}" ) + if isinstance(value, datetime) and pa.types.is_timestamp(arrow_type): + assert isinstance(arrow_type, pa.TimestampType) + timestamp_count(value, arrow_type) + return if isinstance(value, float): # Rounding to the column's precision is how a float column stores any # value, so it is not refused; a finite value beyond its range is. @@ -679,6 +724,150 @@ def check_equality_conditions( return dict(conditions) +def is_range_type(arrow_type: pa.DataType) -> bool: + """Return whether a source's restriction takes a range of a column of ``arrow_type``. + + Integers of every width, timestamps of every unit and zone, and dates: the table + system orders their values as Orcapod does. Float ranges are refused for now + (ITL-1477) because SpiralDB uses IEEE 754 total order. Strings and binary follow + the table system's collation. Use ``filter`` for these ranges. + + Args: + arrow_type: The column's Arrow type. + + Returns: + Whether a range of the column can be a restriction. + """ + return ( + pa.types.is_integer(arrow_type) + or pa.types.is_timestamp(arrow_type) + or pa.types.is_date(arrow_type) + ) + + +_RESTRICTION_FORMS = ( + "where takes equalities (column=value) and ranges (col(c) >= a, col(c) < b, " + "col(c).between(a, b)), all of which must hold" +) +_TO_FILTER = ( + "Filter the stream instead, as a step of the pipeline: source.filter(...) with the " + "same condition" +) + + +def check_restriction(condition: Condition, schema: pa.Schema) -> None: + """Check a source's restriction against its table's columns; convert nothing. + + A restriction is applied by the table system, so it takes only what the table + system tests as Orcapod would: a column equal to a value, and a range (``<``, + ``<=``, ``>``, ``>=``; ``between`` is two of them) of an integer, timestamp or date + column (``is_range_type``). All must hold. A column equals one value; ranges add + up and may select no row. Every value passes ``check_value_for_column``: exactly + of its column's Python type, held exactly by its column's Arrow type. + + Args: + condition: The condition. + schema: The table's columns (system columns removed). + + Raises: + ValueError: If a column is not in the table, or must equal two values. + TypeError: If the condition holds anything else, a range names a column of + another type, a value is not of its column's type or does not fit it, + or a column is to equal ``-0.0`` or a NaN (``check_float_equalities``). + """ + terms: list[Term] = [] + for node in condition.root.children: + if not ( + isinstance(node, Term) + and not node.path.fields + and not isinstance(node.value, ColumnOperand) + and (node.operator == EQUALS or node.operator in ORDER_COMPARISONS) + ): + raise TypeError( + f"{_RESTRICTION_FORMS}; {condition} has others. {_TO_FILTER}" + ) + terms.append(node) + unknown = list( + dict.fromkeys(t.path.column for t in terms if t.path.column not in schema.names) + ) + if unknown: + raise ValueError( + f"where names columns that the table does not have: {unknown}. " + f"Columns: {schema.names}" + ) + equal_to: dict[str, object] = {} + for term in terms: + column, value = term.path.column, term.value + arrow_type = schema.field(column).type + if term.operator != EQUALS and not is_range_type(arrow_type): + raise TypeError( + f"column {column!r} holds {arrow_type}; where takes a range of an " + f"integer, timestamp or date column only. {_TO_FILTER}" + ) + try: + check_value_for_column(value, arrow_type) + except TypeError as exc: + raise TypeError(f"column {column!r} {exc}") from exc + if term.operator != EQUALS: + continue + check_float_equalities({column: value}) + held = equal_to.setdefault(column, value) + if not _same_condition_value(held, value): + raise ValueError( + f"column {column!r} is already restricted to {held!r}; it cannot " + f"also equal {value!r} (a source reads one value per column; filter " + "the stream to state a condition that holds for no row)" + ) + + +def _matched_by_bits(value: object) -> bool: + """Return whether ``value`` is a float the table system and Orcapod match apart.""" + return isinstance(value, float) and ( + math.isnan(value) or (value == 0.0 and math.copysign(1.0, value) < 0) + ) + + +def check_float_equalities( + *conditions: Mapping[str, object] | Condition | None, **columns: object +) -> None: + """For now, refuse equality to ``-0.0`` or NaN before merging (ITL-1480). + + Orcapod counts ``-0.0`` equal to ``0.0`` and NaN equal to NaN, so ``Condition.of`` + and ``combined`` keep one of two such values; SpiralDB matches a float by its bits + (``-0.0`` only ``-0.0``, a NaN only its own bit pattern). The rows read would then + depend on which of two equal values was kept, so neither is taken. Checked on the + arguments as given (each mapping, each condition's top-level equalities, the + keywords), since merging may already have dropped one; every other float + equality is handled as before. Float ranges are refused for now by + ``check_restriction`` (ITL-1477). + + Args: + *conditions: The mappings and conditions given to ``where``. + **columns: The keywords given to ``where``. + + Raises: + TypeError: If a column is to equal ``-0.0`` or a NaN. + """ + given: list[tuple[object, object]] = list(columns.items()) + for argument in conditions: + if isinstance(argument, Condition): + given.extend( + (node.path.column, node.value) + for node in argument.root.children + if isinstance(node, Term) and node.operator == EQUALS + ) + elif isinstance(argument, Mapping): + given.extend(argument.items()) + for column, value in given: + if _matched_by_bits(value): + raise TypeError( + f"column {column!r}: where takes no equality to {value!r}. SpiralDB " + "matches -0.0 and NaN by their bits, while Orcapod counts -0.0 equal " + "to 0.0 and NaN equal to NaN, so which rows are read would depend on " + f"which of two equal values was kept (ITL-1480). {_TO_FILTER}" + ) + + # ----------------------------------------------------------------------------- # Building conditions: col(name) # ----------------------------------------------------------------------------- @@ -956,7 +1145,7 @@ class Condition: not. ``Condition.of`` builds the equalities ``where()`` takes; ``col(name)`` builds the rest; ``&``, ``|`` and ``~`` combine conditions. It knows nothing of a source, a limit or an identity. A source uses one to choose which of its rows are read - (``SpiralDBTableSource.where``, ITL-1218: equalities only), a restriction in no hash; + (``SpiralDBTableSource.where``: equalities and ranges), a restriction in no hash; the ``Filter`` operator takes one as a step of the pipeline, its identity the condition's ``canonical_form()`` (ITL-1374). @@ -1016,6 +1205,7 @@ def _of_children(cls, children: tuple[Node, ...]) -> Condition: @classmethod def of( cls, + /, *conditions: Mapping[str, object] | Condition | None, **columns: object, ) -> Condition: @@ -1135,7 +1325,7 @@ def is_empty(self) -> bool: @property def only_equalities(self) -> bool: - """Whether every requirement is a column equal to a value (``where`` takes only these). + """Whether every requirement is a column equal to a value. True for the empty condition. A field of a struct, or a comparison of two columns, is not an equality in this sense. @@ -1302,7 +1492,9 @@ def canonical_text(self) -> str: def to_config(self) -> dict[str, object]: """Return the condition as it is saved, JSON-ready. - Only equalities: column name to value, as before (a date, datetime or bytes value + In canonical order (the order ``canonical_form`` sorts the requirements), so + equal conditions are saved alike, whatever order they were given in (ITL-998). + Only equalities: column name to value (a date, datetime or bytes value written as ``{"date": iso}``, ``{"datetime": iso}`` or ``{"bytes": hex}``, a NaN or infinite float as ``{"float": "nan"}``, ``{"float": "inf"}`` or ``{"float": "-inf"}``, any other value as it is). Anything else: one key, @@ -1318,8 +1510,9 @@ def to_config(self) -> dict[str, object]: if not self.only_equalities: return {_TREE_KEY: _node_to_config(self._root)} return { - column: _condition_value_to_config(value) - for column, value in self.equalities.items() + node.path.column: _condition_value_to_config(node.value) + for node in _canonically_sorted(self._root.children) + if isinstance(node, Term) } @classmethod diff --git a/tests/test_core/operators/test_filter.py b/tests/test_core/operators/test_filter.py index dc2663887..d901a0c98 100644 --- a/tests/test_core/operators/test_filter.py +++ b/tests/test_core/operators/test_filter.py @@ -9,6 +9,7 @@ from __future__ import annotations import itertools +import json import struct import warnings from decimal import Decimal @@ -391,6 +392,19 @@ def test_round_trip(self, condition: Condition): assert rebuilt.content_hash() == op.content_hash() assert _kept(rebuilt(_units())) == _kept(op(_units())) + def test_equalities_are_saved_in_canonical_order(self): + """The saved form never follows the order given (ITL-998, ITL-1271); a config + saved in the order given loads to the same operator.""" + forward = Filter(Condition.of(session="s1", probe="imec0")) + backward = Filter(Condition.of(probe="imec0", session="s1")) + + assert json.dumps(forward.to_config()) == json.dumps(backward.to_config()) + assert list(forward.to_config()["config"]["condition"]) == ["probe", "session"] + earlier = forward.to_config() + earlier["config"]["condition"] = {"session": "s1", "probe": "imec0"} + rebuilt = _build_operator_registry()["Filter"].from_config(earlier) + assert rebuilt.content_hash() == forward.content_hash() + class TestProvisional: def test_listed_and_marked(self): diff --git a/tests/test_core/operators/test_filter_pipeline.py b/tests/test_core/operators/test_filter_pipeline.py index 01f35c2a2..16b5db26c 100644 --- a/tests/test_core/operators/test_filter_pipeline.py +++ b/tests/test_core/operators/test_filter_pipeline.py @@ -294,22 +294,29 @@ def test_a_filter_reads_what_the_source_selects( @pytest.mark.parametrize( "value, alone, with_where", [ - (float("nan"), [1, 3], [1, 3]), - (-0.0, [4, 5], [4]), + (float("nan"), [1, 3], None), + (-0.0, [4, 5], None), + (0.0, [4, 5], [5]), (2.0, [6], [6]), ], - ids=["NaN", "signed zero", "ordinary float"], + ids=["NaN", "negative zero", "zero", "ordinary float"], ) def test_where_and_filter_on_a_float_column(project, value, alone, with_where): """CodeRabbit on PR 493 (spec 483, Major) and PR 498 (sources.md:447, operators.md:861): - ``filter`` matches floats by Orcapod's rule (NaN equals NaN); ``where`` by the table - system's equality (SpiralDB's, as measured on the service: NaN equals NaN and 0.0 does - not equal -0.0), so ``where`` plus ``filter`` can keep fewer rows than the ``filter`` - alone, and only for a zero.""" + ``filter`` matches floats by Orcapod's rule (NaN equals NaN, -0.0 equals 0.0); + ``where`` by the table system's equality (SpiralDB's, as measured on the service: + 0.0 does not equal -0.0), so ``where`` plus ``filter`` can keep fewer rows than the + ``filter`` alone, and only for a zero. ``where`` refuses -0.0 and NaN (ITL-1480): + SpiralDB matches them by their bits.""" assert _timestamps(_events().filter(reading=value)) == alone - assert ( - _timestamps(_events().where(reading=value).filter(reading=value)) == with_where - ) + if with_where is None: + with pytest.raises(TypeError, match="ITL-1480"): + _events().where(reading=value) + else: + assert ( + _timestamps(_events().where(reading=value).filter(reading=value)) + == with_where + ) @pytest.mark.parametrize( diff --git a/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py b/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py new file mode 100644 index 000000000..1f085a5db --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py @@ -0,0 +1,179 @@ +"""A SpiralDB ``where`` refuses a float equality to ``-0.0`` or NaN (ITL-998, ITL-1480). + +Orcapod counts ``-0.0`` equal to ``0.0`` and NaN equal to NaN, so ``Condition.of`` and +``combined`` keep one of two such values. SpiralDB matches a float by its bits (the +live probe, November 26, 2026): ``-0.0`` reads only ``-0.0`` and a NaN only its own bit +pattern. Which rows a source read would then depend on which equal value was kept +(independent review of d4115197): ``where(col("id") >= 0, {"v": -0.0}, v=0.0)`` read +one row and the signs reversed another, under identical conditions, canonical forms +and saved JSON. Such a value is refused, pointing to ``filter``; every other float +equality is pushed down as before. Runs on the fake only. +""" + +from __future__ import annotations + +import asyncio +import math +import struct +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.sources import SpiralDBTableSource +from orcapod.types import Condition, col +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "workshop-sample" +_NEGATIVE_NAN = struct.unpack(" pa.Table: + """Return rows with both zeros, a NaN of each sign, and ordinary values.""" + return pa.table( + { + "id": pa.array([0, 1, 2, 3, 4, 5], pa.int64()), + "lab": pa.array(["a", "a", "b", "b", "c", "c"], pa.large_string()), + "v": pa.array( + [-0.0, 0.0, math.nan, _NEGATIVE_NAN, 1.5, math.inf], pa.float64() + ), + "g": pa.array([-0.0, 0.0, math.nan, 2.5, 1.5, -math.inf], pa.float32()), + "n": pa.array([10, 11, 12, 13, 14, 15], pa.int32()), + } + ) + + +@pytest.fixture() +def project(tmp_path: Path): + """Provide a fake project holding the ``zeros`` table.""" + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) + project.create_table("default.zeros", key_schema=_KEYS).write(_table()) + fake_spiral_sdk.scan_log.clear() + yield project + fake_spiral_sdk.scan_log.clear() + + +def _source(**kwargs: Any) -> SpiralDBTableSource: + """Return a source over ``zeros``, tags kept tag-only.""" + return SpiralDBTableSource(_PROJECT, "zeros", tag_only_columns=True, **kwargs) + + +def _ids(source: SpiralDBTableSource) -> list[Any]: + """Return the ``id`` of every row ``source`` reads (sync).""" + return source.as_table()["id"].to_pylist() + + +def _async_ids(source: SpiralDBTableSource) -> list[Any]: + """Return the ``id`` of every row ``source`` reads (async).""" + + async def collect() -> list[Any]: + return [tag.as_dict()["id"] async for tag, _ in source.async_iter_data()] + + return asyncio.run(asyncio.wait_for(collect(), timeout=60)) + + +def _forms( + refused: float, other: float, column: str +) -> dict[str, Callable[[], SpiralDBTableSource]]: + """Return every way of giving ``column == refused``, alone or beside ``other``.""" + rng = col("id") >= 0 + return { + "keyword": lambda: _source().where(**{column: refused}), + "mapping": lambda: _source().where({column: refused}), + "col": lambda: _source().where(col(column) == refused), + "Condition.of": lambda: _source().where(Condition.of({column: refused})), + "range, mapping refused, keyword other": lambda: _source().where( + rng, {column: refused}, **{column: other} + ), + "range, mapping other, keyword refused": lambda: _source().where( + rng, {column: other}, **{column: refused} + ), + "keyword refused, range": lambda: _source().where( + {column: refused}, rng, **{column: other} + ), + "two mappings, refused first": lambda: _source().where( + {column: refused}, {column: other} + ), + "two mappings, refused last": lambda: _source().where( + {column: other}, {column: refused} + ), + "col other, mapping refused": lambda: _source().where( + col(column) == other, {column: refused} + ), + "mapping refused, col other": lambda: _source().where( + {column: refused}, col(column) == other + ), + "with another column": lambda: _source().where(n=11, **{column: refused}), + "chained, refused first": lambda: ( + _source().where(**{column: refused}).where(**{column: other}) + ), + "chained, refused last": lambda: ( + _source().where(**{column: other}).where(**{column: refused}) + ), + "where= mapping": lambda: _source(where={column: refused, "n": 11}), + "where= condition": lambda: _source(where=Condition.of(rng, {column: refused})), + } + + +_CASES = [ + (column, refused, other, form) + for column in ("v", "g") + for refused, other in ((-0.0, 0.0), (math.nan, math.nan), (_NEGATIVE_NAN, math.nan)) + for form in _forms(refused, other, column) +] + + +class TestRefused: + @pytest.mark.parametrize( + ("column", "refused", "other", "form"), + _CASES, + ids=[ + f"{c}-{'-0.0' if r == 0 else ('-nan' if math.copysign(1, r) < 0 else 'nan')}" + f"-{f}" + for c, r, _, f in _CASES + ], + ) + def test_an_equality_to_negative_zero_or_nan_is_refused( + self, project, column, refused, other, form + ): + """Every form, both orders, keywords and mappings: refused before any scan.""" + with pytest.raises(TypeError, match=r"ITL-1480.*filter") as raised: + _forms(refused, other, column)[form]() + + assert repr(column) in str(raised.value) + assert fake_spiral_sdk.scan_log == [] + + @pytest.mark.parametrize("signs", [(-0.0, 0.0), (0.0, -0.0)], ids=["-+", "+-"]) + def test_the_reviewed_case_no_longer_depends_on_the_sign_kept(self, project, signs): + """The finding: both orders used to read different rows under one condition.""" + first, second = signs + with pytest.raises(TypeError, match="ITL-1480"): + _source().where(col("id") >= 0, {"v": first}, v=second) + + +class TestEveryOtherFloatEqualityAsBefore: + @pytest.mark.parametrize( + ("where", "expected"), + [ + ({"v": 0.0}, [1]), + ({"v": 1.5}, [4]), + ({"v": math.inf}, [5]), + ({"g": 0.0}, [1]), + ({"g": 1.5}, [4]), + ({"g": -math.inf}, [5]), + ({"v": 0.0, "n": 11}, [1]), + ({"n": 14, "v": 1.5}, [4]), + ], + ) + def test_pushed_down_with_the_services_equality(self, project, where, expected): + """``0.0`` reads only ``+0.0`` (the service's equality, documented); sync and + async read the same rows, keywords and a mapping alike.""" + for source in (_source().where(where), _source().where(**where)): + assert _ids(source) == expected + assert _async_ids(source) == expected + pushed = dict(fake_spiral_sdk.scan_log[-1].kwargs["where"].equalities) + assert set(pushed) == set(where) diff --git a/tests/test_core/sources/test_spiraldb_table_source_live.py b/tests/test_core/sources/test_spiraldb_table_source_live.py index e705f5e6c..bc89fb2da 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_live.py +++ b/tests/test_core/sources/test_spiraldb_table_source_live.py @@ -14,10 +14,13 @@ import os import time from pathlib import Path +from typing import Any +import pyarrow as pa +import pyarrow.compute as pc import pytest -from orcapod import PipelineJob, function_pod +from orcapod import PipelineJob, col, function_pod from orcapod.databases import DeltaTableDatabase from orcapod.errors import SourceTooLargeError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator @@ -165,3 +168,77 @@ def test_tags_as_data_gives_each_unit_its_spike_times_in_time_order(): assert sum(len(r["spike_time_us"]) for r in rows) == spikes.as_table().num_rows for row in rows: assert row["spike_time_us"] == sorted(row["spike_time_us"]) + + +def _one_unit() -> tuple[SpiralDBTableSource, list[Any]]: + """Return a source on the first unit's rows, and that unit's sorted timestamps. + + The unit is every key column of the first row but ``timestamp`` (CodeRabbit on + PR 574): ``unit_id`` alone can name units of several sessions or probes, whose + timestamps the scan reads one group after another, not in one sorted run. + """ + first = SpiralDBTableSource(PROJECT, "spike_event", limit=1, tag_only_columns=True) + row = first.as_table().to_pylist()[0] + unit_key = {c: row[c] for c in first.keys()[0] if c != "timestamp"} + unit = SpiralDBTableSource( + PROJECT, "spike_event", max_rows=None, tag_only_columns=True + ).where(unit_key) + times: list[Any] = sorted( + t for t in unit.as_table().column("timestamp").to_pylist() if t is not None + ) + if len(times) < 8: + pytest.skip("the first unit holds too few rows for a window") + return unit, times + + +def test_a_window_reads_the_rows_a_local_filter_keeps(): + """A window of ``timestamp`` (with the unit's equality) reads exactly the rows of + the whole unit that pyarrow keeps, with their record ids, in either argument order + (ITL-998).""" + unit, times = _one_unit() + start, stop = times[len(times) // 4], times[len(times) // 2] + whole = unit.as_table(all_info=True) + kind = whole.schema.field("timestamp").type + expected = whole.filter( + pc.and_( + pc.greater_equal(whole["timestamp"], pa.scalar(start, kind)), + pc.less(whole["timestamp"], pa.scalar(stop, kind)), + ) + ) + + for bounds in ( + (col("timestamp") >= start, col("timestamp") < stop), + (col("timestamp") < stop, col("timestamp") >= start), + ): + window = unit.where(*bounds) + assert window.as_table(all_info=True).equals(expected) + assert window.content_hash() == unit.content_hash() + assert expected.num_rows > 0 + + +def test_a_window_with_a_limit_and_head_reads_its_first_rows(): + unit, times = _one_unit() + window = unit.where(col("timestamp") >= times[2]) + + first = window.as_table()["timestamp"].to_pylist() + assert first == [t for t in times if t >= times[2]] + assert ( + unit.where(col("timestamp") >= times[2]) + .head(3) + .as_table()["timestamp"] + .to_pylist() + == first[:3] + ) + limited = SpiralDBTableSource( + PROJECT, "spike_event", limit=2, max_rows=None, tag_only_columns=True + ).where(unit.condition, col("timestamp") >= times[2]) + assert limited.as_table()["timestamp"].to_pylist() == first[:2] + + +def test_an_empty_window_reads_no_row_with_the_full_schema(): + unit, times = _one_unit() + empty = unit.where(col("timestamp") >= times[3], col("timestamp") < times[3]) + + table = empty.as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema == unit.as_table(all_info=True).schema diff --git a/tests/test_core/sources/test_spiraldb_table_source_ranges.py b/tests/test_core/sources/test_spiraldb_table_source_ranges.py new file mode 100644 index 000000000..7d8ad21c8 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_ranges.py @@ -0,0 +1,775 @@ +"""``SpiralDBTableSource.where()`` takes ranges of a column (ITL-998). + +A range is a restriction like an equality (ITL-1218): SpiralDB applies it in the scan, and +it changes no identity, schema, system tag or record id. Every expected row set here is +what pyarrow selects from the same table. Runs against the disk-backed pyspiral fake. +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +import functools +import itertools +import json +import operator +from collections.abc import Callable +from decimal import Decimal +from pathlib import Path +from typing import Any + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import SourceTooLargeError +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.sources import SpiralDBTableSource +from orcapod.types import Condition, col +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "workshop-sample" +_UTC = dt.timezone.utc +_T0 = dt.datetime(2026, 11, 1, tzinfo=_UTC) +_WALL = dt.datetime(2026, 11, 1, 6, 30) +_DAY = dt.date(2026, 11, 1) +_MS_PER_DAY = 86_400_000 +_Key = tuple[Any, Any] +"""A row's ``(unit, at)`` key.""" + + +def _table() -> pa.Table: + """Return the ``ranges`` rows: two key columns and data of every range type. + + ``v`` and ``d`` hold nulls; ``w`` holds nanoseconds between two microseconds; + ``d64`` holds values that are not midnight. The other columns are of the types a + range refuses. + """ + n = 12 + w0 = int(dt.datetime(2026, 11, 1, 6, 30, tzinfo=_UTC).timestamp()) * 10**9 + return pa.table( + { + "unit": pa.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], pa.int32()), + "at": pa.array( + [_T0 + dt.timedelta(minutes=90 * i) for i in range(n)], + pa.timestamp("us", tz="UTC"), + ), + "v": pa.array( + [5, None, -3, 7, 7, 0, None, 12, -8, 3, 100, -100], pa.int64() + ), + "n": pa.array([0, 255, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], pa.uint8()), + "d": pa.array( + [ + _DAY + dt.timedelta(days=i % 5 - 2) if i != 4 else None + for i in range(n) + ], + pa.date32(), + ), + "w": pa.array( + [ + w0 + delta + for delta in ( + 0, + 1, + 999, + 1000, + 1001, + -1, + -1000, + 0, + 5, + 2000, + 10**9, + -(10**9), + ) + ], + pa.int64(), + ).view(pa.timestamp("ns")), + "d64": pa.array( + [ + (i % 4) * _MS_PER_DAY + (i % 3) * 3_600_000 + 20_000 * _MS_PER_DAY + for i in range(n) + ], + pa.int64(), + ).view(pa.date64()), + "sec": pa.array( + [int(_T0.timestamp()) + 60 * i for i in range(n)], pa.int64() + ).view(pa.timestamp("s")), + "x": pa.array([float(i) - 5.5 for i in range(n)], pa.float64()), + "g": pa.array([float(i) for i in range(n)], pa.float32()), + "h": pa.array(np.arange(n, dtype=np.float16), pa.float16()), + "s": [f"s{i:02d}" for i in range(n)], + "b": [bytes([i]) for i in range(n)], + "f": [i % 2 == 0 for i in range(n)], + "dec": pa.array([Decimal(i) for i in range(n)], pa.decimal128(5, 0)), + } + ) + + +_KEYS = pa.schema( + [pa.field("unit", pa.int32()), pa.field("at", pa.timestamp("us", tz="UTC"))] +) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Provide a fake project holding the 12-row ``ranges`` table, 4 rows per batch.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 4) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) + project.create_table("default.ranges", key_schema=_KEYS).write(_table()) + fake_spiral_sdk.scan_log.clear() + yield project + fake_spiral_sdk.scan_log.clear() + + +def _source(**kwargs: Any) -> SpiralDBTableSource: + """Return a source over ``ranges``, tags kept tag-only unless ``kwargs`` says.""" + kwargs.setdefault("tag_only_columns", True) + return SpiralDBTableSource(_PROJECT, "ranges", **kwargs) + + +def _keys(source: SpiralDBTableSource) -> list[_Key]: + """Return the ``(unit, at)`` key of every row ``source`` reads, in order.""" + table = source.as_table() + return list(zip(table["unit"].to_pylist(), table["at"].to_pylist())) + + +def _expected(*masks: Any) -> list[_Key]: + """Return the keys of the rows where every pyarrow mask holds (a null holds not).""" + table = _table() + keep = functools.reduce(pc.and_, [pc.fill_null(m, False) for m in masks]) + kept = table.filter(keep) + return list(zip(kept["unit"].to_pylist(), kept["at"].to_pylist())) + + +def _scalar(column: str, value: Any) -> pa.Scalar[Any]: + """Return ``value`` as a pyarrow scalar of ``column``'s type.""" + return pa.scalar(value, _table().schema.field(column).type) + + +_OPERATORS: dict[str, tuple[Callable[[Any, Any], Any], Any]] = { + "<": (operator.lt, pc.less), + "<=": (operator.le, pc.less_equal), + ">": (operator.gt, pc.greater), + ">=": (operator.ge, pc.greater_equal), +} + +# Bounds per range column: a stored value or one between, at and beyond both ends. +_BOUNDS: dict[str, list[Any]] = { + "unit": [0, 1, 2, 4, 5], + "at": [ + _T0, + _T0 + dt.timedelta(minutes=100), + _T0 + dt.timedelta(hours=16, minutes=30), + ], + "v": [-100, -3, 0, 7, 100], + "n": [0, 5, 255], + "d": [_DAY - dt.timedelta(days=2), _DAY, _DAY + dt.timedelta(days=2)], + "w": [ + _WALL - dt.timedelta(microseconds=1), + _WALL, + _WALL + dt.timedelta(microseconds=1), + ], + "d64": [ + dt.date(1970, 1, 1) + dt.timedelta(days=20_000), + dt.date(1970, 1, 1) + dt.timedelta(days=20_001), + dt.date(1970, 1, 1) + dt.timedelta(days=20_003), + ], + "sec": [_T0, _T0 + dt.timedelta(minutes=5)], +} + + +def _pyarrow_bound(column: str, value: Any) -> pa.Scalar[Any]: + """Return a bound as the column's scalar (``w`` and ``sec`` are naive in UTC).""" + if column == "sec" and isinstance(value, dt.datetime): + return _scalar(column, value.replace(tzinfo=None)) + return _scalar(column, value) + + +def _bound(column: str, value: Any) -> Any: + """Return a bound as ``where`` takes it (``sec`` is naive).""" + if column == "sec": + return value.replace(tzinfo=None) + return value + + +_CASES = [ + (column, op, value) + for column, values in _BOUNDS.items() + for op in _OPERATORS + for value in values +] + + +class TestRows: + """Each operator and ``between``, on every range type, reads pyarrow's rows.""" + + @pytest.mark.parametrize(("column", "op", "value"), _CASES) + def test_each_operator(self, project, column, op, value): + python_op, arrow_op = _OPERATORS[op] + condition = python_op(col(column), _bound(column, value)) + expected = _expected(arrow_op(_table()[column], _pyarrow_bound(column, value))) + + assert _keys(_source().where(condition)) == expected + + @pytest.mark.parametrize("column", list(_BOUNDS)) + def test_between_includes_both_ends(self, project, column): + values = _BOUNDS[column] + for low, high in itertools.combinations_with_replacement(values, 2): + expected = _expected( + pc.greater_equal(_table()[column], _pyarrow_bound(column, low)), + pc.less_equal(_table()[column], _pyarrow_bound(column, high)), + ) + restricted = _source().where( + col(column).between(_bound(column, low), _bound(column, high)) + ) + assert _keys(restricted) == expected + + def test_a_half_open_window_and_its_neighbour_share_no_row(self, project): + """``>= a`` and ``< b``: adjacent windows neither overlap nor leave a gap.""" + cut = _T0 + dt.timedelta(hours=6) + before = _keys(_source().where(col("at") < cut)) + after = _keys(_source().where(col("at") >= cut)) + + assert not set(before) & set(after) + assert sorted(before + after) == _keys(_source()) + + def test_both_ends_of_an_integer_type(self, project): + assert _keys(_source().where(col("n") >= 0, col("n") <= 255)) == _keys( + _source() + ) + assert _keys(_source().where(col("n") > 255)) == [] + assert _keys(_source().where(col("v") >= -(2**63), col("v") < 2**63 - 1)) == ( + _expected(pc.is_valid(_table()["v"])) + ) + + def test_a_null_meets_no_comparison(self, project): + """A null ``v`` is in no range, whatever the operator.""" + nulls = { + key + for key, v in zip(_keys(_source()), _table()["v"].to_pylist()) + if v is None + } + for op in _OPERATORS.values(): + assert not nulls & set(_keys(_source().where(op[0](col("v"), 0)))) + + @pytest.mark.parametrize( + "build", + [ + lambda: (col("unit") >= 3, col("unit") < 2), + lambda: (col("unit") >= 3, col("unit") < 3), + lambda: (col("v") > 100,), + lambda: (Condition.of(unit=1), col("unit") >= 3), + ], + ids=["reversed", "start equals stop", "beyond", "equality outside"], + ) + def test_a_window_that_holds_no_row_reads_none(self, project, build): + """Kept, not refused (D3): zero rows, with the full schema.""" + restricted = _source().where(*build()) + + table = restricted.as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema == _source().as_table(all_info=True).schema + + def test_the_bounds_reach_the_scan_with_the_column_type(self, project): + """SpiralDB compares only a literal of the column's own type.""" + _source().where( + col("n") >= 2, col("at") < _T0 + dt.timedelta(hours=9) + ).as_table() + + terms = fake_spiral_sdk.scan_log[-1].kwargs["where"].terms + assert {(name, op, lit.type) for name, lit, op in terms} == { + ("n", ">=", pa.uint8()), + ("at", "<", pa.timestamp("us", tz="UTC")), + } + + +def _parts() -> list[Condition]: + """Four parts of one restriction: ranges of two columns, a between, an equality.""" + return [ + col("unit") >= 2, + col("at") < _T0 + dt.timedelta(hours=14), + col("v").between(-5, 50), + Condition.of(f=False), + ] + + +def _expected_parts() -> list[_Key]: + """Return the rows ``_parts()`` selects, as pyarrow selects them.""" + return _expected( + pc.greater_equal(_table()["unit"], _scalar("unit", 2)), + pc.less(_table()["at"], _scalar("at", _T0 + dt.timedelta(hours=14))), + pc.greater_equal(_table()["v"], _scalar("v", -5)), + pc.less_equal(_table()["v"], _scalar("v", 50)), + pc.equal(_table()["f"], pa.scalar(False)), + ) + + +_FORMS: dict[str, Callable[[list[Condition]], SpiralDBTableSource]] = { + "arguments": lambda parts: _source().where(*parts), + "&": lambda parts: _source().where(functools.reduce(operator.and_, parts)), + "combined": lambda parts: _source().where( + functools.reduce(lambda a, b: a.combined(b), parts) + ), + "chained": lambda parts: functools.reduce( + lambda source, part: source.where(part), parts, _source() + ), + "constructor then where": lambda parts: _source(where=parts[0]).where(*parts[1:]), +} + + +class TestSeveralItemsInEveryOrder: + """Every order of the parts, in every form, is one restriction (D7, D8).""" + + @pytest.mark.parametrize("form", list(_FORMS)) + def test_every_order_reads_the_same_rows_and_saves_the_same_bytes( + self, project, form + ): + reference = _source().where(*_parts()) + expected_rows = _expected_parts() + saved = json.dumps(reference.to_config()["where"]) + for order in itertools.permutations(range(4)): + parts = [_parts()[i] for i in order] + restricted = _FORMS[form](parts) + + assert _keys(restricted) == expected_rows, order + assert restricted.condition == reference.condition + assert hash(restricted.condition) == hash(reference.condition) + assert ( + restricted.condition.canonical_form() + == reference.condition.canonical_form() + ) + assert json.dumps(restricted.to_config()["where"]) == saved + loaded = SpiralDBTableSource.from_config( + json.loads(json.dumps(restricted.to_config())) + ) + assert loaded.condition == reference.condition + + def test_the_text_keeps_the_order_given(self, project): + """``text()`` is display, in the order given; the saved form is canonical.""" + forward = _source().where(*_parts()) + backward = _source().where(*reversed(_parts())) + + assert forward.condition.text().startswith("unit >= 2") + assert backward.condition.text().startswith("f=False") + assert forward.to_config() == backward.to_config() + + @pytest.mark.parametrize( + "build", + [ + lambda: _source().where({"f": False}, *_parts()[:3]), + lambda: _source().where(*_parts()[:3], f=False), + lambda: _source().where(_parts()[2], {"f": False}, *_parts()[:2]), + lambda: _source(where={"f": False}).where(*_parts()[:3]), + ], + ids=["mapping first", "keyword last", "mapping between", "constructor mapping"], + ) + def test_mappings_and_keywords_are_the_same_equality(self, project, build): + restricted = build() + + assert restricted.condition == _source().where(*_parts()).condition + assert _keys(restricted) == _expected_parts() + + def test_two_ranges_of_one_column_add_up(self, project): + restricted = _source().where(col("v") >= -5, col("v") >= 0, col("v") < 12) + + assert _keys(restricted) == _expected( + pc.greater_equal(_table()["v"], _scalar("v", 0)), + pc.less(_table()["v"], _scalar("v", 12)), + ) + + def test_redundant_bounds_are_kept(self, project): + """No simplification (D7): ``v >= 0`` and ``v > -1`` are two restrictions.""" + assert _source().where(col("v") >= 0).condition != ( + _source().where(col("v") > -1).condition + ) + both = _source().where(col("v") >= 0, col("v") > -1).condition + assert len(list(both.terms())) == 2 + + +class TestRoles: + """A range of each kind of column, on the sync and the async path.""" + + @staticmethod + def _both_paths(source: SpiralDBTableSource) -> tuple[list[Any], list[Any]]: + """Return the rows (every column) the sync and the async read yield.""" + + async def collect() -> list[dict[str, Any]]: + return [ + {**tag.as_dict(all_info=True), **data.as_dict(all_info=True)} + async for tag, data in source.async_iter_data() + ] + + sync = [ + {**tag.as_dict(all_info=True), **data.as_dict(all_info=True)} + for tag, data in source.iter_data() + ] + return sync, asyncio.run(collect()) + + @pytest.mark.parametrize( + ("build", "masks"), + [ + ( + lambda: col("unit") >= 3, + lambda t: [pc.greater_equal(t["unit"], pa.scalar(3, pa.int32()))], + ), + ( + lambda: col("at") < _T0 + dt.timedelta(hours=6), + lambda t: [ + pc.less(t["at"], _scalar("at", _T0 + dt.timedelta(hours=6))) + ], + ), + ( + lambda: col("v") <= 5, + lambda t: [pc.less_equal(t["v"], pa.scalar(5, pa.int64()))], + ), + ], + ids=["first key", "last key", "data with nulls"], + ) + @pytest.mark.parametrize("tag_only", [True, False], ids=["tags", "data-tags"]) + def test_sync_and_async_read_the_same_rows(self, project, build, masks, tag_only): + source = _source(tag_only_columns=tag_only).where(build()) + + sync, asynchronous = self._both_paths(source) + + assert asynchronous == sync + assert [(r["unit"], r["at"]) for r in sync] == _expected(*masks(_table())) + + def test_a_key_offered_as_data_is_restricted_by_its_table_name(self, project): + """With ``tags_as_data``, the range names the table's column, not the copy.""" + source = _source(tags_as_data={"at": "at_copy"}, source_id="ranges") + restricted = source.where(col("at") < _T0 + dt.timedelta(hours=3)) + + assert restricted.as_table()["at_copy"].to_pylist() == [ + _T0, + _T0 + dt.timedelta(minutes=90), + ] + with pytest.raises(ValueError, match="at_copy"): + source.where(col("at_copy") < _T0) + + +class TestRefusals: + """Everything a range does not take is refused before any scan.""" + + @pytest.mark.parametrize( + ("column", "value"), + [ + ("x", 0.5), + ("g", 1.0), + ("h", 1.0), + ("s", "s03"), + ("b", b"\x03"), + ("f", True), + ], + ids=["float64", "float32", "float16", "string", "binary", "bool"], + ) + @pytest.mark.parametrize("op", list(_OPERATORS)) + def test_a_range_of_another_type_is_refused(self, project, column, value, op): + source = _source() + fake_spiral_sdk.scan_log.clear() + + with pytest.raises( + TypeError, match=rf"column {column!r}.*integer, timestamp or date.*filter" + ): + source.where(_OPERATORS[op][0](col(column), value)) + assert fake_spiral_sdk.scan_log == [] + + def test_a_between_of_another_type_is_refused(self, project): + with pytest.raises(TypeError, match="integer, timestamp or date"): + _source().where(col("x").between(0.0, 1.0)) + + def test_a_chained_comparison_is_refused(self, project): + """``start <= col(c) < stop`` would keep one bound silently (ITL-1465).""" + start, stop = _T0, _T0 + dt.timedelta(hours=1) + source = _source() + fake_spiral_sdk.scan_log.clear() + + with pytest.raises( + TypeError, + match=r"Condition has no truth value\. .*For a range, use " + r"\.between\(a, b\) \(both ends included\)\.", + ): + source.where(start <= col("at") < stop) + assert source.condition.is_empty + assert fake_spiral_sdk.scan_log == [] + + @pytest.mark.parametrize( + ("column", "value"), + [("x", 0.5), ("g", 1.0), ("s", "s03"), ("f", True)], + ids=["float64", "float32", "string", "bool"], + ) + def test_an_equality_of_those_types_still_works(self, project, column, value): + expected = _expected(pc.equal(_table()[column], _scalar(column, value))) + + assert _keys(_source().where({column: value})) == expected + + def test_a_decimal_column_takes_no_condition(self, project): + with pytest.raises(TypeError, match="dec"): + _source().where(col("dec") >= 3) + + @pytest.mark.parametrize( + ("column", "value", "match"), + [ + ("n", -1, "cannot hold -1"), + ("n", 256, "cannot hold 256"), + ("n", 2.0, "is a float"), + ("n", True, "is a bool"), + ("n", "2", "is a str"), + ("n", np.uint8(2), "is a uint8"), + ("unit", 2**31, "cannot hold"), + ("v", 2**63, "cannot hold"), + ("at", _WALL, "aware"), + ("w", _T0, "naive"), + ("sec", _WALL.replace(microsecond=1), "cannot hold"), + ("d", _T0, "is a datetime"), + ("d64", _T0, "is a datetime"), + ("d", "2026-11-01", "is a str"), + ], + ids=[ + "negative unsigned", + "beyond uint8", + "float for int", + "bool for int", + "str for int", + "numpy scalar", + "beyond int32", + "beyond int64", + "naive for zoned", + "aware for naive", + "finer than the unit", + "datetime for date32", + "datetime for date64", + "str for date", + ], + ) + @pytest.mark.parametrize("op", ["<", ">="]) + def test_a_bound_the_column_cannot_hold_is_refused( + self, project, column, value, match, op + ): + """Nothing is converted, rounded or clamped (D6); nothing is read.""" + source = _source() + fake_spiral_sdk.scan_log.clear() + + with pytest.raises(TypeError, match=match) as caught: + source.where(_OPERATORS[op][0](col(column), value)) + assert f"column {column!r}" in str(caught.value) + assert fake_spiral_sdk.scan_log == [] + + def test_the_constructor_refuses_what_where_refuses(self, project): + with pytest.raises(TypeError, match="integer, timestamp or date"): + _source(where=col("x") > 0.0) + with pytest.raises(TypeError, match="cannot hold"): + _source(where=col("n") < 256) + + def test_an_unknown_column_is_refused(self, project): + with pytest.raises(ValueError, match="no_such"): + _source().where(col("no_such") >= 1) + + def test_a_refused_range_leaves_the_source_unchanged(self, project): + source = _source().where(col("unit") >= 2) + + with pytest.raises(TypeError): + source.where(col("x") > 0.0) + assert source.condition == Condition.of(col("unit") >= 2) + + +class TestIdentity: + """A range changes no identity, schema, system tag or record id.""" + + def test_hashes_source_id_schema_and_rows_are_the_unrestricted_ones(self, project): + source = _source() + restricted = source.where( + col("unit") >= 2, col("at") < _T0 + dt.timedelta(hours=12) + ) + + assert restricted.content_hash() == source.content_hash() + assert restricted.pipeline_hash() == source.pipeline_hash() + assert restricted.source_id == source.source_id + assert restricted.output_schema() == source.output_schema() + assert restricted.output_schema(all_info=True) == source.output_schema( + all_info=True + ) + every = { + (r["unit"], r["at"]): r for r in source.as_table(all_info=True).to_pylist() + } + rows = restricted.as_table(all_info=True).to_pylist() + assert rows + assert rows == [every[(r["unit"], r["at"])] for r in rows] + + def test_the_original_source_is_unchanged(self, project): + source = _source() + _ = source.where(col("unit") >= 4) + + assert source.condition.is_empty + assert len(_keys(source)) == 12 + + def test_the_constructor_and_where_are_one_mechanism(self, project): + window = (col("unit") >= 2) & (col("unit") < 4) + + built = _source(where=window) + added = _source().where(window) + + assert built.condition == added.condition + assert built.to_config() == added.to_config() + assert _keys(built) == _keys(added) + + +class TestReads: + """The cap, the limit, ``head`` and new data, with a range.""" + + def test_a_window_under_the_cap_is_read_without_counting_the_table(self, project): + source = _source(max_rows=4) + fake_spiral_sdk.scan_log.clear() + + assert len(_keys(source.where(col("unit") >= 4))) == 3 + assert len(fake_spiral_sdk.scan_log) == 1 + assert fake_spiral_sdk.scan_log[0].kwargs["where"] is not None + + def test_a_window_over_the_cap_names_the_window(self, project): + with pytest.raises(SourceTooLargeError, match=r"unit >= 2.*max_rows"): + _source(max_rows=4).where(col("unit") >= 2).as_table() + + def test_the_limit_counts_matching_rows(self, project): + restricted = _source(limit=2).where(col("v") > 0) + + assert ( + _keys(restricted) + == _expected(pc.greater(_table()["v"], pa.scalar(0, pa.int64())))[:2] + ) + assert fake_spiral_sdk.scan_log[-1].kwargs["limit"] == 2 + + def test_head_reads_the_first_matching_rows_and_names_the_window(self, project): + view = _source().where(col("unit") >= 3, col("unit") < 4).head(2) + + assert view.as_table()["unit"].to_pylist() == [3, 3] + assert len(fake_spiral_sdk.scan_log) == 1 + assert view.description is not None + assert "unit >= 3, unit < 4" in view.description + + def test_new_rows_outside_the_window_move_the_version_only(self, project): + restricted = _source().where(col("unit") <= 2) + before = _keys(restricted) + extra = _table().slice(0, 1).set_column(0, "unit", pa.array([9], pa.int32())) + project.table("default.ranges").write(extra) + + assert restricted.check_for_new_data() is True + assert _keys(restricted) == before + + +class TestJobs: + """A job over a window: summary, refusals, reuse of stored rows, saving.""" + + @staticmethod + def _job(store: Path, source: Any, calls: list[int]) -> PipelineJob: + """Return a job over ``source`` that counts its calls.""" + + @function_pod(output_keys="half") + def half(n: int | None) -> float | None: + """Return half of ``n``; counts the call.""" + calls.append(-1 if n is None else n) + return None if n is None else n / 2 + + job = PipelineJob(name="windows", database=DeltaTableDatabase(store)) + with job: + half.pod(source.select_data_columns(["n"]), label="half") + return job + + @pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) + def test_the_summary_records_the_window(self, project, tmp_path, orchestrator): + window = (col("at") >= _T0) & (col("at") < _T0 + dt.timedelta(hours=6)) + source = _source(source_id="events").where(window) + job = self._job(tmp_path / "store", source, []) + + summary = job.run(orchestrator=orchestrator() if orchestrator else None) + + assert summary.conditions == {"events": window} + assert sorted(job.nodes["half"].as_table()["half"].to_pylist()) == [ + 0.0, + 0.5, + 1.0, + 127.5, + ] + + def test_overlapping_windows_compute_each_row_once(self, project, tmp_path): + """Record ids do not depend on the window, so stored rows are reused.""" + calls: list[int] = [] + events = _source(source_id="events") + job = self._job(tmp_path / "store", events.where(col("unit") < 3), calls) + job.run() + assert sorted(calls) == [0, 1, 2, 3, 4, 255] + + calls.clear() + job.bind(sources={"events": events.where(col("unit") >= 2)}) + assert job.nodes["half"].is_stale + job.run() + + assert sorted(calls) == [5, 6, 7, 8, 9, 10] + assert len(job.nodes["half"].as_table()) == 9 + + def test_one_table_under_two_windows_in_one_job_is_refused(self, project, tmp_path): + events = _source(source_id="events") + + @function_pod(output_keys="m") + def same(n: int | None) -> int | None: + return n + + job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) + with pytest.raises(ValueError, match="different rows in one pipeline"): + with job: + same.pod( + events.where(col("unit") < 2).select_data_columns(["n"]), label="a" + ) + same.pod( + events.where(col("unit") >= 2).select_data_columns(["n"]), label="b" + ) + + def test_a_saved_job_keeps_the_window_in_canonical_order(self, project, tmp_path): + store = tmp_path / "store" + source = _source(source_id="events").where( + col("at") < _T0 + dt.timedelta(hours=9), f=True, unit=2 + ) + job = self._job(store, source, []) + job.run() + path = tmp_path / "job.json" + job.save(path) + + saved = json.loads(path.read_text())["bindings"]["sources"]["events"]["where"] + assert saved == source.condition.to_config() + terms = saved[":condition"]["all"] + assert [t["column"] for t in terms] == sorted(t["column"] for t in terms) + loaded = PipelineJob.load(path, database=DeltaTableDatabase(store)) + loaded_source = loaded.nodes["events"].bound_source + assert isinstance(loaded_source, SpiralDBTableSource) + assert loaded_source.condition == source.condition + assert _keys(loaded_source) == _keys(source) + + +class TestSavedEqualities: + """An equality-only ``where`` is saved in canonical order (D8).""" + + def test_two_equalities_given_in_either_order_save_the_same_bytes(self, project): + forward = _source().where(unit=2, f=True) + backward = _source().where(f=True, unit=2) + + assert json.dumps(forward.to_config()["where"]) == '{"f": true, "unit": 2}' + assert json.dumps(backward.to_config()["where"]) == '{"f": true, "unit": 2}' + + def test_a_config_saved_in_the_order_given_still_loads(self, project): + """A file written before this change (keys in the order given) loads equal.""" + config = _source().where(unit=2, f=True).to_config() + config["where"] = {"unit": 2, "f": True} + + loaded = SpiralDBTableSource.from_config(config) + + assert loaded.condition == Condition.of(f=True, unit=2) + assert _keys(loaded) == _expected( + pc.equal(_table()["unit"], pa.scalar(2, pa.int32())), + pc.equal(_table()["f"], pa.scalar(True)), + ) + + def test_one_equality_is_saved_as_before(self, project): + assert _source().where(unit=2).to_config()["where"] == {"unit": 2} diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index b69edfaf8..368c1442f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -26,12 +26,12 @@ from orcapod.errors import RestrictedAggregationWarning from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.restrictions import restrictions_in_force -from orcapod.core.sources.spiraldb_table_source import _checked_conditions from orcapod.core.sources.base import RootSource from orcapod.core.sources.cached_source import CachedSource from orcapod.sources import SpiralDBTableSource from orcapod.core.operators import MapData from orcapod.types import CacheMode, Condition, col +from orcapod.types.condition import check_equality_conditions from tests.test_databases import fake_spiral_sdk _PROJECT = "workshop-sample" @@ -380,8 +380,8 @@ def test_a_float_beyond_the_column_range_is_refused(self): # About the condition check itself: the fake has no float32 data to match. with pytest.raises(TypeError, match="range"): - _checked_conditions({"x": 1e300}, schema) - assert _checked_conditions({"x": 0.1}, schema) == {"x": 0.1} + check_equality_conditions({"x": 1e300}, schema) + assert check_equality_conditions({"x": 0.1}, schema) == {"x": 0.1} @pytest.mark.parametrize("value", [1e300, -1e300]) def test_a_float_overflow_is_refused_by_where_and_the_constructor( @@ -409,9 +409,9 @@ def test_a_zoned_column_takes_an_aware_time_only(self): aware = _START.replace(tzinfo=dt.timezone.utc) # About the condition check itself: the pyspiral fake keeps no time zone. - assert _checked_conditions({"at": aware}, schema) == {"at": aware} + assert check_equality_conditions({"at": aware}, schema) == {"at": aware} with pytest.raises(TypeError, match="aware"): - _checked_conditions({"at": _START}, schema) + check_equality_conditions({"at": _START}, schema) @pytest.mark.parametrize("fold", [0, 1]) @pytest.mark.parametrize("zone", ["America/New_York", "UTC"]) @@ -432,9 +432,9 @@ def test_a_time_in_a_daylight_saving_overlap_is_accepted(self, fold, zone): # About the condition check itself: the pyspiral fake keeps no time zone. for conditions in ({"at": local, "unit": 1}, {"unit": 1, "at": local}): - assert _checked_conditions(conditions, schema) == conditions + assert check_equality_conditions(conditions, schema) == conditions - @pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf, -0.0]) + @pytest.mark.parametrize("value", [math.inf, -math.inf, 0.0]) @pytest.mark.parametrize( "restrict", [ @@ -456,11 +456,12 @@ def test_a_time_in_a_daylight_saving_overlap_is_accepted(self, fold, zone): "Condition.of mapping", ], ) - def test_a_non_finite_or_signed_zero_float_is_pushed_down_as_given( + def test_an_infinite_float_or_zero_is_pushed_down_as_given( self, project, restrict, value ): """Accepted, and sent to the table system as ``column == value``: which rows - it selects is that system's equality (developer decision, 2026-11-19).""" + it selects is that system's equality (developer decision, 2026-11-19). ``-0.0`` + and NaN are refused (ITL-1480; ``test_spiraldb_table_source_float_equalities``).""" source = restrict(value) source.as_table() @@ -482,7 +483,7 @@ def test_a_time_finer_than_the_column_is_refused(self): schema = pa.schema([pa.field("at", pa.timestamp("s"))]) with pytest.raises(TypeError, match="exactly"): - _checked_conditions({"at": _START.replace(microsecond=5)}, schema) + check_equality_conditions({"at": _START.replace(microsecond=5)}, schema) def test_none_is_refused(self, project): """``None`` matches no row (a null equals nothing), so it is refused.""" @@ -680,7 +681,7 @@ def test_a_float16_column_takes_a_float(self): (About the check itself: pyarrow, and so the fake, has no float16 equality.)""" schema = pa.schema([pa.field("h", pa.float16()), pa.field("k", pa.int64())]) for conditions in ({"h": 1.5, "k": 1}, {"k": 1, "h": 1.5}): - assert _checked_conditions(conditions, schema) == conditions + assert check_equality_conditions(conditions, schema) == conditions # Two layouts of one table: three key columns (two timestamps and an integer), three @@ -1489,31 +1490,14 @@ def test_a_saved_config_of_the_earlier_form_loads(self, project): [(0.0, -0.0), (-0.0, 0.0), (math.nan, math.nan)], ids=["0.0 then -0.0", "-0.0 then 0.0", "NaN twice"], ) - def test_equal_float_conditions_are_one_restriction_in_a_pipeline( - self, project, tmp_path, values - ): - """``0.0`` and ``-0.0``, or NaN twice, are one restriction (as Polars matches - them), so one table read with both in one pipeline is accepted.""" - - @function_pod(output_keys="a") - def first(amplitude: float | None) -> float | None: - """Return ``amplitude``.""" - return amplitude - - @function_pod(output_keys="b") - def second(channel: int | None) -> int | None: - """Return ``channel``.""" - return channel - + def test_equal_float_conditions_of_two_reads_are_refused(self, project, values): + """``0.0`` and ``-0.0``, or NaN twice, are one condition to Orcapod but not to + SpiralDB, so ``where`` refuses the ``-0.0`` or NaN read (ITL-1480) before a + pipeline could hold both.""" events = _source(source_id="events", tag_only_columns=True) - job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with job: - first.pod(events.where(amplitude=values[0]), label="first") - second.pod(events.where(amplitude=values[1]), label="second") - - summary = job.run() - - assert summary.conditions == {"events": Condition.of(amplitude=values[0])} + with pytest.raises(TypeError, match="ITL-1480"): + for value in values: + events.where(amplitude=value) _RESTRICTED_FORMS: dict[str, tuple[Callable[[], SpiralDBTableSource], list[str]]] = { @@ -1535,6 +1519,10 @@ def second(channel: int | None) -> int | None: lambda: _source(where={"channel": 0, "subject_id": "m1"}), ["channel=0", "subject_id='m1'"], ), + "a range and an equality": ( + lambda: _source().where(col("timestamp") >= 2, col("timestamp") < 4, flag=True), + ["timestamp >= 2", "timestamp < 4", "flag=True"], + ), } @@ -1617,6 +1605,7 @@ def first(amplitude: float | None) -> float | None: "a condition and a limit": lambda s: SpiralDBTableSource( _PROJECT, "event", source_id="events", tag_only_columns=True, limit=3 ).where(subject_id="m1"), + "a range": lambda s: s.where(col("timestamp") >= 2, col("timestamp") < 4), } _CACHING = [CacheMode.LOG, CacheMode.REPLAY] @@ -2564,33 +2553,50 @@ def test_a_direct_label_with_no_collision_is_not_numbered(self, project): assert set(restrictions_in_force([second, first])) == {"a", "b"} -class TestWhereTakesEqualitiesOnly: - """``where`` refuses every condition but equalities, pointing to ``filter`` (ITL-1374).""" +class TestWhereTakesEqualitiesAndRanges: + """``where`` refuses every condition but equalities and ranges, pointing to + ``filter`` (ITL-1374, ITL-998).""" @pytest.mark.parametrize( "build", [ - lambda: col("timestamp") >= 3, lambda: col("subject_id").is_in(["m1", "m2"]), lambda: col("note").is_null(), lambda: (col("subject_id") == "m1") | (col("subject_id") == "m2"), lambda: ~(col("subject_id") == "m1"), lambda: col("subject_id") != "m1", - lambda: (col("subject_id") == "m1") & (col("subject_id") == "m2"), + lambda: col("timestamp") < col("channel"), + lambda: (col("timestamp") < 2) | (col("timestamp") > 4), + lambda: ~(col("timestamp") >= 3), + lambda: (col("timestamp") >= 3) & ~(col("timestamp") < 5), ], ids=[ - "comparison", "is_in", "null test", "or", "not", "not equal", - "two values", + "two columns", + "or of ranges", + "not a range", + "range and not", ], ) - def test_a_condition_other_than_equality_is_refused(self, project, build): - with pytest.raises(TypeError, match=r"equality conditions only.*filter"): - _source().where(build()) + def test_any_other_condition_is_refused(self, project, build): + """The whole condition is refused, pointing to ``filter``; nothing is read.""" + source = _source() + fake_spiral_sdk.scan_log.clear() + + with pytest.raises(TypeError, match=r"equalities .* and ranges .*filter"): + source.where(build()) + assert fake_spiral_sdk.scan_log == [] + + def test_two_values_of_one_column_are_refused(self, project): + """A column equals one value: two different ones are refused.""" + both = (col("subject_id") == "m1") & (col("subject_id") == "m2") + + with pytest.raises(ValueError, match="already restricted to 'm1'"): + _source().where(both) def test_an_equality_built_with_col_is_taken(self, project): """``col(c) == v`` is the equality ``where`` takes, with the keyword's rows.""" @@ -2600,5 +2606,5 @@ def test_an_equality_built_with_col_is_taken(self, project): assert restricted.condition == Condition.of(subject_id="m2") def test_the_constructor_refuses_it_too(self, project): - with pytest.raises(TypeError, match="equality conditions only"): - _source(where=col("timestamp") >= 3) + with pytest.raises(TypeError, match=r"equalities .* and ranges"): + _source(where=col("timestamp").is_in([3])) diff --git a/tests/test_core/sources/test_spiraldb_table_source_where_edges.py b/tests/test_core/sources/test_spiraldb_table_source_where_edges.py new file mode 100644 index 000000000..11f3b5848 --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_table_source_where_edges.py @@ -0,0 +1,294 @@ +"""Edges of a SpiralDB ``where`` found in the round-2 review of 77d75ed0 (ITL-998). + +1. Every column name works as a keyword, also ``self``, ``conditions``, ``columns`` + and, for ``Condition.of``, ``cls``. +2. A timestamp bound is taken when the column's type holds it exactly, also when its + instant is not a Python ``datetime`` in the column's zone (year 1 east of UTC, year + 9999 west of it). +3. An equality to ``-0.0`` or a NaN is refused with the ``filter`` guidance before the + arguments are merged, also beside a different value for the same column. + +Runs on the fake only. +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +import math +import zoneinfo +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod.sources import SpiralDBTableSource +from orcapod.types import Condition, col +from orcapod.types.condition import check_restriction +from tests.test_databases import fake_spiral_sdk + +_PROJECT = "workshop-sample" +_UTC = dt.timezone.utc +_EAST = dt.timezone(dt.timedelta(hours=1)) +_WEST = dt.timezone(dt.timedelta(hours=-5)) +_KEYS = pa.schema([pa.field("id", pa.int64()), pa.field("lab", pa.large_string())]) +_STAMPS = [ + dt.datetime(1, 1, 1, tzinfo=_UTC), + dt.datetime(1, 1, 1, 1, tzinfo=_UTC), + dt.datetime(2026, 11, 1, tzinfo=_UTC), + dt.datetime(9999, 12, 31, 22, tzinfo=_UTC), + dt.datetime(9999, 12, 31, 22, 30, tzinfo=_UTC), +] + + +def _table() -> pa.Table: + """Return rows with columns named like ``where``'s parameters, and extreme times.""" + n = len(_STAMPS) + return pa.table( + { + "id": pa.array(range(n), pa.int64()), + "lab": pa.array(["a", "b", "a", "b", "a"], pa.large_string()), + "self": pa.array([1, 2, 1, 2, 1], pa.int64()), + "conditions": pa.array(["x", "x", "y", "y", "x"], pa.large_string()), + "columns": pa.array([7, 8, 7, 8, 9], pa.int32()), + "cls": pa.array([0, 0, 1, 1, 1], pa.int64()), + "t_us": pa.array(_STAMPS, pa.timestamp("us", tz="UTC")), + "t_s": pa.array(_STAMPS, pa.timestamp("s", tz="UTC")), + "t_ms_paris": pa.array(_STAMPS, pa.timestamp("ms", tz="Europe/Paris")), + "v": pa.array([-0.0, 0.0, math.nan, 1.5, 2.5], pa.float64()), + } + ) + + +_LOW = dt.datetime(1677, 9, 21, 0, 12, 43, 145225, tzinfo=_UTC) +_HIGH = dt.datetime(2262, 4, 11, 23, 47, 16, 854775, tzinfo=_UTC) +_NS_ZONES = ("America/New_York", "Europe/Paris") + + +def _ns_count(instant: dt.datetime) -> int: + """Return the nanoseconds since the epoch of a UTC ``instant``.""" + since = instant - dt.datetime(1970, 1, 1, tzinfo=_UTC) + return (since // dt.timedelta(microseconds=1)) * 1000 + + +def _nanos() -> pa.Table: + """Return nanosecond timestamps at both ends of the 64-bit count, in two zones.""" + counts = [-(2**63), _ns_count(_LOW), 0, _ns_count(_HIGH), 2**63 - 1] + columns: dict[str, Any] = { + "id": pa.array(range(len(counts)), pa.int64()), + "lab": pa.array(["a"] * len(counts), pa.large_string()), + } + for number, zone in enumerate(_NS_ZONES): + columns[f"ns{number}"] = pa.array(counts, pa.int64()).view( + pa.timestamp("ns", tz=zone) + ) + return pa.table(columns) + + +@pytest.fixture() +def project(tmp_path: Path): + """Provide a fake project holding the ``edges`` table.""" + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) + project.create_table("default.edges", key_schema=_KEYS).write(_table()) + project.create_table("default.nanos", key_schema=_KEYS).write(_nanos()) + fake_spiral_sdk.scan_log.clear() + yield project + fake_spiral_sdk.scan_log.clear() + + +def _source(**kwargs: Any) -> SpiralDBTableSource: + """Return a source over ``edges``, tags kept tag-only.""" + return SpiralDBTableSource(_PROJECT, "edges", tag_only_columns=True, **kwargs) + + +def _ids(source: SpiralDBTableSource) -> list[Any]: + """Return the ``id`` of every row ``source`` reads (sync).""" + return source.as_table()["id"].to_pylist() + + +def _async_ids(source: SpiralDBTableSource) -> list[Any]: + """Return the ``id`` of every row ``source`` reads (async).""" + + async def collect() -> list[Any]: + return [tag.as_dict()["id"] async for tag, _ in source.async_iter_data()] + + return asyncio.run(asyncio.wait_for(collect(), timeout=60)) + + +def _expected(mask: Any) -> list[Any]: + """Return the ids of the rows where the pyarrow ``mask`` holds.""" + return _table().filter(pc.fill_null(mask, False))["id"].to_pylist() + + +class TestEveryColumnNameIsAKeyword: + @pytest.mark.parametrize( + ("keywords", "expected"), + [ + ({"self": 1}, [0, 2, 4]), + ({"conditions": "x"}, [0, 1, 4]), + ({"columns": 8}, [1, 3]), + ({"self": 1, "conditions": "x", "columns": 7}, [0]), + ({"columns": 7, "conditions": "x", "self": 1}, [0]), + ], + ids=["self", "conditions", "columns", "all three", "all three reversed"], + ) + def test_where_takes_a_column_named_like_its_parameters( + self, project, keywords, expected + ): + """Keywords, a mapping, and keywords beside a range: one set of rows.""" + for source, condition in ( + (_source().where(**keywords), Condition.of(keywords)), + (_source().where(keywords), Condition.of(keywords)), + ( + _source().where(col("id") >= 0, **keywords), + Condition.of(col("id") >= 0, keywords), + ), + ): + assert _ids(source) == expected + assert _async_ids(source) == expected + assert source.condition == condition + + def test_condition_of_takes_a_column_named_cls(self, project): + condition = Condition.of(cls=1, self=1) + + assert condition == Condition.of({"self": 1, "cls": 1}) + assert _ids(_source().where(condition)) == [2, 4] + + +_BOUNDS = [ + dt.datetime(1, 1, 1, tzinfo=_EAST), + dt.datetime(1, 1, 1, 1, 30, tzinfo=_EAST), + dt.datetime(9999, 12, 31, 23, tzinfo=_WEST), + dt.datetime(9999, 12, 31, 18, 30, tzinfo=_WEST), +] + + +class TestTimestampBoundsAtTheEndsOfTheCalendar: + @pytest.mark.parametrize("column", ["t_us", "t_s", "t_ms_paris"]) + @pytest.mark.parametrize( + "bound", + _BOUNDS, + ids=["year 1 +01:00", "year 1 01:30+01:00", "year 9999 -05:00", "18:30-05:00"], + ) + @pytest.mark.parametrize("op", ["<", "<=", ">", ">="]) + def test_a_bound_the_column_holds_exactly_is_taken( + self, project, column, bound, op + ): + """The instant converts exactly to the column's type, though it is not a + Python ``datetime`` in UTC: taken, and the rows are pyarrow's.""" + build = { + "<": lambda c: c < bound, + "<=": lambda c: c <= bound, + ">": lambda c: c > bound, + ">=": lambda c: c >= bound, + }[op] + compare = {"<": pc.less, "<=": pc.less_equal, ">": pc.greater}.get( + op, pc.greater_equal + ) + table = _table() + expected = _expected( + compare( + table[column], pa.scalar(bound, type=table.schema.field(column).type) + ) + ) + + source = _source().where(build(col(column))) + + assert _ids(source) == expected + assert _async_ids(source) == expected + + def test_a_bound_finer_than_the_column_is_still_refused(self, project): + bound = dt.datetime(1, 1, 1, 0, 0, 0, 5, tzinfo=_EAST) + + with pytest.raises(TypeError, match="cannot hold .* exactly"): + _source().where(col("t_s") >= bound) + assert fake_spiral_sdk.scan_log == [] + + @pytest.mark.parametrize( + "bound", + [dt.datetime(1, 1, 1, tzinfo=_UTC), dt.datetime(9999, 12, 31, tzinfo=_UTC)], + ids=["year 1", "year 9999"], + ) + def test_a_bound_beyond_a_nanosecond_column_is_refused(self, project, bound): + """``timestamp[ns]`` reaches 1677 to 2262 only.""" + condition = Condition.of(col("t") >= bound) + schema = pa.schema([pa.field("t", pa.timestamp("ns", "UTC"))]) + + with pytest.raises(TypeError, match="beyond the range of a 64-bit count of ns"): + check_restriction(condition, schema) + + +class TestNanosecondBoundsAtTheEndsOfTheCount: + @pytest.mark.parametrize("number", range(len(_NS_ZONES)), ids=list(_NS_ZONES)) + @pytest.mark.parametrize( + ("instant", "op"), + [(_LOW, ">="), (_LOW, ">"), (_HIGH, "<="), (_HIGH, "<")], + ids=["low >=", "low >", "high <=", "high <"], + ) + def test_a_zoned_bound_at_the_edge_reads_pyarrows_rows( + self, project, number, instant, op + ): + """Bounds a ``timestamp[ns]`` column holds at the ends of its 64-bit count, + given in the column's zone, read the rows pyarrow selects (sync and async).""" + column = f"ns{number}" + bound = instant.astimezone(zoneinfo.ZoneInfo(_NS_ZONES[number])) + table = _nanos() + compare = { + ">=": pc.greater_equal, + ">": pc.greater, + "<=": pc.less_equal, + "<": pc.less, + }[op] + # pyarrow drops the seconds of an offset (New York's 1677 offset is -4:56:02), + # so the expected rows compare the integer counts. + count = _ns_count(instant) + expected = table.filter( + compare(table[column].cast(pa.int64()), pa.scalar(count, pa.int64())) + )["id"].to_pylist() + build = { + ">=": lambda c: c >= bound, + ">": lambda c: c > bound, + "<=": lambda c: c <= bound, + "<": lambda c: c < bound, + }[op] + + source = SpiralDBTableSource(_PROJECT, "nanos", tag_only_columns=True).where( + build(col(column)) + ) + + assert expected == {">=": [1, 2, 3, 4], ">": [2, 3, 4], "<=": [0, 1, 2, 3]}.get( + op, [0, 1, 2] + ) + assert _ids(source) == expected + assert _async_ids(source) == expected + + +class TestSpecialFloatsBeforeMerging: + @pytest.mark.parametrize("refused", [-0.0, math.nan], ids=["negative zero", "NaN"]) + @pytest.mark.parametrize( + "where", + [ + lambda r: _source().where(col("id") >= 0, {"v": r}, v=1.5), + lambda r: _source().where(col("id") >= 0, {"v": 1.5}, v=r), + lambda r: _source().where({"v": r}, {"v": 1.5}), + lambda r: _source().where({"v": 1.5}, {"v": r}), + lambda r: _source().where(col("v") == 1.5, {"v": r}), + ], + ids=[ + "mapping refused, keyword other", + "mapping other, keyword refused", + "two mappings, refused first", + "two mappings, refused last", + "col other, mapping refused", + ], + ) + def test_refused_with_the_filter_guidance_beside_another_value( + self, project, refused, where + ): + """Not the generic two-values error: the specified ``TypeError``.""" + with pytest.raises(TypeError, match=r"ITL-1480.*filter"): + where(refused) + assert fake_spiral_sdk.scan_log == [] diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 5b9e13d61..b4af52dee 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -14,7 +14,9 @@ import json import math +import operator import os +import struct import types import urllib.parse import uuid @@ -68,6 +70,9 @@ "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", + "float-order": "lt, lte, gt and gte order floats by IEEE 754 total order: the " + "negative NaN below -inf, -0.0 below 0.0, positive NaNs above inf (seen November 26, " + "2026, ITL-998); a null meets no comparison", "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)", @@ -289,6 +294,26 @@ def _bits(value: Any) -> Any: return value +def _ordered(value: Any) -> Any: + """Return ``value`` so that ``<`` orders it as the service does (``float-order``).""" + if isinstance(value, float): + (bits,) = struct.unpack("= 0 else -(bits & 0x7FFFFFFFFFFFFFFF) - 1 + return value + + +def _compares(stored: Any, op: str, value: Any) -> bool: + """Return whether a stored value meets ``op value`` (not null).""" + if op == "==": + return _bits(stored) == _bits(value) + return { + "<": operator.lt, + "<=": operator.le, + ">": operator.gt, + ">=": operator.ge, + }[op](_ordered(stored), _ordered(value)) + + # ------------------------------------------------------------------------------- the store @@ -509,18 +534,18 @@ class _Literal: @dataclass(frozen=True) class FakePredicate: - """Equalities a row must all match.""" + """Comparisons a row must all match: ``(column, literal, operator)``.""" - terms: tuple[tuple[str, _Literal], ...] + terms: tuple[tuple[str, _Literal, str], ...] @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] + return [(name, wanted.value) for name, wanted, op in self.terms if op == "=="] 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) + """Return the terms as ``name == value`` joined by ``&``.""" + return " & ".join(f"{name} {op} {w.value!r}" for name, w, op in self.terms) def column(name: str) -> _Column: @@ -532,12 +557,38 @@ 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) + scalar = pa.scalar(value, type) + if pa.types.is_timestamp(type): + # Kept as its integer count, never a Python value: an instant at either end of + # a count (year 1 east of UTC, the ends of timestamp[ns]) has no datetime or + # pandas Timestamp in its zone. The scan reads the count as the same type. + return _Literal(scalar.value, type) + return _Literal(scalar.as_py(), type) def eq(left: _Column, right: _Literal) -> FakePredicate: """Stand in for ``spiral.eq``.""" - return FakePredicate(((left.name, right),)) + return FakePredicate(((left.name, right, "=="),)) + + +def lt(left: _Column, right: _Literal) -> FakePredicate: + """Stand in for ``spiral.lt``.""" + return FakePredicate(((left.name, right, "<"),)) + + +def lte(left: _Column, right: _Literal) -> FakePredicate: + """Stand in for ``spiral.lte``.""" + return FakePredicate(((left.name, right, "<="),)) + + +def gt(left: _Column, right: _Literal) -> FakePredicate: + """Stand in for ``spiral.gt``.""" + return FakePredicate(((left.name, right, ">"),)) + + +def gte(left: _Column, right: _Literal) -> FakePredicate: + """Stand in for ``spiral.gte``.""" + return FakePredicate(((left.name, right, ">="),)) def and_(left: FakePredicate, right: FakePredicate) -> FakePredicate: @@ -638,9 +689,9 @@ def scan( limit: int | None = None, batch_rows: int | None = None, ) -> FakeScan: - """Plan a scan (``rows``, ``literal``, ``float-eq``).""" + """Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``).""" rows = self._store.read(self.resource_id, self._version) - for name, wanted in filter.terms if filter else (): + for name, wanted, op 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 " @@ -655,7 +706,7 @@ def scan( 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], + [v is not None and _compares(v, op, value) for v in values], pa.bool_(), ) ) @@ -870,6 +921,10 @@ def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]: column=column, literal=literal, eq=eq, + lt=lt, + lte=lte, + gt=gt, + gte=gte, and_=and_, drop_column=drop_column, ) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index f256de2fa..29b8ac231 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -16,19 +16,24 @@ import datetime as dt import math +import operator import os +import struct 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 SpiralDBConnector +from orcapod.databases import spiraldb_connector as connector_module from orcapod.databases import spiraldb_schema_table as st from orcapod.databases.spiraldb_connector import SpiralDBTableNotFoundError from orcapod.sources import SpiralDBTableSource +from orcapod.types import Condition, col from tests.test_databases import fake_spiral_sdk as fake _LIVE = os.environ.get("SPIRAL_INTEGRATION_TESTS") == "1" @@ -93,6 +98,60 @@ ) +def _ranges() -> pa.Table: + """Return the ``ranges`` rows: every type a range takes, and a float column (ITL-998). + + Integers of every width at both ends; timestamps of every unit, naive, in UTC and in + a daylight-saving zone, before and after 1970, with values one unit apart; dates, and + ``date64`` values that are not midnight; a null in every column but the key. ``x`` + holds the floats whose order decided that a float range is refused. + """ + columns: dict[str, Any] = {"k": pa.array(range(10), pa.int64())} + for name in ( + "uint8", + "uint16", + "uint32", + "uint64", + "int8", + "int16", + "int32", + "int64", + ): + arrow_type = getattr(pa, name)() + signed = name.startswith("int") + high = 2 ** (arrow_type.bit_width - signed) - 1 + low = -high - 1 if signed else 0 + values = [low, low + 1, 0, 7, 7, None, 3, high - 1, high, 5] + columns[name] = pa.array(values, arrow_type) + timestamp: Any = pa.timestamp # its stubs take literal units only + seconds = [-315_619_200, 0, 1_793_511_000, 1_793_514_600, 1_793_514_600] + seconds += [None, 4_102_444_800, 1_793_514_600, 1, -1] + for unit, per_second in (("s", 1), ("ms", 10**3), ("us", 10**6), ("ns", 10**9)): + counts = [None if s is None else s * per_second for s in seconds] + counts[7] = 1_793_514_600 * per_second + 1 # one unit after a stored value + for zone in (None, "UTC", "America/New_York"): + name = f"ts_{unit}_{zone or 'naive'}".replace("America/New_York", "ny") + arrow_type = timestamp(unit, zone) + columns[name] = pa.array(counts, pa.int64()).view(arrow_type) + days = [-400, 0, 1, 20_000, 20_000, None, 30_000, -719_162, 2, 5] + columns["d32"] = pa.array(days, pa.int32()).view(pa.date32()) + day = 86_400_000 + columns["d64"] = pa.array( + [None if d is None else d * day for d in days], pa.int64() + ).view(pa.date64()) + off_midnight = [None if d is None else d * day + (d % 3) * 3_600_000 for d in days] + columns["d64_off"] = pa.array(off_midnight, pa.int64()).view(pa.date64()) + nan, negative_nan = struct.unpack( + "<2d", struct.pack("<2Q", 0x7FF8 << 48, 0xFFF8 << 48) + ) + floats = [nan, negative_nan, -0.0, 0.0, math.inf, -math.inf, 1.5, None, 2.5, -3.0] + columns["x"] = pa.array(floats, pa.float64()) + return pa.table(columns) + + +_RANGES = _ranges() + + @dataclass(frozen=True) class _Place: """Where the tables are.""" @@ -124,6 +183,7 @@ def _seed(client: Any, place: _Place) -> None: for name, keys, rows in ( ("units", ["k2", "k1"], _ROWS), ("typed", ["k"], _TYPED), + ("ranges", ["k"], _RANGES), ): key_schema = pa.schema([rows.schema.field(k) for k in keys]) table = project.create_keyed_table( @@ -283,7 +343,7 @@ def test_limit_reads_the_first_keys(place: _Place, limit: int) -> None: ], ) def test_where(place: _Place, where: dict[str, Any], expected: list[int]) -> None: - batches = place.connector().scan_batches("typed", where=where) + batches = place.connector().scan_batches("typed", where=Condition.of(where)) assert [k for b in batches for k in b.column("k").to_pylist()] == expected @@ -315,3 +375,109 @@ def test_an_early_close(place: _Place) -> None: batches: Any = place.connector().scan_batches("units") assert next(batches).num_rows > 0 batches.close() + + +# ---------------------------------------------------------------------------- ranges +# A dataset seeded before ``ranges`` existed records no schema row for it (rows are +# written once): its columns then read as nullable, with a warning; the keys compared +# here are unaffected. + +_RANGE_OPERATORS = { + "<": (operator.lt, pc.less), + "<=": (operator.le, pc.less_equal), + ">": (operator.gt, pc.greater), + ">=": (operator.ge, pc.greater_equal), +} + + +def _range_bounds(name: str) -> tuple[Any, Any, Any]: + """Return a low, a middle and a high bound for a ``ranges`` column, as ``where`` + takes them (a stored value where the column holds one exactly).""" + arrow_type = _RANGES.schema.field(name).type + if pa.types.is_integer(arrow_type): + return (_RANGES[name][1].as_py(), 7, _RANGES[name][7].as_py()) + if pa.types.is_date(arrow_type): + epoch = dt.date(1970, 1, 1) + return ( + epoch, + epoch + dt.timedelta(days=20_000), + epoch + dt.timedelta(days=30_000), + ) + zone = dt.timezone.utc if arrow_type.tz is not None else None + moments = [ + dt.datetime(1970, 1, 1), + dt.datetime(2026, 11, 1, 6, 30), + dt.datetime(2100, 1, 1), + ] + low, middle, high = (m.replace(tzinfo=zone) for m in moments) + return low, middle, high + + +_RANGE_COLUMNS = [n for n in _RANGES.column_names if n not in ("k", "x")] + + +def _keys_where(place: _Place, condition: Condition) -> list[Any]: + """Return the keys the connector reads under ``condition``, in order.""" + batches = place.connector().scan_batches("ranges", where=condition) + return [k for b in batches for k in b.column("k").to_pylist()] + + +def _pyarrow_keys(*masks: Any) -> list[Any]: + """Return the keys of the rows where every mask holds (a null holds not).""" + keep = pc.fill_null(masks[0], False) + for mask in masks[1:]: + keep = pc.and_(keep, pc.fill_null(mask, False)) + return _RANGES.filter(keep)["k"].to_pylist() + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.UnrecordedTableSchemaWarning") +@pytest.mark.parametrize("name", _RANGE_COLUMNS) +def test_a_range_of_every_type_reads_pyarrows_rows(place: _Place, name: str) -> None: + """Each operator with a bound, and ``between``, on every type a range takes.""" + column = _RANGES[name] + arrow_type = column.type + low, middle, high = _range_bounds(name) + for python_op, arrow_op in _RANGE_OPERATORS.values(): + expected = _pyarrow_keys(arrow_op(column, pa.scalar(middle, arrow_type))) + assert _keys_where(place, python_op(col(name), middle)) == expected, name + expected = _pyarrow_keys( + pc.greater_equal(column, pa.scalar(low, arrow_type)), + pc.less_equal(column, pa.scalar(high, arrow_type)), + ) + assert _keys_where(place, col(name).between(low, high)) == expected + + +def test_the_service_orders_floats_by_total_order(place: _Place) -> None: + """Why a float range is refused (ITL-998, D14; ITL-1477): through the SDK alone, a + positive NaN is above every number, the negative NaN below, and -0.0 below 0.0.""" + sp: Any = connector_module.sp + connector = place.connector() + with connector: + table = connector.lookup_table("ranges")._at(None) # pyright: ignore[reportPrivateUsage] # the SDK's handle, for an SDK-only scan + zero = sp.literal(0.0, pa.float64()) + + def keys(predicate: Any) -> list[int]: + return table.scan(filter=predicate).to_table()["k"].to_pylist() + + assert keys(sp.gt(sp.column("x"), zero)) == [0, 4, 6, 8] # NaN, inf, 1.5, 2.5 + assert keys(sp.lt(sp.column("x"), zero)) == [1, 2, 5, 9] # -NaN, -0.0, -inf, -3 + assert keys(sp.eq(sp.column("x"), zero)) == [3] # not -0.0 + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.UnrecordedTableSchemaWarning") +def test_a_source_reads_a_window_with_an_equality_and_a_limit(place: _Place) -> None: + """Through the source: a window and an equality, with and without a limit; a float + range is refused before any read.""" + window = (col("ts_us_UTC") >= dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)) & ( + col("int64") < 7 + ) + expected = _pyarrow_keys( + pc.greater_equal(_RANGES["ts_us_UTC"], pa.scalar(0, pa.timestamp("us", "UTC"))), + pc.less(_RANGES["int64"], pa.scalar(7, pa.int64())), + ) + source = place.source("ranges").where(window) + assert source.as_table()["k"].to_pylist() == expected + limited = place.source("ranges", limit=2).where(window) + assert limited.as_table()["k"].to_pylist() == expected[:2] + with pytest.raises(TypeError, match="integer, timestamp or date"): + place.source("ranges").where(col("x") > 0.0) diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index f11fee4e5..de0d1b0df 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -36,6 +36,7 @@ from orcapod.nodes import FunctionJobNode from orcapod.sources import DictSource, SpiralDBTableSource from orcapod.types import ColumnInfo +from orcapod.types import Condition from tests.test_databases import fake_spiral_sdk as fake _ITEM = pa.field("item", pa.float32(), False) @@ -364,7 +365,9 @@ 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}) + batches = SpiralDBConnector("p").scan_batches( + "typed", where=Condition.of({column: value}) + ) assert [k for b in batches for k in b.column("k").to_pylist()] == expected @@ -379,11 +382,46 @@ def test_a_filter_applied_here_comes_before_the_limit(project: Any, limit: int) ) project.create_table("default.half", key_schema=[("k", pa.int64())]).write(rows) for where in ({"h": 2.0, "s": "x"}, {"s": "x", "h": 2.0}): - batches = SpiralDBConnector("p").scan_batches("half", where=where, limit=limit) + batches = SpiralDBConnector("p").scan_batches( + "half", where=Condition.of(where), limit=limit + ) found = [k for b in batches for k in b.column("k").to_pylist()] assert found == [1, 3, 5, 7][:limit] +@pytest.mark.parametrize("limit", [None, 1, 3]) +@pytest.mark.parametrize( + "values", + [(1.0, 2.0), (2.0, 1.0), (2.0, 2.0)], + ids=["1 then 2", "2 then 1", "2 twice"], +) +def test_every_equality_applied_here_holds( + project: Any, values: tuple[float, float], limit: int | None +) -> None: + """CodeRabbit on PR 574 (connector:550): two equalities of one ``float16`` column + are both applied here, so different values read no row (the last one used to + replace the first), and equal values read that value's rows.""" + 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) + first, second = values + for where in ( + Condition.of(Condition.of(h=first), Condition.of(h=second)), + Condition.of(Condition.of(h=first), Condition.of(s="x", h=second)), + ): + batches = SpiralDBConnector("p").scan_batches("half", where=where, limit=limit) + found = [k for b in batches for k in b.column("k").to_pylist()] + if first != second: + assert found == [] + else: + assert found == [1, 3, 5, 7][:limit] + + # --------------------------------------------------------------------------------- counts diff --git a/tests/test_types_condition.py b/tests/test_types_condition.py index da3041982..b37491ef4 100644 --- a/tests/test_types_condition.py +++ b/tests/test_types_condition.py @@ -7,6 +7,7 @@ from __future__ import annotations import datetime as dt +import itertools import json import math import zoneinfo @@ -277,6 +278,28 @@ def test_repr_rebuilds(self): class TestSavedForm: """``to_config`` / ``from_config``: the saved ``where`` mapping, unchanged on disk.""" + def test_equalities_are_saved_in_canonical_order(self): + """Order never counts in what is saved (ITL-998): two equal conditions given in + either order are saved as the same text; one column is saved as before.""" + texts = { + json.dumps(Condition.of(dict(order)).to_config()) + for order in itertools.permutations( + [("unit", 106), ("label", "a"), ("day", _DAY), ("x", 1.5)] + ) + } + + assert texts == { + '{"day": {"date": "2026-11-20"}, "label": "a", "unit": 106, "x": 1.5}' + } + assert json.dumps(Condition.of(unit=106).to_config()) == '{"unit": 106}' + + def test_a_mapping_saved_in_the_order_given_loads_equal(self): + """A file written before (keys in the order given) loads to the same condition.""" + loaded = Condition.from_config({"unit": 106, "label": "a"}) + + assert loaded == Condition.of(label="a", unit=106) + assert json.dumps(loaded.to_config()) == '{"label": "a", "unit": 106}' + def test_the_saved_form_is_the_mapping(self): """Dates, datetimes and bytes are tagged; other values are as they are.""" condition = Condition.of( @@ -308,9 +331,10 @@ def test_round_trip_through_json(self, condition): loaded = Condition.from_config(saved) assert loaded == condition - assert [type(v) for v in loaded.equalities.values()] == [ - type(v) for v in condition.equalities.values() - ] + # By column: what is saved is in canonical order, not the order given. + assert {c: type(v) for c, v in loaded.equalities.items()} == { + c: type(v) for c, v in condition.equalities.items() + } def test_an_empty_mapping_reads_as_the_empty_condition(self): """A source saved without ``where`` reads as no condition."""