diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index 7f828d483..3b5cbc933 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -61246,208 +61246,6 @@ } } ], - "./src/orcapod/types.py": [ - { - "code": "reportMissingTypeArgument", - "range": { - "startColumn": 28, - "endColumn": 39, - "lineCount": 1 - } - }, - { - "code": "reportImplicitOverride", - "range": { - "startColumn": 8, - "endColumn": 19, - "lineCount": 1 - } - }, - { - "code": "reportImplicitOverride", - "range": { - "startColumn": 8, - "endColumn": 16, - "lineCount": 1 - } - }, - { - "code": "reportImplicitOverride", - "range": { - "startColumn": 8, - "endColumn": 15, - "lineCount": 1 - } - }, - { - "code": "reportImplicitOverride", - "range": { - "startColumn": 8, - "endColumn": 16, - "lineCount": 1 - } - }, - { - "code": "reportImplicitOverride", - "range": { - "startColumn": 8, - "endColumn": 14, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 38, - "endColumn": 43, - "lineCount": 1 - } - }, - { - "code": "reportUnknownVariableType", - "range": { - "startColumn": 8, - "endColumn": 22, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 53, - "endColumn": 84, - "lineCount": 1 - } - }, - { - "code": "reportReturnType", - "range": { - "startColumn": 19, - "endColumn": 36, - "lineCount": 1 - } - }, - { - "code": "reportArgumentType", - "range": { - "startColumn": 30, - "endColumn": 35, - "lineCount": 1 - } - }, - { - "code": "reportExplicitAny", - "range": { - "startColumn": 37, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportExplicitAny", - "range": { - "startColumn": 38, - "endColumn": 41, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportAny", - "range": { - "startColumn": 34, - "endColumn": 40, - "lineCount": 1 - } - }, - { - "code": "reportImplicitStringConcatenation", - "range": { - "startColumn": 16, - "endColumn": 57, - "lineCount": 2 - } - }, - { - "code": "reportImplicitOverride", - "range": { - "startColumn": 8, - "endColumn": 15, - "lineCount": 1 - } - }, - { - "code": "reportImplicitStringConcatenation", - "range": { - "startColumn": 16, - "endColumn": 50, - "lineCount": 2 - } - }, - { - "code": "reportImplicitStringConcatenation", - "range": { - "startColumn": 16, - "endColumn": 52, - "lineCount": 2 - } - }, - { - "code": "reportImplicitStringConcatenation", - "range": { - "startColumn": 16, - "endColumn": 48, - "lineCount": 2 - } - } - ], "./src/orcapod/utils/arrow_utils.py": [ { "code": "reportExplicitAny", diff --git a/.zed/rules b/.zed/rules index c4fde9c72..277cde329 100644 --- a/.zed/rules +++ b/.zed/rules @@ -645,7 +645,8 @@ audit is `docs/dev/specs/itl-1271-order-invariance-audit.md`. ## Project layout src/orcapod/ - types.py — Schema, ColumnConfig, ContentHash + types/ — Schema, ColumnConfig, ContentHash (__init__.py); + Condition (condition.py) system_constants.py — Column prefixes and separators errors.py — InputValidationError, DuplicateTagError config.py — Config dataclass @@ -1230,6 +1231,67 @@ data. The rules: only after the read succeeded. Without key columns a row's record id is its position: a change of row order is a change; with one, only content counts (reload.same_rows(..., ordered=), decided by the caller; in doubt, order counts). +- A restriction is not an operator (developer, November 17, 2026, ITL-1218). It is attached + to a source, chooses which of its rows flow, and changes no row, schema, DAG node or + identity: content_hash, pipeline_hash, source_id, schema, system-tag column names and + every row's record id equal the unrestricted source's (a positional record id is never + renumbered). Selecting rows as part of what a pipeline computes is an operator + (SemiJoin, PolarsFilter). The conditions are one public class, orcapod.types.Condition + (defined in types/condition.py; developer, November 18, 2026): row conditions only, no limit, no source, in no hash; a + future in-pipeline filter operator is to take the same class (its identity then: ITL-1265). + Its factory Condition.of(mapping=None, /, **columns) takes where()'s arguments and does + every check that needs no table (None, a value not exactly bool/int/float/str/ + bytes/datetime/date, mapping against keyword); combined adds two and refuses a + contradiction; equality is by value, order-free, exact types, floats as Orcapod matches them + (0.0 equals -0.0, NaN equals NaN), an aware datetime by its instant (fold counts, zones do + 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 + 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 + 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 + Arrow range, no conversion) and combines it with where='s, applied by SpiralDB in the + scan. where() is _copy() then _apply_restriction() in place on the copy, the future + public copy() and apply_restriction(); other source kinds and limit() are ITL-1219. + A source states its restriction through two read-only members of SourceProtocol, + condition (the empty Condition when it reads every row) and row_limit (None + for none): RootSource answers the defaults, SpiralDBTableSource its own, and a + source over another (CachedSource, SourceProxy) answers for itself only + (developer, November 20, 2026: StreamProtocol gets them when restrictions reach + general streams, ITL-1219). Every rule that reads them is in one module, + pipeline/restrictions.py, typed, never probing a private attribute. + RunSummary records each restricted source by slot: conditions (slot to Condition), + limits (slot to limit), restricted_source_ids (every such slot), filled by one walk; + the saved job keeps where and limit in the source config. A slot's new restriction need not + match its previous one (bind does not compare the two), but bind refuses, before replacing + any binding, a bind after which two slots would read one source identity under different + restrictions (below). A job run over a restricted source feeding GroupBy, Batch or MergeJoin issues one RestrictedAggregationWarning. + A pipeline keeps one restriction (or none) per source identity (a restriction leaves the + identity unchanged), so one table restricted two ways (or with and without a restriction) in + one pipeline is refused (restrictions.require_one_restriction, over the sources the streams + read now, sources_read; nothing is remembered between checks, since a rebound slot changes + what they read) at capture, at compile, by bind before it binds and at the start of every + run (refuse_restriction_conflicts), whatever streams lead there: projections, operator + chains, streams built before the capture. A bind's walk matches the job's own slots by object + (Rebinding), never by name. RunSummary keeps one condition and one limit per slot (ITL-1293). Every restriction walk goes through a slot's bound source, + a SourceProxy's delegate and a CachedSource's source (_streams_beneath); a + DerivedSource is a root. A CachedSource + over a restricted source is refused at construction (a cache is kept under the table's + identity; developer, November 18, 2026), and so is an operator job node that caches (LOG or + REPLAY) over a restricted source (developer, November 19, 2026: its cache is kept under the + node's identity): restrictions.refuse_restricted_operator_cache(s), called where the cache mode + is attached, by bind before it binds, before a job distributes its databases, by the + upstreams setter, by execute (on the streams it is handed) and async_execute, and at + the start of job.run(), run_async() and a job node's run(), before any source is + checked or anything computed or written; a new way to run or rewire a caching operator node + calls it too (it reads the node's public cache_mode). CacheMode.OFF and function nodes + are not concerned. The refusal is for now: how an operator node logs and replays is to be + redesigned to load its cache and then apply the restriction (TODO(ITL-1219)). - Empty data → ArrowTableSource raises ValueError("Table is empty"). - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): job.run(), node.run() (state-driven, ITL-1095: a node holding a current run delivers diff --git a/CLAUDE.md b/CLAUDE.md index 45bf2ff8a..bb8806246 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -657,7 +657,8 @@ audit is `docs/dev/specs/itl-1271-order-invariance-audit.md`. ``` src/orcapod/ -├── types.py # Schema, ColumnConfig, ContentHash +├── types/ # Schema, ColumnConfig, ContentHash (__init__.py); +│ # Condition (condition.py) ├── system_constants.py # Column prefixes and separators ├── errors.py # InputValidationError, DuplicateTagError ├── config.py # Config dataclass @@ -1020,10 +1021,10 @@ current data context are the current entries. ### Schema types and ColumnConfig -`Schema` (`types.py`) — immutable `Mapping[str, DataType]` with `optional_fields` support. +`Schema` (`types/__init__.py`) — immutable `Mapping[str, DataType]` with `optional_fields` support. `output_schema()` always returns `(tag_schema, data_schema)` as a tuple of Schemas. -`ColumnConfig` (`types.py`) — frozen dataclass controlling which column groups are included. +`ColumnConfig` (`types/__init__.py`) — frozen dataclass controlling which column groups are included. Fields: `meta`, `context`, `source`, `system_tags`, `content_hash`, `sort_by_tags`. Normalize via `ColumnConfig.handle_config(columns, all_info)` at the top of `output_schema()` and `as_table()` methods. `all_info=True` sets everything to True. @@ -1274,6 +1275,67 @@ data. The rules: only after the read succeeded. Without key columns a row's record id is its position: a change of row order is a change; with one, only content counts (`reload.same_rows(..., ordered=)`, decided by the caller; in doubt, order counts). +- A restriction is not an operator (developer, November 17, 2026, ITL-1218). It is attached + to a source, chooses which of its rows flow, and changes no row, schema, DAG node or + identity: `content_hash`, `pipeline_hash`, `source_id`, schema, system-tag column names and + every row's record id equal the unrestricted source's (a positional record id is never + renumbered). Selecting rows as part of what a pipeline computes is an operator + (`SemiJoin`, `PolarsFilter`). The conditions are one public class, `orcapod.types.Condition` + (defined in `types/condition.py`; developer, November 18, 2026): row conditions only, no limit, no source, in no hash; a + future in-pipeline filter operator is to take the same class (its identity then: ITL-1265). + Its factory `Condition.of(mapping=None, /, **columns)` takes `where()`'s arguments and does + every check that needs no table (`None`, a value not exactly `bool`/`int`/`float`/`str`/ + `bytes`/`datetime`/`date`, mapping against keyword); `combined` adds two and refuses a + contradiction; equality is by value, order-free, exact types, floats as Orcapod matches them + (0.0 equals -0.0, NaN equals NaN), an aware datetime by its instant (`fold` counts, zones do + 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 + `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 + 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 + Arrow range, no conversion) and combines it with `where=`'s, applied by SpiralDB in the + scan. `where()` is `_copy()` then `_apply_restriction()` in place on the copy, the future + public `copy()` and `apply_restriction()`; other source kinds and `limit()` are ITL-1219. + A source states its restriction through two read-only members of `SourceProtocol`, + `condition` (the empty `Condition` when it reads every row) and `row_limit` (`None` + for none): `RootSource` answers the defaults, `SpiralDBTableSource` its own, and a + source over another (`CachedSource`, `SourceProxy`) answers for itself only + (developer, November 20, 2026: `StreamProtocol` gets them when restrictions reach + general streams, ITL-1219). Every rule that reads them is in one module, + `pipeline/restrictions.py`, typed, never probing a private attribute. + `RunSummary` records each restricted source by slot: `conditions` (slot to `Condition`), + `limits` (slot to limit), `restricted_source_ids` (every such slot), filled by one walk; + the saved job keeps `where` and `limit` in the source config. A slot's new restriction need not + match its previous one (bind does not compare the two), but `bind` refuses, before replacing + any binding, a bind after which two slots would read one source identity under different + restrictions (below). A job run over a restricted source feeding `GroupBy`, `Batch` or `MergeJoin` issues one `RestrictedAggregationWarning`. + A pipeline keeps one restriction (or none) per source identity (a restriction leaves the + identity unchanged), so one table restricted two ways (or with and without a restriction) in + one pipeline is refused (`restrictions.require_one_restriction`, over the sources the streams + read now, `sources_read`; nothing is remembered between checks, since a rebound slot changes + what they read) at capture, at compile, by `bind` before it binds and at the start of every + run (`refuse_restriction_conflicts`), whatever streams lead there: projections, operator + chains, streams built before the capture. A bind's walk matches the job's own slots by object + (`Rebinding`), never by name. `RunSummary` keeps one condition and one limit per slot (ITL-1293). Every restriction walk goes through a slot's bound source, + a `SourceProxy`'s delegate and a `CachedSource`'s source (`_streams_beneath`); a + `DerivedSource` is a root. A `CachedSource` + over a restricted source is refused at construction (a cache is kept under the table's + identity; developer, November 18, 2026), and so is an operator job node that caches (`LOG` or + `REPLAY`) over a restricted source (developer, November 19, 2026: its cache is kept under the + node's identity): `restrictions.refuse_restricted_operator_cache(s)`, called where the cache mode + is attached, by `bind` before it binds, before a job distributes its databases, by the + `upstreams` setter, by `execute` (on the streams it is handed) and `async_execute`, and at + the start of `job.run()`, `run_async()` and a job node's `run()`, before any source is + checked or anything computed or written; a new way to run or rewire a caching operator node + calls it too (it reads the node's public `cache_mode`). `CacheMode.OFF` and function nodes + are not concerned. The refusal is for now: how an operator node logs and replays is to be + redesigned to load its cache and then apply the restriction (`TODO(ITL-1219)`). - Empty data → `ArrowTableSource` raises `ValueError("Table is empty")`. - A side-effect job node delivers only when it runs (developer, November 13, 2026, ITL-1091): `job.run()`, `node.run()` (state-driven, ITL-1095: a node holding a current run delivers diff --git a/changelog.d/ITL-1218.md b/changelog.d/ITL-1218.md new file mode 100644 index 000000000..3330c9480 --- /dev/null +++ b/changelog.d/ITL-1218.md @@ -0,0 +1,53 @@ +### Added + +- `SpiralDBTableSource.where(mapping=None, /, **columns)` returns a new source on the same + table that reads only the rows in which every named column equals its value. It is a + restriction, not an operator: the new source has the same `source_id`, `content_hash`, + `pipeline_hash`, schema, system-tag columns and record IDs as the unrestricted source, and + adds no node to a pipeline. Its conditions are added to those given with `where=` + (one mechanism, applied in the SpiralDB scan); a conflicting value for a column is refused. + Other source kinds do not have `where()` yet. A pipeline holds one source per identity, + so one table read with two different restrictions in one pipeline raises `ValueError`: + when the pipeline is built or compiled, when `bind` would bind such a source, or when a + run starts. + A `CachedSource` (or `source.cached(...)`) over a restricted source raises `ValueError`: + a cache is kept under the table's identity, which a restriction is not part of. So does + an operator node that caches (`CacheMode.LOG` or `CacheMode.REPLAY`) when a source feeding + it is restricted, whichever is set first: when the cache mode is set, when `bind` binds the + source, when its `upstreams` are replaced, when `execute` or `async_execute` is called, or + when a run starts, before anything is read or written. `CacheMode.OFF` and + function nodes are not concerned. +- `orcapod.types.Condition`: equality conditions on named columns, all of which must hold. + `Condition.of(mapping=None, /, **columns)` builds one from the arguments `where()` takes; + `combined` adds two and refuses a column required to equal two values; two conditions are + equal when they require the same columns to equal the same values, in any order (values of + different types differ; `0.0` equals `-0.0`; an aware `datetime` is its instant, so one + instant in two zones is one value and the two times of a daylight-saving overlap are two); + `text()` / `str` show it. That equality decides whether two restrictions are one; which + rows a condition selects is the table system's own equality (for a float column, whether a + NaN selects NaN rows and whether `0.0` selects `-0.0` rows is SpiralDB's). A NaN or + infinite value is saved as `{"float": "nan"}`, `{"float": "inf"}` or `{"float": "-inf"}`. + It has a Python hash (a dictionary key, a set member) and never enters an Orcapod source or + pipeline hash. `where()` and `where=` accept a `Condition` as well as a mapping. +- `RunSummary.conditions` (slot to `Condition`), `RunSummary.limits` (slot to limit) and + `RunSummary.restricted_source_ids` (slot to source id): each restricted source of a run, by + slot; shown in the summary. A slot keeps one entry: a slot bound to a stream over two + restricted tables reports one condition and one limit, those of the first table found + (ITL-1293). +- `RestrictedAggregationWarning`: one per job run when a restricted source feeds a + `GroupBy`, `Batch` or `MergeJoin`. +- `SourceProtocol.condition` and `SourceProtocol.row_limit`: read-only properties that + state which rows a source reads. `condition` is the empty `Condition` and `row_limit` is + `None` for every source except a restricted `SpiralDBTableSource`. A `CachedSource` or a + `SourceProxy` answers for itself, not for the source it reads. +- `OperatorJobNode.cache_mode`: the node's cache mode (`CacheMode.OFF` until + `attach_databases` sets another). + +### Changed + +- `SpiralDBTableSource(where=...)` checks each value against its column: the value must be + exactly of the column's Python type and fit its Arrow type (no conversion: a NumPy scalar + or a date string is refused with `TypeError`), and `None` is refused with `ValueError`. +- `orcapod.types` is a package. `Condition` is defined in `orcapod.types.condition`, and + everything else stays in `orcapod.types`. Every `from orcapod.types import ...` works as + before, and no hash, type identity or saved form changes. diff --git a/docs/api/index.md b/docs/api/index.md index 58e69fdda..849c8de10 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -25,4 +25,4 @@ Everything else lives in subpackages: | [`orcapod.databases`](databases.md) | Persistent storage backends for computation results | | [`orcapod.nodes`](nodes.md) | Pipeline graph elements, including the DB-backed job nodes | | [`orcapod.streams`](streams.md) | Immutable (Tag, Data) sequences backed by PyArrow tables | -| [`orcapod.types`](types.md) | Core type definitions: `Schema`, `ColumnConfig`, `ContentHash` | +| [`orcapod.types`](types.md) | Core type definitions: `Schema`, `ColumnConfig`, `ContentHash`, `Condition` | diff --git a/docs/api/types.md b/docs/api/types.md index 62b736584..aea93282d 100644 --- a/docs/api/types.md +++ b/docs/api/types.md @@ -13,3 +13,5 @@ Core type definitions used throughout Orcapod. ::: orcapod.types.ColumnConfig ::: orcapod.types.ContentHash + +::: orcapod.types.Condition diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index de18cabc6..125cd09db 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -798,6 +798,12 @@ output, and it then reads as a zero-row table, as before the first run, until th An operator node attached in `CacheMode.REPLAY` does not compute: its run replays the rows stored under its key by `CacheMode.LOG` runs, every logged run of that key, not only the latest; before its run it shows nothing, like every node (a narrower replay is ITL-1098). +An operator node that caches (`CacheMode.LOG` or `CacheMode.REPLAY`) cannot read a restricted +source (one restricted with `where` or `limit=`; see +[Restricting a source versus filtering in the pipeline](sources.md#restricting-a-source-versus-filtering-in-the-pipeline)): +its cache is kept under the node's identity, which a restriction is not part of, so it is +refused with `ValueError` before anything is read or written, and no log is ever written from +a restricted read. `CacheMode.OFF` is not concerned. ### When the database cannot be written diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 109979963..0e614235f 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -262,7 +262,9 @@ print(first.row_count_estimate) # rows in the whole table, without reading any ``` - `limit=n` reads the first `n` rows in key order. -- `where={column: value, ...}` reads the rows in which every named column equals its value. +- `where={column: value, ...}` reads the rows in which every named column equals its value + (`source.where(...)` adds conditions to a built source; 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 run finds a newer one (see [What a source does at a run](#what-a-source-does-at-a-run)): @@ -300,6 +302,156 @@ consequence: with a shared store, reading a job node's stored records back pipeline has read from that table, not only the rows of the latest restriction. The rows sent downstream during a run are only the rows that run read. +#### Restricting a source versus filtering in the pipeline + +`source.where(column=value, ...)` returns a new source on the same table that reads only the +rows in which every named column equals its value. Several conditions can be given in one +call, as keywords or as a mapping, or across chained calls: +`events.where(unit_id=106, session_index=2)` and +`events.where(unit_id=106).where(session_index=2)` are the same restriction, reading the +same rows. The conditions are a `Condition` (`orcapod.types`): `where(...)` builds one with +`Condition.of(...)`, which takes the same arguments, and a `Condition` built beforehand can be +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: + +- An operator (`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 + else than one without, and its nodes have other hashes and other stored tables. +- A restriction is attached to the source. It chooses which of the source's rows flow and + changes nothing else: the restricted source has the same `source_id`, `content_hash`, + `pipeline_hash`, schema and system-tag columns as the unrestricted one, and every row it + reads is a row of the table with every column, record ID included, as the unrestricted + source reads it. With `limit=`, the conditions apply before the limit, so a restricted read + with a limit is not a part of an unrestricted read with the same limit; each matching row + still keeps its record ID. It adds no node, so a job bound to a restricted source is the + same job, run over fewer rows. + +Use a restriction to work on part of a table (one subject, one session) with the pipeline you +will later run on all of it: results computed under the restriction are stored under the same +identities and reused by the full run. Use an operator when selecting rows is part of what +the pipeline computes. Restrict on tag (key) columns where you can; a condition on a data +column is allowed. + + +```python +events = SpiralDBTableSource("my-project-123456", "spike_event", source_id="spikes") +one_unit = events.where(unit_id=106) # or events.where({"unit_id": 106}) +one_session = one_unit.where(session_index=2) # conditions add up +same_session = events.where(unit_id=106, session_index=2) # both in one call +print(one_session.condition) +# unit_id=106, session_index=2 +print(one_session.row_limit) +# None + +assert same_session.to_config() == one_session.to_config() +assert one_unit.content_hash() == events.content_hash() +job.bind(sources={"spikes": one_unit}) # the slot the unrestricted source fills +summary = job.run() +print(summary.conditions) +# {'spikes': Condition.of({'unit_id': 106})} +print(summary.restricted_source_ids) +# {'spikes': 'spikes'} +``` + +(This sample needs a SpiralDB project, so it is not run with the documentation; `job` is a +job built over `events`, whose slot is named by the source id.) + +A date or a time written as text is converted explicitly, with the function of its column's +type: `date.fromisoformat` for a date column, `datetime.fromisoformat` for a timestamp +column, with an offset (an aware value) for a column with a time zone. + +```python +import datetime as dt + +from orcapod.types import Condition + +day = dt.date.fromisoformat("2026-11-20") # a date column +started = dt.datetime.fromisoformat("2026-11-20T09:30:00") # a timestamp, no zone +recorded = dt.datetime.fromisoformat("2026-11-20T09:30:00+00:00") # a zoned timestamp +print(Condition.of(day=day, started=started, recorded=recorded)) +# day=datetime.date(2026, 11, 20), started=datetime.datetime(2026, 11, 20, 9, 30), recorded=datetime.datetime(2026, 11, 20, 9, 30, tzinfo=datetime.timezone.utc) +``` + +- **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 + `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. +- **No conversion.** A value must be exactly of its column's Python type: an `int` for an + integer column (not `True`, not `1.0`, not a NumPy scalar: use `.item()`), a `float` for a + float column, a `datetime.date` for a date column and a `datetime.datetime` for a timestamp + column (not a string; see below), and it must fit the column's Arrow type. A timestamp + column with a time zone takes an aware `datetime`, one without a zone a naive `datetime`. + Anything else raises `TypeError`, naming the column and both types. Columns of other types + (lists, structs) take no condition. +- **The table system's equality.** Each condition is sent to SpiralDB as `column == value`, + and which rows it selects is SpiralDB's own equality, not Orcapod's. For a float column, + whether a NaN value selects the NaN rows and whether `0.0` selects the `-0.0` rows is + decided by SpiralDB; under the usual floating-point rule a NaN equals nothing, so such a + condition may select no row. To select rows by such values as Orcapod matches them, filter + 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. +- **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 + `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 + restrictions are one restriction (for the one-restriction rule above); it does not decide + which rows a source returns. + `str(condition)` (or `condition.text()`) reads `unit_id=106, session_index=2`, and + `condition.equalities` maps each column to its value. A `Condition` has a Python hash, + consistent with that equality, so it can be a dictionary key or a set member; it never + enters an Orcapod source or pipeline hash. +- **Recorded.** `RunSummary.conditions` maps the slot of each source read under a condition + to its `Condition`, `RunSummary.limits` the slot of each source read with a `limit=` to the + limit, and `RunSummary.restricted_source_ids` every such slot to its source id; the + summary shows them (`spikes (spikes): where unit_id=106, limit 3`). A saved job records them in + the source's config, and a loaded job reads with them. A slot's new restriction need + not match its previous one: a restricted source fits the slot of the unrestricted one, and + `bind` does not compare the two. But a bind after which two slots would read one source + identity under different restrictions is refused before any binding is replaced (one + restriction per table, above). A slot keeps one entry: a slot bound to a stream over two + restricted tables (a `semi_join` of two restricted sources) reports one condition and one + limit, those of the first table found (a known limit, ITL-1293), although every check reads + both. +- **No cache over a restriction.** `CachedSource` (and `source.cached(...)`) refuses a + restricted source with `ValueError`, naming the restriction: a cache keeps the table's rows + under the table's identity, which a restriction is not part of, so a restricted read would + be read back as the whole table by every cache of it. Cache the unrestricted source, or read + without a cache. For the same reason an operator node that caches (`CacheMode.LOG` or + `CacheMode.REPLAY`) is refused when a source feeding it is restricted: its cache is kept + under the node's identity, so a log written from a restricted read would be replayed for + another restriction or none. The `ValueError` names the node and each restriction, and is + raised when both are known, before anything is read or written: when the cache mode is set + over a restricted source, when `bind` binds a restricted source under a caching node, or + else when a run starts. Use `CacheMode.OFF` there, or read the unrestricted source. A + function node stores its results row by row and is not concerned. +- **Under an aggregation.** A `GroupBy`, `Batch` or `MergeJoin` below a restricted source + builds its groups from the rows the restriction lets through. That is allowed (each + aggregated row lists its members), and a job run issues one + `RestrictedAggregationWarning` naming the source and the step. +- **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. + **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 on, and the job's nodes below it run. The added rows are new keys, the only rows computed; diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 2b6da1705..4913d8d67 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -281,7 +281,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Polars value hash | descriptor, `\0`, starfix digest called directly (a step of this algorithm) | SHA-256, `polars_dataframe_v1` / `polars_series_v1` | Polars value hash | `logical_types/polars_type.py:_digest`, `logical_types/polars_type.py:_values_digest` | | Polars expression hash | the expression's canonical tree | SHA-256 of canonical JSON, `polars_expr_v1` | `PolarsFilter` identity | `hashing/semantic_hashing/polars_expr.py:polars_expr_content_hash` | | value handlers with an ignore list | wrap the value digests above | the type's label | top level, nested, Arrow cell | `logical_types/ignore_list.py:IgnoreListHandler.handle`, `logical_types/ignore_list.py:IgnoreListHandler.hash_ignoring` | -| parse a stored hash | `"